diff --git a/index.js b/index.js index 31e3124..85be02f 100644 --- a/index.js +++ b/index.js @@ -80,7 +80,8 @@ Blockly.Msg["VARIABLES_SET"] = "変数 %1 を %2 にする"; Blockly.Msg["LOGIC_BOOLEAN_FALSE"] = "偽"; Blockly.Msg["LOGIC_BOOLEAN_TOOLTIP"] = "真 または 偽 を返します。"; Blockly.Msg["LOGIC_BOOLEAN_TRUE"] = "真"; -// ローカライズ対応の準備 + +// ローカライズ対応しといた方がいいかと思ってやってみたけど面倒になってきた Blockly.Msg["UGJ_CONTROL_FOR_TITLE"] = "%1 %2 を %3 から %4 まで %5 ずつ %6 %7 %8"; Blockly.Msg["UGJ_CONTROL_FOR_INDEX"] = "番号"; Blockly.Msg["UGJ_CONTROL_FOR_INCREASE"] = "増やして"; @@ -183,6 +184,8 @@ Blockly.Msg["UGJ_DECTOHEX_TOOLTIP"] = "10進数を16進数に変換します。" Blockly.Msg["UGJ_CANVAS_INIT_TITLE"] = "キャンバスを表示"; Blockly.Msg["UGJ_CANVAS_INIT_TOOLTIP"] = "キャンバスを表示し、使用できるようにします。"; +// Blockly.Msg["UGJ_FACEAPI_TITLE"] = "TensorFlowによる顔検出: %1 ランドマークを検出 %2 %3"; +// Blockly.Msg["UGJ_FACEAPI_TOOLTIP"] = "TensorFlow とFaceAPI をロードし、顔検出をできるようにします。"; Blockly.Msg["UGJ_SLEEP_TITLE"] = "%1 秒待つ"; Blockly.Msg["UGJ_SLEEP_TOOLTIP"] = "指定した秒数だけ処理を中断します。"; diff --git a/index_elutil.js b/index_elutil.js index 4e8234e..cd34d61 100644 --- a/index_elutil.js +++ b/index_elutil.js @@ -4,7 +4,6 @@ // 定数 const ugj_const = { - // doc_root: process.env["HOME"] + '/Documents', app_name: 'ocoge', mascot_path: './img/', mascot_defname: 'tamachee.png', @@ -13,7 +12,7 @@ const ugj_const = { localStorage_fname: 'ocoge.json', error_ja_all: 'エラーが発生しました。\n『おこげ倶楽部』までお問い合わせください。', pig: 'pigpio', - lg: 'lgpio', // lgpioがハードウェアPWMを実装してRPiOSにプリインストールされるようになったら切り替え予定 + lg: 'lgpio', // 対応未定 i2c_defbus: '6', // 文字列リテラルで指定 dev_hash: '4e9205f9b7e571bec1aa52ab7871f420684fcf96149672a4d550a95863d6b072' } @@ -340,6 +339,9 @@ if (!is_el) { case '@ocogeclub/amg8833': block = '赤外線アレイセンサ'; break; + case '@ocogeclub/paj7620': + block = 'ジェスチャーセンサー'; + break; case 'fs': block = 'ファイル'; break; diff --git a/local_modules/@ocogeclub/amg8833/AMG8833.js b/local_modules/@ocogeclub/amg8833/AMG8833.js index 46545f3..406cc3f 100644 --- a/local_modules/@ocogeclub/amg8833/AMG8833.js +++ b/local_modules/@ocogeclub/amg8833/AMG8833.js @@ -4,23 +4,23 @@ const pig = require('@ocogeclub/pigpio'); let pi = -1; let i2c_hand = -1; -exports.init = (i2c_bus, i2c_addr) => { - if (pi < 0) pi = pig._pigpio_start('', ''); - if (i2c_hand < 0) pig._i2c_close(pi, i2c_hand); - i2c_hand = pig._i2c_open(pi, i2c_bus, i2c_addr); - pig._i2c_write_byte_data(pi, i2c_hand, 0x00, 0x00); //Normal mode - pig._i2c_write_byte_data(pi, i2c_hand, 0x02, 0x00); //10FPS +exports.init = async (i2c_bus, i2c_addr) => { + if (pi < 0) pi = await pig._pigpio_start('', ''); + if (i2c_hand < 0) await pig._i2c_close(pi, i2c_hand); + i2c_hand = await pig._i2c_open(pi, i2c_bus, i2c_addr); + await pig._i2c_write_byte_data(pi, i2c_hand, 0x00, 0x00); //Normal mode + await pig._i2c_write_byte_data(pi, i2c_hand, 0x02, 0x00); //10FPS } -exports.read_thermistor = () => { - let temp = pig._i2c_read_word_data(pi, i2c_hand, 0x0e); +exports.read_thermistor = async () => { + let temp = await pig._i2c_read_word_data(pi, i2c_hand, 0x0e); return temp * 0.0625; } -exports.read_temp_array = () => { +exports.read_temp_array = async () => { let linedata = []; for (let i = 0; i < 8; i++) { - let data = pig._i2c_read_i2c_block_data(pi, i2c_hand, 0x80 + 0x10 * i, 16); + let data = await pig._i2c_read_i2c_block_data(pi, i2c_hand, 0x80 + 0x10 * i, 16); let oneline = []; for (let j = 0; j < 8; j++) { oneline.push(((data[2 * j + 1] & 0x07) * 256 + data[2 * j]) * 0.25); @@ -30,13 +30,13 @@ exports.read_temp_array = () => { return linedata; } -exports.stop = () => { +exports.stop = async () => { if (i2c_hand >= 0) { - pig._i2c_close(pi, i2c_hand); + await pig._i2c_close(pi, i2c_hand); i2c_hand = -1; } if (pi >= 0) { - pig._pigpio_stop(pi); + await pig._pigpio_stop(pi); pi = -1; } } diff --git a/local_modules/@ocogeclub/bme280/BME280.js b/local_modules/@ocogeclub/bme280/BME280.js index 47a3b2c..0a186a1 100644 --- a/local_modules/@ocogeclub/bme280/BME280.js +++ b/local_modules/@ocogeclub/bme280/BME280.js @@ -41,24 +41,24 @@ this.REGISTER_PRESSURE_DATA = 0xF7; this.REGISTER_TEMP_DATA = 0xFA; this.REGISTER_HUMIDITY_DATA = 0xFD; -exports.init = (options) => { +exports.init = async (options) => { this.pig = require('@ocogeclub/pigpio') // console.log('pig= ' + this.pig) - this.pi = this.pig._pigpio_start('', ''); + this.pi = await this.pig._pigpio_start('', ''); // console.log('pi= ' + this.pi) // this.pi = require('@ocogeclub/lgpio'); this.i2cBusNo = (options && options.hasOwnProperty('i2cBusNo')) ? options.i2cBusNo : 1; this.i2cAddress = (options && options.hasOwnProperty('i2cAddress')) ? options.i2cAddress : this.BME280_DEFAULT_I2C_ADDRESS(); - this.i2cHand = this.pig._i2c_open(this.pi, this.i2cBusNo, this.i2cAddress); + this.i2cHand = await this.pig._i2c_open(this.pi, this.i2cBusNo, this.i2cAddress); // console.log('i2cHand= ' + this.i2cHand) // this.i2cHand = this.pi._i2c_open(this.i2cBusNo, this.i2cAddress); let r; - r = this.pig._i2c_write_byte_data(this.pi, this.i2cHand, this.REGISTER_CHIPID, 0); + r = await this.pig._i2c_write_byte_data(this.pi, this.i2cHand, this.REGISTER_CHIPID, 0); // r = this.pi._i2c_write_byte_data(this.i2cHand, this.REGISTER_CHIPID, 0); if (r < 0) return r; - let chipId = this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_CHIPID); + let chipId = await this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_CHIPID); // let chipId = this.pi._i2c_read_byte_data(this.i2cHand, this.REGISTER_CHIPID); if (chipId !== this.CHIP_ID_BME280() && chipId !== this.CHIP_ID1_BMP280() && @@ -67,18 +67,18 @@ exports.init = (options) => { return `Unexpected BMx280 chip ID: 0x${chipId.toString(16).toUpperCase()}`; } // console.log(`Found BMx280 chip ID 0x${chipId.toString(16).toUpperCase()} on bus i2c-${this.i2cBusNo}, address 0x${this.i2cAddress.toString(16).toUpperCase()}`); - this.loadCalibration((err) => { + await this.loadCalibration(async (err) => { if (err) { return err; } // Humidity 16x oversampling // - let r = this.pig._i2c_write_byte_data(this.pi, this.i2cHand, this.REGISTER_CONTROL_HUM, 0b00000101); + let r = await this.pig._i2c_write_byte_data(this.pi, this.i2cHand, this.REGISTER_CONTROL_HUM, 0b00000101); // let r = this.pi._i2c_write_byte_data(this.i2cHand, this.REGISTER_CONTROL_HUM, 0b00000101); if (r < 0) return `Humidity 16x oversampling error: ${r}`; // Temperture/pressure 16x oversampling, normal mode // - r = this.pig._i2c_write_byte_data(this.pi, this.i2cHand, this.REGISTER_CONTROL, 0b10110111); + r = await this.pig._i2c_write_byte_data(this.pi, this.i2cHand, this.REGISTER_CONTROL, 0b10110111); // r = this.pi._i2c_write_byte_data(this.i2cHand, this.REGISTER_CONTROL, 0b10110111); if (r < 0) return `Temperture/pressure 16x oversampling error: ${r}`; @@ -90,9 +90,9 @@ exports.init = (options) => { // // Perform a power-on reset procedure. You will need to call init() following a reset() // -exports.reset = () => { +exports.reset = async () => { const POWER_ON_RESET_CMD = 0xB6; - let r = this.pig._i2c_write_byte_data(this.pi, this.i2cHand, this.REGISTER_RESET, POWER_ON_RESET_CMD); + let r = await this.pig._i2c_write_byte_data(this.pi, this.i2cHand, this.REGISTER_RESET, POWER_ON_RESET_CMD); // let r = this.pi._i2c_write_byte_data(this.i2cHand, this.REGISTER_RESET, POWER_ON_RESET_CMD); if (r < 0) return `cannot power-on reset: ${r}`; else return 0; @@ -102,24 +102,24 @@ exports.reset = () => { // // Cancels the sensor and releases resources. // -exports.cancel = () => { +exports.cancel = async () => { if (this.i2cHand >= 0) { - this.pig._i2c_close(this.pi, this.i2cHand); + await this.pig._i2c_close(this.pi, this.i2cHand); // this.pi._i2c_close(this.i2cHand); this.i2cHand = null; - this.pig._pigpio_stop(this.pi); + await this.pig._pigpio_stop(this.pi); this.pi = null; } } -exports.readSensorData = () => { +exports.readSensorData = async () => { if (!this.cal) { return 'You must first call bme280.init()'; } // Grab temperature, humidity, and pressure in a single read // - let buffer = this.pig._i2c_read_i2c_block_data(this.pi, this.i2cHand, this.REGISTER_PRESSURE_DATA, 8); + let buffer = await this.pig._i2c_read_i2c_block_data(this.pi, this.i2cHand, this.REGISTER_PRESSURE_DATA, 8); // let buffer = this.pi._i2c_read_i2c_block_data(this.i2cHand, this.REGISTER_PRESSURE_DATA, 8); if (!buffer) return `couldn't grab data`; // Temperature (temperature first since we need t_fine for pressure and humidity) @@ -171,18 +171,18 @@ exports.readSensorData = () => { }; } -exports.loadCalibration = (callback) => { - let buffer = this.pig._i2c_read_i2c_block_data(this.pi, this.i2cHand, this.REGISTER_DIG_T1, 24); +exports.loadCalibration = async (callback) => { + let buffer = await this.pig._i2c_read_i2c_block_data(this.pi, this.i2cHand, this.REGISTER_DIG_T1, 24); // let buffer = this.pi._i2c_read_i2c_block_data(this.i2cHand, this.REGISTER_DIG_T1, 24); // for (let i = 0; i < 24; i++) console.log(parseInt(buffer[i], 16)); if (buffer) { - let h1 = this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H1); - let h2 = this.pig._i2c_read_word_data(this.pi, this.i2cHand, this.REGISTER_DIG_H2); - let h3 = this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H3); - let h4 = this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H4); - let h5 = this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H5); - let h5_1 = this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H5 + 1); - let h6 = this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H6); + let h1 = await this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H1); + let h2 = await this.pig._i2c_read_word_data(this.pi, this.i2cHand, this.REGISTER_DIG_H2); + let h3 = await this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H3); + let h4 = await this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H4); + let h5 = await this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H5); + let h5_1 = await this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H5 + 1); + let h6 = await this.pig._i2c_read_byte_data(this.pi, this.i2cHand, this.REGISTER_DIG_H6); // let h1 = this.pi._i2c_read_byte_data(this.i2cHand, this.REGISTER_DIG_H1); // let h2 = this.pi._i2c_read_word_data(this.i2cHand, this.REGISTER_DIG_H2); // let h3 = this.pi._i2c_read_byte_data(this.i2cHand, this.REGISTER_DIG_H3); @@ -215,7 +215,7 @@ exports.loadCalibration = (callback) => { }; // console.log('BME280 cal = ' + JSON.stringify(this.cal, null, 2)); - callback(); + await callback(); } } diff --git a/local_modules/@ocogeclub/paj7620/PAJ7620.js b/local_modules/@ocogeclub/paj7620/PAJ7620.js index 9ed92af..5b8dffd 100644 --- a/local_modules/@ocogeclub/paj7620/PAJ7620.js +++ b/local_modules/@ocogeclub/paj7620/PAJ7620.js @@ -317,18 +317,20 @@ let pi = -1; let i2c_hand = -1; //Initialize the sensors exports.init = async (i2c_bus, i2c_addr) => { - if (pi < 0) pi = pig._pigpio_start('', ''); - if (i2c_hand < 0) pig._i2c_close(pi, i2c_hand); - i2c_hand = pig._i2c_open(pi, i2c_bus, i2c_addr); + if (pi < 0) pi = await pig._pigpio_start('', ''); + if (i2c_hand < 0) await pig._i2c_close(pi, i2c_hand); + i2c_hand = await pig._i2c_open(pi, i2c_bus, i2c_addr); + if (debug) + console.log("pi" + pi + "i2c_hand" + i2c_hand); await sleep(.001); - paj7620SelectBank(BANK0); - paj7620SelectBank(BANK0); + await paj7620SelectBank(BANK0); + await paj7620SelectBank(BANK0); - let data0 = paj7620ReadReg(0, 1)[0]; - let data1 = paj7620ReadReg(1, 1)[0]; + let data0 = (await paj7620ReadReg(0, 1))[0]; + let data1 = (await paj7620ReadReg(1, 1))[0]; if (debug) - console.log("data0" + data0 + "data1" + data1); + console.log("data0:" + data0 + ", data1:" + data1); if (data0 != 0x20) //or data1 <> 0x76 console.log("Error with sensor"); //return 0xff @@ -336,27 +338,27 @@ exports.init = async (i2c_bus, i2c_addr) => { console.log("wake-up finish."); for (let i = 0; i < initRegisterArray.length; i += 1) - paj7620WriteReg(initRegisterArray[i][0], initRegisterArray[i][1]); + await paj7620WriteReg(initRegisterArray[i][0], initRegisterArray[i][1]); - paj7620SelectBank(BANK0); + await paj7620SelectBank(BANK0); console.log("Paj7620 initialize register finished."); } // Write a byte to a register on the Gesture sensor -const paj7620WriteReg = (addr, cmd) => - pig._i2c_write_word_data(pi, i2c_hand, addr, cmd); +const paj7620WriteReg = async (addr, cmd) => + await pig._i2c_write_word_data(pi, i2c_hand, addr, cmd); //Select a register bank on the Gesture Sensor -const paj7620SelectBank = bank => { +const paj7620SelectBank = async bank => { if (bank == BANK0) - paj7620WriteReg(PAJ7620_REGITER_BANK_SEL, PAJ7620_BANK0); + await paj7620WriteReg(PAJ7620_REGITER_BANK_SEL, PAJ7620_BANK0); } //Read a block of bytes of length "qty" starting at address "addr" from the Gesture sensor -const paj7620ReadReg = (addr, qty) => { - return pig._i2c_read_i2c_block_data(pi, i2c_hand, addr, qty); +const paj7620ReadReg = async (addr, qty) => { + return await pig._i2c_read_i2c_block_data(pi, i2c_hand, addr, qty); } //Return a vlaue from the gestire sensor which can be used in a program @@ -372,10 +374,10 @@ const paj7620ReadReg = (addr, qty) => { // 9:wave exports.return_gesture = async () => { - let data = paj7620ReadReg(0x43, 1)[0]; + let data = (await paj7620ReadReg(0x43, 1))[0]; if (data == GES_RIGHT_FLAG) { await sleep(GES_ENTRY_TIME); - data = paj7620ReadReg(0x43, 1)[0]; + data = (await paj7620ReadReg(0x43, 1))[0]; if (data == GES_FORWARD_FLAG) { return 1; // await sleep(GES_QUIT_TIME); @@ -390,7 +392,7 @@ exports.return_gesture = async () => { else if (data == GES_LEFT_FLAG) { await sleep(GES_ENTRY_TIME); - data = paj7620ReadReg(0x43, 1)[0]; + data = (await paj7620ReadReg(0x43, 1))[0]; if (data == GES_FORWARD_FLAG) { return 1; // await sleep(GES_QUIT_TIME); @@ -405,7 +407,7 @@ exports.return_gesture = async () => { else if (data == GES_UP_FLAG) { await sleep(GES_ENTRY_TIME); - data = paj7620ReadReg(0x43, 1)[0]; + data = (await paj7620ReadReg(0x43, 1))[0]; if (data == GES_FORWARD_FLAG) { return 1; // await sleep(GES_QUIT_TIME); @@ -420,7 +422,7 @@ exports.return_gesture = async () => { else if (data == GES_DOWN_FLAG) { await sleep(GES_ENTRY_TIME); - data = paj7620ReadReg(0x43, 1)[0]; + data = (await paj7620ReadReg(0x43, 1))[0]; if (data == GES_FORWARD_FLAG) { return 1; // await sleep(GES_QUIT_TIME); @@ -449,20 +451,20 @@ exports.return_gesture = async () => { return 8; else { - let data1 = paj7620ReadReg(0x44, 1)[0]; + let data1 = (await paj7620ReadReg(0x44, 1))[0]; if (data1 == GES_WAVE_FLAG) return 9; } return 0; } -exports.stop = () => { +exports.stop = async () => { if (i2c_hand >= 0) { - pig._i2c_close(pi, i2c_hand); + await pig._i2c_close(pi, i2c_hand); i2c_hand = -1; } if (pi >= 0) { - pig._pigpio_stop(pi); + await pig._pigpio_stop(pi); pi = -1; } } diff --git a/local_modules/@ocogeclub/pigpio/index.js b/local_modules/@ocogeclub/pigpio/index.js index b21642c..b92612b 100644 --- a/local_modules/@ocogeclub/pigpio/index.js +++ b/local_modules/@ocogeclub/pigpio/index.js @@ -13,82 +13,82 @@ module.exports.PULL_NONE = 0; let pi = -1; let i2c_hand = -1; let ser_hand = -1; -module.exports.gpio_open = () => { - if (pi < 0) pi = module.exports._pigpio_start('', ''); +module.exports.gpio_open = async () => { + if (pi < 0) pi = await module.exports._pigpio_start('', ''); return pi; } -module.exports.gpio_close = () => { - if (pi >= 0) module.exports._pigpio_stop(pi); +module.exports.gpio_close = async () => { + if (pi >= 0) await module.exports._pigpio_stop(pi); pi = -1; } -module.exports.gpio_set_output = gpio => { - if (pi >= 0) return module.exports._set_mode(pi, gpio, 1); +module.exports.gpio_set_output = async gpio => { + if (pi >= 0) return await module.exports._set_mode(pi, gpio, 1); } -module.exports.gpio_set_input = (gpio, mode) => { +module.exports.gpio_set_input = async (gpio, mode) => { if (pi >= 0) { - let r = module.exports._set_mode(pi, gpio, 0); + let r = await module.exports._set_mode(pi, gpio, 0); if (r == 0) - return module.exports._set_pull_up_down(pi, gpio, mode); + return await module.exports._set_pull_up_down(pi, gpio, mode); else return r; } } -module.exports.gpio_read = gpio => { - if (pi >= 0) return module.exports._gpio_read(pi, gpio); +module.exports.gpio_read = async gpio => { + if (pi >= 0) return await module.exports._gpio_read(pi, gpio); } -module.exports.gpio_write = (gpio, value) => { - if (pi >= 0) return module.exports._gpio_write(pi, gpio, value); +module.exports.gpio_write = async (gpio, value) => { + if (pi >= 0) return await module.exports._gpio_write(pi, gpio, value); } -module.exports.servo = (gpio, pulse_width) => { - if (pi >= 0) return module.exports._set_servo_pulsewidth(pi, gpio, pulse_width); +module.exports.servo = async (gpio, pulse_width) => { + if (pi >= 0) return await module.exports._set_servo_pulsewidth(pi, gpio, pulse_width); } -module.exports.pwm = (gpio, pwm_frequency, pwm_duty_cycle) => { +module.exports.pwm = async (gpio, pwm_frequency, pwm_duty_cycle) => { if (pi >= 0) { - module.exports._set_PWM_frequency(pi, gpio, pwm_frequency); - module.exports._set_PWM_dutycycle(pi, gpio, pwm_duty_cycle); + await module.exports._set_PWM_frequency(pi, gpio, pwm_frequency); + await module.exports._set_PWM_dutycycle(pi, gpio, pwm_duty_cycle); } } -module.exports.serial_open = (tty, baud) => { - if (ser_hand >= 0) module.exports._serial_close(pi, ser_hand); // 勝手に閉じる - ser_hand = module.exports._serial_open(pi, tty, baud); +module.exports.serial_open = async (tty, baud) => { + if (ser_hand >= 0) await module.exports._serial_close(pi, ser_hand); // 勝手に閉じる + ser_hand = await module.exports._serial_open(pi, tty, baud); return ser_hand; } -module.exports.serial_close = () => { - if (ser_hand >= 0) module.exports._serial_close(pi, ser_hand); +module.exports.serial_close = async () => { + if (ser_hand >= 0) await module.exports._serial_close(pi, ser_hand); ser_hand = -1; } -module.exports.serial_write = data => { - if (ser_hand >= 0) return module.exports._serial_write(pi, ser_hand, Buffer.from(data)); +module.exports.serial_write = async data => { + if (ser_hand >= 0) return await module.exports._serial_write(pi, ser_hand, Buffer.from(data)); } -module.exports.serial_read = count => { - if (ser_hand >= 0) return module.exports._serial_read(pi, ser_hand, count).toString('utf8'); +module.exports.serial_read = async count => { + if (ser_hand >= 0) return await module.exports._serial_read(pi, ser_hand, count).toString('utf8'); } -module.exports.i2c_open = (i2c_bus, i2c_address) => { - if (i2c_hand >= 0) module.exports._i2c_close(pi, i2c_hand); // 勝手に閉じる - i2c_hand = module.exports._i2c_open(pi, i2c_bus, i2c_address); +module.exports.i2c_open = async (i2c_bus, i2c_address) => { + if (i2c_hand >= 0) await module.exports._i2c_close(pi, i2c_hand); // 勝手に閉じる + i2c_hand = await module.exports._i2c_open(pi, i2c_bus, i2c_address); return i2c_hand; } -module.exports.i2c_close = () => { - if (i2c_hand >= 0) module.exports._i2c_close(pi, i2c_hand); +module.exports.i2c_close = async () => { + if (i2c_hand >= 0) await module.exports._i2c_close(pi, i2c_hand); i2c_hand = -1; } -module.exports.i2c_write_byte_data = (reg, byte_val) => { - if (i2c_hand >= 0) return module.exports._i2c_write_byte_data(pi, i2c_hand, reg, byte_val); +module.exports.i2c_write_byte_data = async (reg, byte_val) => { + if (i2c_hand >= 0) return await module.exports._i2c_write_byte_data(pi, i2c_hand, reg, byte_val); } -module.exports.i2c_read_byte_data = reg => { - if (i2c_hand >= 0) return module.exports._i2c_read_byte_data(pi, i2c_hand, reg); +module.exports.i2c_read_byte_data = async reg => { + if (i2c_hand >= 0) return await module.exports._i2c_read_byte_data(pi, i2c_hand, reg); } -module.exports.i2c_write_i2c_block_data = (reg, data) => { - if (i2c_hand >= 0) return module.exports._i2c_write_i2c_block_data(pi, i2c_hand, reg, Buffer.from(data)); +module.exports.i2c_write_i2c_block_data = async (reg, data) => { + if (i2c_hand >= 0) return await module.exports._i2c_write_i2c_block_data(pi, i2c_hand, reg, Buffer.from(data)); } -module.exports.i2c_read_word_data = reg => { - if (i2c_hand >= 0) return module.exports._i2c_read_word_data(pi, i2c_hand, reg); +module.exports.i2c_read_word_data = async reg => { + if (i2c_hand >= 0) return await module.exports._i2c_read_word_data(pi, i2c_hand, reg); } -module.exports.i2c_read_device = count => { - if (i2c_hand >= 0) return module.exports._i2c_read_device(pi, i2c_hand, count).toString('utf8'); +module.exports.i2c_read_device = async count => { + if (i2c_hand >= 0) return await module.exports._i2c_read_device(pi, i2c_hand, count).toString('utf8'); } -module.exports.i2c_write_device = data => { - if (i2c_hand >= 0) return module.exports._i2c_write_device(pi, i2c_hand, Buffer.from(data)); +module.exports.i2c_write_device = async data => { + if (i2c_hand >= 0) return await module.exports._i2c_write_device(pi, i2c_hand, Buffer.from(data)); } // 終了処理 module.exports.close_all_handle = () => { diff --git a/local_modules/@ocogeclub/pigpio/pigpio.cpp b/local_modules/@ocogeclub/pigpio/pigpio.cpp index bf8375d..061a179 100644 --- a/local_modules/@ocogeclub/pigpio/pigpio.cpp +++ b/local_modules/@ocogeclub/pigpio/pigpio.cpp @@ -9,649 +9,656 @@ using namespace Napi; // pigpio 初期化 -Value _pigpioStart(const CallbackInfo &info) +Promise _pigpioStart(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 2) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 2) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsString() || !info[1].IsString()) + else if (!info[0].IsString() || !info[1].IsString()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - std::string addrStr = info[0].As().Utf8Value(); - std::string portStr = info[1].As().Utf8Value(); - return Number::New(env, pigpio_start(addrStr.c_str(), portStr.c_str())); - // return Number::New(env, pigpio_start(&addrStr[0], &portStr[0])); + else + { + std::string addrStr = info[0].As().Utf8Value(); + std::string portStr = info[1].As().Utf8Value(); + deferred.Resolve(Number::New(env, pigpio_start(addrStr.c_str(), portStr.c_str()))); + } + return deferred.Promise(); } // pigpio 後始末 -Value _pigpioStop(const CallbackInfo &info) +Promise _pigpioStop(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 1) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 1) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "IInvalid argument count").Value()); } - if (!info[0].IsNumber()) + else if (!info[0].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid aargument types").Value()); } - int pi = info[0].As().Int32Value(); - pigpio_stop(pi); - return env.Null(); + else + { + int pi = info[0].As().Int32Value(); + pigpio_stop(pi); + deferred.Resolve(env.Null()); + } + return deferred.Promise(); } // GPIO 端子のモードを設定 -Value _setMode(const CallbackInfo &info) +Promise _setMode(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int gpio = info[1].As().Uint32Value(); - unsigned int mode = info[2].As().Uint32Value(); + else + { + int pi = info[0].As().Int32Value(); + unsigned int gpio = info[1].As().Uint32Value(); + unsigned int mode = info[2].As().Uint32Value(); - return Number::New(env, - set_mode(pi, gpio, mode)); + deferred.Resolve(Number::New(env, set_mode(pi, gpio, mode))); + } + return deferred.Promise(); } -// GPIO 端子のモードを取得 -// Value _GetMode(const CallbackInfo &info) -// { -// Env env = info.Env(); -// if (info.Length() < 1) -// { -// TypeError::New(env, "Wrong number of arguments") -// .ThrowAsJavaScriptException(); -// return env.Null(); -// } -// if (!info[0].IsNumber()) -// { -// TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); -// return env.Null(); -// } - -// unsigned int gpio = info[0].As().DoubleValue(); - -// return Number::New(env, -// get_mode(pi, gpio)); -// } - // GPIOの内部プルアップ/ダウン抵抗の設定/クリア -Value _setPullUpDown(const CallbackInfo &info) +Promise _setPullUpDown(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int gpio = info[1].As().Uint32Value(); - unsigned int pud = info[2].As().Uint32Value(); - - return Number::New(env, - set_pull_up_down(pi, gpio, pud)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int gpio = info[1].As().Uint32Value(); + unsigned int pud = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, set_pull_up_down(pi, gpio, pud))); + } + return deferred.Promise(); } // GPIOの電圧を読む -Value _gpioRead(const CallbackInfo &info) +Promise _gpioRead(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 2) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 2) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - - int pi = info[0].As().Int32Value(); - unsigned int gpio = info[1].As().Uint32Value(); - - return Number::New(env, - gpio_read(pi, gpio)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int gpio = info[1].As().Uint32Value(); + deferred.Resolve(Number::New(env, gpio_read(pi, gpio))); + } + return deferred.Promise(); } // GPIO の電圧をセットする -Value _gpioWrite(const CallbackInfo &info) +Promise _gpioWrite(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int gpio = info[1].As().Uint32Value(); - unsigned int value = info[2].As().Uint32Value(); - - return Number::New(env, - gpio_write(pi, gpio, value)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int gpio = info[1].As().Uint32Value(); + unsigned int value = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, gpio_write(pi, gpio, value))); + } + return deferred.Promise(); } // サーボパルス幅をセットする -Value _setServoPulsewidth(const CallbackInfo &info) +Promise _setServoPulsewidth(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int user_gpio = info[1].As().Uint32Value(); - unsigned int pulsewidth = info[2].As().Uint32Value(); - - return Number::New(env, - set_servo_pulsewidth(pi, user_gpio, pulsewidth)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int user_gpio = info[1].As().Uint32Value(); + unsigned int pulsewidth = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, set_servo_pulsewidth(pi, user_gpio, pulsewidth))); + } + return deferred.Promise(); } // PWM周波数を設定する -Value _setPwmFrequency(const CallbackInfo &info) +Promise _setPwmFrequency(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int user_gpio = info[1].As().Uint32Value(); - unsigned int frequency = info[2].As().Uint32Value(); - - return Number::New(env, - set_PWM_frequency(pi, user_gpio, frequency)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int user_gpio = info[1].As().Uint32Value(); + unsigned int frequency = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, set_PWM_frequency(pi, user_gpio, frequency))); + } + return deferred.Promise(); } -// PWMのレンジを設定する -// Value _SetPwmRange(const CallbackInfo &info) -// { -// Env env = info.Env(); -// if (info.Length() < 2) -// { -// TypeError::New(env, "Wrong number of arguments") -// .ThrowAsJavaScriptException(); -// return env.Null(); -// } -// if (!info[0].IsNumber() || !info[1].IsNumber()) -// { -// TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); -// return env.Null(); -// } - -// unsigned int user_gpio = info[0].As().DoubleValue(); -// unsigned int range = info[1].As().DoubleValue(); - -// return Number::New(env, -// set_PWM_range(pi, user_gpio, range)); -// } - // PWMのデューティ比を指定して出力を開始する -Value _setPwmDutycycle(const CallbackInfo &info) +Promise _setPwmDutycycle(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int user_gpio = info[1].As().Uint32Value(); - unsigned int dutycycle = info[2].As().Uint32Value(); - - return Number::New(env, - set_PWM_dutycycle(pi, user_gpio, dutycycle)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int user_gpio = info[1].As().Uint32Value(); + unsigned int dutycycle = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, set_PWM_dutycycle(pi, user_gpio, dutycycle))); + } + return deferred.Promise(); } // シリアルポートを開く -Value _serialOpen(const CallbackInfo &info) +Promise _serialOpen(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsString() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsString() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - std::string ser_tty = info[1].As().Utf8Value(); - unsigned int baud = info[2].As().Uint32Value(); - // &ser_tty[0] - return Number::New(env, - serial_open(pi, (char *)ser_tty.c_str(), baud, 0)); + else + { + int pi = info[0].As().Int32Value(); + std::string ser_tty = info[1].As().Utf8Value(); + unsigned int baud = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, serial_open(pi, (char *)ser_tty.c_str(), baud, 0))); + } + return deferred.Promise(); } // シリアルポートを閉じる -Value _serialClose(const CallbackInfo &info) +Promise _serialClose(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 2) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 2) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - - return Number::New(env, - serial_close(pi, handle)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + deferred.Resolve(Number::New(env, serial_close(pi, handle))); + } + return deferred.Promise(); } // シリアルデバイスからデータを読む -Value _serialRead(const CallbackInfo &info) +Promise _serialRead(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int count = info[2].As().Uint32Value(); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int count = info[2].As().Uint32Value(); - char buf[count]; - int rxCount = serial_read(pi, handle, buf, count); - auto outBuf = Buffer::Copy(env, buf, rxCount); - - return outBuf; + char buf[count]; + int rxCount = serial_read(pi, handle, buf, count); + auto outBuf = Buffer::Copy(env, buf, rxCount); + deferred.Resolve(outBuf); + } + return deferred.Promise(); } // シリアルデバイスにバイト列を書き込む(data: string) -Value _serialWrite(const CallbackInfo &info) +Promise _serialWrite(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsBuffer()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsBuffer()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - auto buf = info[2].As>(); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + auto buf = info[2].As>(); - int count = buf.Length(); - - return Number::New(env, - serial_write(pi, handle, buf.Data(), count)); + int count = buf.Length(); + deferred.Resolve(Number::New(env, serial_write(pi, handle, buf.Data(), count))); + } + return deferred.Promise(); } // I2Cバスアドレスのデバイスのハンドルを返す -Value _i2cOpen(const CallbackInfo &info) +Promise _i2cOpen(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - - int pi = info[0].As().Int32Value(); - unsigned int i2c_bus = info[1].As().Uint32Value(); - unsigned int i2c_addr = info[2].As().Uint32Value(); - - return Number::New(env, - i2c_open(pi, i2c_bus, i2c_addr, 0)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int i2c_bus = info[1].As().Uint32Value(); + unsigned int i2c_addr = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, i2c_open(pi, i2c_bus, i2c_addr, 0))); + } + return deferred.Promise(); } // オープン済みI2Cハンドルを閉じる -Value _i2cClose(const CallbackInfo &info) +Promise _i2cClose(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 2) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 2) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - - return Number::New(env, - i2c_close(pi, handle)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + deferred.Resolve(Number::New(env, i2c_close(pi, handle))); + } + return deferred.Promise(); } // デバイスに1バイトを送る -Value _i2cWriteByte(const CallbackInfo &info) +Promise _i2cWriteByte(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int bVal = info[2].As().Uint32Value(); - - return Number::New(env, - i2c_write_byte(pi, handle, bVal)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int bVal = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, i2c_write_byte(pi, handle, bVal))); + } + return deferred.Promise(); } // デバイスから1バイトを受け取る -Value _i2cReadByte(const CallbackInfo &info) +Promise _i2cReadByte(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 2) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 2) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[0].IsNumber()) + else if (!info[0].IsNumber() || !info[0].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - - return Number::New(env, - i2c_read_byte(pi, handle)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + deferred.Resolve(Number::New(env, i2c_read_byte(pi, handle))); + } + return deferred.Promise(); } // I2Cハンドルに関連付けられているデバイスの指定されたレジスタに1バイトを書き込む -Value _i2cWriteByteData(const CallbackInfo &info) +Promise _i2cWriteByteData(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 4) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 4) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int i2c_reg = info[2].As().Uint32Value(); - unsigned int bVal = info[3].As().Uint32Value(); - - return Number::New(env, - i2c_write_byte_data(pi, handle, i2c_reg, bVal)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int i2c_reg = info[2].As().Uint32Value(); + unsigned int bVal = info[3].As().Uint32Value(); + deferred.Resolve(Number::New(env, i2c_write_byte_data(pi, handle, i2c_reg, bVal))); + } + return deferred.Promise(); } // I2Cハンドルに関連付けられているデバイスの指定されたレジスタから1バイトを読み込む -Value _i2cReadByteData(const CallbackInfo &info) +Promise _i2cReadByteData(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int i2c_reg = info[2].As().Uint32Value(); - - return Number::New(env, - i2c_read_byte_data(pi, handle, i2c_reg)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int i2c_reg = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, i2c_read_byte_data(pi, handle, i2c_reg))); + } + return deferred.Promise(); } // I2Cハンドルに関連付けられているデバイスの指定されたレジスタに最大32バイトのデータを書き込む。 -Value _i2cWriteI2cBlockData(const CallbackInfo &info) +Promise _i2cWriteI2cBlockData(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 4) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 4) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsBuffer()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsBuffer()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int i2c_reg = info[2].As().Uint32Value(); - auto buf = info[3].As>(); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int i2c_reg = info[2].As().Uint32Value(); + auto buf = info[3].As>(); - unsigned int count = buf.Length(); - - return Number::New(env, - i2c_write_i2c_block_data(pi, handle, i2c_reg, buf.Data(), count)); + unsigned int count = buf.Length(); + deferred.Resolve(Number::New(env, i2c_write_i2c_block_data(pi, handle, i2c_reg, buf.Data(), count))); + } + return deferred.Promise(); } // I2Cハンドルに関連付けられているデバイスの指定されたレジスタからcountバイトを読み込む。countは1~32。 -Value _i2cReadI2cBlockData(const CallbackInfo &info) +Promise _i2cReadI2cBlockData(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 4) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 4) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int i2cReg = info[2].As().Uint32Value(); - unsigned int count = info[3].As().Uint32Value(); - - char buf[count]; - int rxCount = i2c_read_i2c_block_data(pi, handle, i2cReg, buf, count); - auto outBuf = Buffer::Copy(env, buf, rxCount); - - return outBuf; + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int i2cReg = info[2].As().Uint32Value(); + unsigned int count = info[3].As().Uint32Value(); + char buf[count]; + int rxCount = i2c_read_i2c_block_data(pi, handle, i2cReg, buf, count); + auto outBuf = Buffer::Copy(env, buf, rxCount); + deferred.Resolve(outBuf); + } + return deferred.Promise(); } // I2Cハンドルに関連付けられているデバイスの指定されたレジスタから単一の16ビットワードを読み取る -Value _i2cReadWordData(const CallbackInfo &info) +Promise _i2cReadWordData(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int i2c_reg = info[2].As().Uint32Value(); - - return Number::New(env, - i2c_read_word_data(pi, handle, i2c_reg)); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int i2c_reg = info[2].As().Uint32Value(); + deferred.Resolve(Number::New(env, i2c_read_word_data(pi, handle, i2c_reg))); + } + return deferred.Promise(); } // I2Cハンドルに関連付けられているデバイスの指定されたレジスタに単一の16ビットワードを書き込む -Value _i2cWriteWordData(const CallbackInfo &info) +Promise _i2cWriteWordData(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 4) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 4) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int i2c_reg = info[2].As().Uint32Value(); - unsigned int wVal = info[3].As().Uint32Value(); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int i2c_reg = info[2].As().Uint32Value(); + unsigned int wVal = info[3].As().Uint32Value(); - return Number::New(env, - i2c_write_word_data(pi, handle, i2c_reg, wVal)); + deferred.Resolve(Number::New(env, i2c_write_word_data(pi, handle, i2c_reg, wVal))); + } + return deferred.Promise(); } // i2c デバイスからデータを受け取る -Value _i2cReadDevice(const CallbackInfo &info) +Promise _i2cReadDevice(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsNumber()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - unsigned int count = info[2].As().Uint32Value(); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + unsigned int count = info[2].As().Uint32Value(); - char buf[count]; - int rxCount = i2c_read_device(pi, handle, buf, count); - auto outBuf = Buffer::Copy(env, buf, rxCount); - - return outBuf; + char buf[count]; + int rxCount = i2c_read_device(pi, handle, buf, count); + auto outBuf = Buffer::Copy(env, buf, rxCount); + deferred.Resolve(outBuf); + } + return deferred.Promise(); } // i2c デバイスにバイト列を送る(data: buffer) -Value _i2cWriteDevice(const CallbackInfo &info) +Promise _i2cWriteDevice(const CallbackInfo &info) { Env env = info.Env(); - if (info.Length() < 3) + auto deferred = Napi::Promise::Deferred::New(env); + if (info.Length() != 3) { - TypeError::New(env, "Wrong number of arguments") - .ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + TypeError::New(env, "Invalid argument count").Value()); } - if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsBuffer()) + else if (!info[0].IsNumber() || !info[1].IsNumber() || !info[2].IsBuffer()) { - TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException(); - return env.Null(); + deferred.Reject( + Napi::TypeError::New(env, "Invalid argument types").Value()); } - int pi = info[0].As().Int32Value(); - unsigned int handle = info[1].As().Uint32Value(); - auto buf = info[2].As>(); + else + { + int pi = info[0].As().Int32Value(); + unsigned int handle = info[1].As().Uint32Value(); + auto buf = info[2].As>(); - unsigned int count = buf.Length(); - - return Number::New(env, - i2c_write_device(pi, handle, buf.Data(), count)); + unsigned int count = buf.Length(); + deferred.Resolve(Number::New(env, i2c_write_device(pi, handle, buf.Data(), count))); + } + return deferred.Promise(); } Object Init(Env env, Object exports) { - // exports.Set(String::New(env, "usleep"), Function::New(env, _Usleep)); exports.Set(String::New(env, "_pigpio_start"), Function::New(env, _pigpioStart)); exports.Set(String::New(env, "_pigpio_stop"), Function::New(env, _pigpioStop)); exports.Set(String::New(env, "_set_mode"), Function::New(env, _setMode)); - // exports.Set(String::New(env, "get_mode"), Function::New(env, _GetMode)); exports.Set(String::New(env, "_set_pull_up_down"), Function::New(env, _setPullUpDown)); exports.Set(String::New(env, "_gpio_read"), Function::New(env, _gpioRead)); exports.Set(String::New(env, "_gpio_write"), Function::New(env, _gpioWrite)); exports.Set(String::New(env, "_set_servo_pulsewidth"), Function::New(env, _setServoPulsewidth)); exports.Set(String::New(env, "_set_PWM_frequency"), Function::New(env, _setPwmFrequency)); - // exports.Set(String::New(env, "set_PWM_range"), Function::New(env, _SetPwmRange)); exports.Set(String::New(env, "_set_PWM_dutycycle"), Function::New(env, _setPwmDutycycle)); exports.Set(String::New(env, "_serial_open"), Function::New(env, _serialOpen)); exports.Set(String::New(env, "_serial_close"), Function::New(env, _serialClose)); diff --git a/package-lock.json b/package-lock.json index 406c565..3debbfd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,11 @@ "tensorset": "^1.2.9" }, "devDependencies": { +<<<<<<< HEAD "electron": "^16.0.1", +======= + "electron": "^16.0.2", +>>>>>>> develop "electron-rebuild": "^3.2.5" } }, @@ -1199,9 +1203,15 @@ "dev": true }, "node_modules/electron": { +<<<<<<< HEAD "version": "16.0.1", "resolved": "https://registry.npmjs.org/electron/-/electron-16.0.1.tgz", "integrity": "sha512-6TSDBcoKGgmKL/+W+LyaXidRVeRl1V4I81ZOWcqsVksdTMfM4AlxTgfaoYdK/nUhqBrUtuPDcqOyJE6Bc4qMpw==", +======= + "version": "16.0.2", + "resolved": "https://registry.npmjs.org/electron/-/electron-16.0.2.tgz", + "integrity": "sha512-kT746yVMztrP4BbT3nrFNcUcfgFu2yelUw6TWBVTy0pju+fBISaqcvoiMrq+8U0vRpoXSu2MJYygOf4T0Det7g==", +>>>>>>> develop "dev": true, "hasInstallScript": true, "dependencies": { @@ -4521,9 +4531,15 @@ "dev": true }, "electron": { +<<<<<<< HEAD "version": "16.0.1", "resolved": "https://registry.npmjs.org/electron/-/electron-16.0.1.tgz", "integrity": "sha512-6TSDBcoKGgmKL/+W+LyaXidRVeRl1V4I81ZOWcqsVksdTMfM4AlxTgfaoYdK/nUhqBrUtuPDcqOyJE6Bc4qMpw==", +======= + "version": "16.0.2", + "resolved": "https://registry.npmjs.org/electron/-/electron-16.0.2.tgz", + "integrity": "sha512-kT746yVMztrP4BbT3nrFNcUcfgFu2yelUw6TWBVTy0pju+fBISaqcvoiMrq+8U0vRpoXSu2MJYygOf4T0Det7g==", +>>>>>>> develop "dev": true, "requires": { "@electron/get": "^1.13.0", diff --git a/package.json b/package.json index 3ca0580..0163731 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ }, "homepage": "https://github.com/ocogeclub/ocoge#readme", "devDependencies": { - "electron": "^16.0.1", + "electron": "^16.0.2", "electron-rebuild": "^3.2.5" }, "dependencies": { @@ -35,4 +35,4 @@ "nodemailer": "^6.7.1", "tensorset": "^1.2.9" } -} +} \ No newline at end of file diff --git a/ugj_blocks.js b/ugj_blocks.js index 91be51d..d8df69b 100644 --- a/ugj_blocks.js +++ b/ugj_blocks.js @@ -135,8 +135,8 @@ Blockly.JavaScript['ugj_controls_forEach'] = function (block) { var variable_item = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('item'), Blockly.Variables.NAME_TYPE); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - `for (let i_index in ${value_list}) {`, - `${variable_item} = ${value_list}[i_index];`, + `for (let _index in ${value_list}) {`, + `${variable_item} = ${value_list}[_index];`, statements_do, `}`, '' @@ -321,9 +321,9 @@ Blockly.Blocks['ugj_gpio_open'] = { }; Blockly.JavaScript['ugj_gpio_open'] = function (block) { Blockly.JavaScript.provideFunction_( - 'require_gpio', [`const pi = require('@ocogeclub/` + elutil.gpio_backend + `');`] + 'require_gpio', [`const _pi = require('@ocogeclub/` + elutil.gpio_backend + `');`] ); - var code = `console.log('pi='+pi.gpio_open());\n`; // + var code = `await _pi.gpio_open();\n`; // return code; }; Blockly.Python['ugj_gpio_open'] = function (block) { @@ -352,7 +352,7 @@ Blockly.Blocks['ugj_gpio_close'] = { } }; Blockly.JavaScript['ugj_gpio_close'] = function (block) { - var code = 'pi.gpio_close();\n'; + var code = 'await _pi.gpio_close();\n'; return code; }; Blockly.Python['ugj_gpio_close'] = function (block) { @@ -387,12 +387,12 @@ Blockly.Blocks['ugj_gpio_set_output'] = { }; Blockly.JavaScript['ugj_gpio_set_output'] = function (block) { var value_gpio = Blockly.JavaScript.valueToCode(block, 'gpio', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.gpio_set_output(${value_gpio});\n`; + var code = `await _pi.gpio_set_output(${value_gpio});\n`; return code; }; Blockly.Python['ugj_gpio_set_output'] = function (block) { var value_gpio = Blockly.Python.valueToCode(block, 'gpio', Blockly.Python.ORDER_ATOMIC); - var code = `pi.gpio_set_output(${value_gpio})\n`; + var code = `await pi.gpio_set_output(${value_gpio})\n`; return code; }; @@ -442,13 +442,13 @@ Blockly.Blocks['ugj_gpio_set_input'] = { Blockly.JavaScript['ugj_gpio_set_input'] = function (block) { var value_gpio = Blockly.JavaScript.valueToCode(block, 'gpio', Blockly.JavaScript.ORDER_ATOMIC); var dropdown_lflag = block.getFieldValue('lflag'); - var code = `pi.gpio_set_input(${value_gpio}, ${dropdown_lflag});\n`; + var code = `await _pi.gpio_set_input(${value_gpio}, ${dropdown_lflag});\n`; return code; }; Blockly.Python['ugj_gpio_set_input'] = function (block) { var value_gpio = Blockly.Python.valueToCode(block, 'gpio', Blockly.Python.ORDER_ATOMIC); var dropdown_lflag = block.getFieldValue('lflag'); - var code = `pi.gpio_set_input(gpioHand, ${value_gpio}, ${dropdown_lflag})\n`; + var code = `await pi.gpio_set_input(gpioHand, ${value_gpio}, ${dropdown_lflag})\n`; return code; }; @@ -478,12 +478,12 @@ Blockly.Blocks['ugj_gpio_read'] = { }; Blockly.JavaScript['ugj_gpio_read'] = function (block) { var value_gpio = Blockly.JavaScript.valueToCode(block, 'gpio', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.gpio_read(${value_gpio})`; + var code = `await _pi.gpio_read(${value_gpio})`; return [code, Blockly.JavaScript.ORDER_NONE]; }; Blockly.Python['ugj_gpio_read'] = function (block) { var value_gpio = Blockly.Python.valueToCode(block, 'gpio', Blockly.Python.ORDER_ATOMIC); - var code = `pi.gpio_read(gpioHand, ${value_gpio})`; + var code = `await pi.gpio_read(gpioHand, ${value_gpio})`; return [code, Blockly.Python.ORDER_NONE]; }; @@ -529,13 +529,13 @@ Blockly.Blocks['ugj_gpio_write'] = { Blockly.JavaScript['ugj_gpio_write'] = function (block) { var value_gpio = Blockly.JavaScript.valueToCode(block, 'gpio', Blockly.JavaScript.ORDER_ATOMIC); var dropdown_level = block.getFieldValue('level'); - var code = `pi.gpio_write(${value_gpio}, ${dropdown_level});\n`; + var code = `await _pi.gpio_write(${value_gpio}, ${dropdown_level});\n`; return code; }; Blockly.Python['ugj_gpio_write'] = function (block) { var value_gpio = Blockly.Python.valueToCode(block, 'gpio', Blockly.Python.ORDER_ATOMIC); var dropdown_level = block.getFieldValue('level'); - var code = `pi.gpio_write(gpioHand, ${value_gpio}, ${dropdown_level})\n`; + var code = `await pi.gpio_write(gpioHand, ${value_gpio}, ${dropdown_level})\n`; return code; }; @@ -572,13 +572,13 @@ Blockly.Blocks['ugj_servo'] = { Blockly.JavaScript['ugj_servo'] = function (block) { var value_gpio = Blockly.JavaScript.valueToCode(block, 'gpio', Blockly.JavaScript.ORDER_ATOMIC); var value_pulsewidth = Blockly.JavaScript.valueToCode(block, 'pulsewidth', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.servo(${value_gpio}, ${value_pulsewidth});\n`; + var code = `await _pi.servo(${value_gpio}, ${value_pulsewidth});\n`; return code; }; Blockly.Python['ugj_servo'] = function (block) { var value_gpio = Blockly.Python.valueToCode(block, 'gpio', Blockly.Python.ORDER_ATOMIC); var value_pulsewidth = Blockly.Python.valueToCode(block, 'pulsewidth', Blockly.Python.ORDER_ATOMIC); - var code = `pi.servo(gpioHand, ${value_gpio}, ${value_pulsewidth})\n`; + var code = `await pi.servo(gpioHand, ${value_gpio}, ${value_pulsewidth})\n`; return code; }; @@ -621,14 +621,14 @@ Blockly.JavaScript['ugj_pwm'] = function (block) { var value_gpio = Blockly.JavaScript.valueToCode(block, 'gpio', Blockly.JavaScript.ORDER_ATOMIC); var value_pwm_frequency = Blockly.JavaScript.valueToCode(block, 'pwm_frequency', Blockly.JavaScript.ORDER_ATOMIC); var value_pwm_duty_cycle = Blockly.JavaScript.valueToCode(block, 'pwm_duty_cycle', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.pwm(${value_gpio}, ${value_pwm_frequency}, ${value_pwm_duty_cycle});\n`; + var code = `await _pi.pwm(${value_gpio}, ${value_pwm_frequency}, ${value_pwm_duty_cycle});\n`; return code; }; Blockly.Python['ugj_pwm'] = function (block) { var value_gpio = Blockly.Python.valueToCode(block, 'gpio', Blockly.Python.ORDER_ATOMIC); var value_pwm_frequency = Blockly.Python.valueToCode(block, 'pwm_frequency', Blockly.Python.ORDER_ATOMIC); var value_pwm_duty_cycle = Blockly.Python.valueToCode(block, 'pwm_duty_cycle', Blockly.Python.ORDER_ATOMIC); - var code = `pi.pwm(gpioHand, ${value_gpio}, ${value_pwm_frequency}, ${value_pwm_duty_cycle})\n`; + var code = `await pi.pwm(gpioHand, ${value_gpio}, ${value_pwm_frequency}, ${value_pwm_duty_cycle})\n`; return code; }; /********************** */ @@ -678,9 +678,9 @@ Blockly.JavaScript['ugj_serial_open'] = function (block) { // var value_tty = Blockly.JavaScript.valueToCode(block, 'tty', Blockly.JavaScript.ORDER_ATOMIC); var dropdown_baud = block.getFieldValue('baud'); Blockly.JavaScript.provideFunction_( - 'require_gpio', [`const pi = require('@ocogeclub/` + elutil.gpio_backend + `');`] + 'require_gpio', [`const _pi = require('@ocogeclub/` + elutil.gpio_backend + `');`] ); - var code = `pi.serial_open('/dev/serial0', ${dropdown_baud});\n`; + var code = `await _pi.serial_open('/dev/serial0', ${dropdown_baud});\n`; return code; }; Blockly.Python['ugj_serial_open'] = function (block) { @@ -711,7 +711,7 @@ Blockly.Blocks['ugj_serial_close'] = { } }; Blockly.JavaScript['ugj_serial_close'] = function (block) { - var code = 'pi.serial_close();\n'; + var code = 'await _pi.serial_close();\n'; return code; }; Blockly.Python['ugj_serial_close'] = function (block) { @@ -746,12 +746,12 @@ Blockly.Blocks['ugj_serial_write'] = { }; Blockly.JavaScript['ugj_serial_write'] = function (block) { var value_data = Blockly.JavaScript.valueToCode(block, 'data', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.serial_write(${value_data});\n`; + var code = `await _pi.serial_write(${value_data});\n`; return code; }; Blockly.Python['ugj_serial_write'] = function (block) { var value_data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC); - var code = `pi.serial_write(ser_hand, ${value_data}.encode())\n`; + var code = `await pi.serial_write(ser_hand, ${value_data}.encode())\n`; return code; }; @@ -781,12 +781,12 @@ Blockly.Blocks['ugj_serial_read'] = { }; Blockly.JavaScript['ugj_serial_read'] = function (block) { var value_count = Blockly.JavaScript.valueToCode(block, 'count', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.serial_read(${value_count})`; + var code = `await _pi.serial_read(${value_count})`; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.Python['ugj_serial_read'] = function (block) { var value_count = Blockly.Python.valueToCode(block, 'count', Blockly.Python.ORDER_ATOMIC); - var code = `pi.serial_read(ser_hand, ${value_count}).decode()`; + var code = `await pi.serial_read(ser_hand, ${value_count}).decode()`; return [code, Blockly.Python.ORDER_ATOMIC]; }; @@ -818,9 +818,9 @@ Blockly.Blocks['ugj_i2c_open'] = { Blockly.JavaScript['ugj_i2c_open'] = function (block) { var value_i2c_address = Blockly.JavaScript.valueToCode(block, 'i2c_address', Blockly.JavaScript.ORDER_ATOMIC); Blockly.JavaScript.provideFunction_( - 'require_gpio', [`const pi = require('@ocogeclub/` + elutil.gpio_backend + `');`] + 'require_gpio', [`const _pi = require('@ocogeclub/` + elutil.gpio_backend + `');`] ); - var code = `console.log('i2c_hand='+pi.i2c_open(${elutil.i2c_bus}, ${value_i2c_address}));\n`; + var code = `await _pi.i2c_open(${elutil.i2c_bus}, ${value_i2c_address});\n`; return code; }; Blockly.Python['ugj_i2c_open'] = function (block) { @@ -850,11 +850,11 @@ Blockly.Blocks['ugj_i2c_close'] = { } }; Blockly.JavaScript['ugj_i2c_close'] = function (block) { - var code = `pi.i2c_close();\n`; + var code = `await _pi.i2c_close();\n`; return code; }; Blockly.Python['ugj_i2c_close'] = function (block) { - var code = `pi.i2c_close(i2c_hand)\n`; + var code = `await pi.i2c_close(i2c_hand)\n`; return code; }; @@ -891,13 +891,13 @@ Blockly.Blocks['ugj_i2c_write_byte_data'] = { Blockly.JavaScript['ugj_i2c_write_byte_data'] = function (block) { var value_reg = Blockly.JavaScript.valueToCode(block, 'reg', Blockly.JavaScript.ORDER_ATOMIC); var value_byte_val = Blockly.JavaScript.valueToCode(block, 'byte_val', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.i2c_write_byte_data(${value_reg}, ${value_byte_val});\n`; + var code = `await _pi.i2c_write_byte_data(${value_reg}, ${value_byte_val});\n`; return code; }; Blockly.Python['ugj_i2c_write_byte_data'] = function (block) { var value_reg = Blockly.Python.valueToCode(block, 'reg', Blockly.Python.ORDER_ATOMIC); var value_byte_val = Blockly.Python.valueToCode(block, 'byte_val', Blockly.Python.ORDER_ATOMIC); - var code = `pi.i2c_write_byte_data(i2c_hand, ${value_reg}, ${value_byte_val})\n`; + var code = `await pi.i2c_write_byte_data(i2c_hand, ${value_reg}, ${value_byte_val})\n`; return code; }; @@ -927,12 +927,12 @@ Blockly.Blocks['ugj_i2c_read_byte_data'] = { }; Blockly.JavaScript['ugj_i2c_read_byte_data'] = function (block) { var value_reg = Blockly.JavaScript.valueToCode(block, 'reg', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.i2c_read_byte_data(${value_reg})\n`; + var code = `await _pi.i2c_read_byte_data(${value_reg})\n`; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.Python['ugj_i2c_read_byte_data'] = function (block) { var value_reg = Blockly.Python.valueToCode(block, 'reg', Blockly.Python.ORDER_ATOMIC); - var code = `pi.i2c_read_byte_data(i2c_hand, ${value_reg})\n`; + var code = `await pi.i2c_read_byte_data(i2c_hand, ${value_reg})\n`; return [code, Blockly.Python.ORDER_ATOMIC]; }; @@ -966,7 +966,7 @@ Blockly.Blocks['ugj_i2c_write_i2c_block_data'] = { Blockly.JavaScript['ugj_i2c_write_i2c_block_data'] = function (block) { var value_reg = Blockly.JavaScript.valueToCode(block, 'reg', Blockly.JavaScript.ORDER_ATOMIC); var value_data = Blockly.JavaScript.valueToCode(block, 'data', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.i2c_write_i2c_block_data (${value_reg}, ${value_data});`; + var code = `await _pi.i2c_write_i2c_block_data (${value_reg}, ${value_data});`; return code; }; Blockly.Python['ugj_i2c_write_i2c_block_data'] = function (block) { @@ -1003,12 +1003,12 @@ Blockly.Blocks['ugj_i2c_read_device'] = { }; Blockly.JavaScript['ugj_i2c_read_device'] = function (block) { var value_count = Blockly.JavaScript.valueToCode(block, 'count', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.i2c_read_device(${value_count})`; + var code = `await _pi.i2c_read_device(${value_count})`; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.Python['ugj_i2c_read_device'] = function (block) { var value_count = Blockly.Python.valueToCode(block, 'count', Blockly.Python.ORDER_ATOMIC); - var code = `pi.i2c_read_device(i2c_hand, ${value_count}).decode()`; + var code = `await pi.i2c_read_device(i2c_hand, ${value_count}).decode()`; return [code, Blockly.Python.ORDER_ATOMIC]; }; /********************************************** */ @@ -1038,12 +1038,12 @@ Blockly.Blocks['ugj_i2c_write_device'] = { }; Blockly.JavaScript['ugj_i2c_write_device'] = function (block) { var value_data = Blockly.JavaScript.valueToCode(block, 'data', Blockly.JavaScript.ORDER_ATOMIC); - var code = `pi.i2c_write_device(${value_data})\n`; + var code = `await _pi.i2c_write_device(${value_data})\n`; return code; }; Blockly.Python['ugj_i2c_write_device'] = function (block) { var value_data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC); - var code = `pi.i2c_write_device(i2c_hand, ${value_data}.encode())\n`; + var code = `await pi.i2c_write_device(i2c_hand, ${value_data}.encode())\n`; return code; }; @@ -1094,19 +1094,19 @@ Blockly.JavaScript['ugj_bme280'] = function (block) { var variable_hum = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('hum'), Blockly.Variables.NAME_TYPE); var variable_pres = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('pres'), Blockly.Variables.NAME_TYPE); Blockly.JavaScript.provideFunction_( - 'require_bme280', [`const bme280 = require('@ocogeclub/bme280');`] + 'require_bme280', [`const _bme280 = require('@ocogeclub/bme280');`] ); var code = [ `const options = {`, ` i2cBusNo: ${elutil.i2c_bus},`, ` i2cAddress: ${value_address}`, `};`, - `bme280.init(options);`, - `let thp = bme280.readSensorData();`, - `${variable_temp} = Math.round(thp.temperature_C * 10) / 10;`, - `${variable_hum} = Math.round(thp.humidity * 10) / 10;`, - `${variable_pres} = Math.round(thp.pressure_hPa);`, - `bme280.cancel();`, + `await _bme280.init(options);`, + `let _thp = await _bme280.readSensorData();`, + `${variable_temp} = Math.round(_thp.temperature_C * 10) / 10;`, + `${variable_hum} = Math.round(_thp.humidity * 10) / 10;`, + `${variable_pres} = Math.round(_thp.pressure_hPa);`, + `await _bme280.cancel();`, `` ].join('\n'); return code; @@ -1159,9 +1159,9 @@ Blockly.Blocks['ugj_gesture_init'] = { Blockly.JavaScript['ugj_gesture_init'] = function (block) { var value_i2c_addr = Blockly.JavaScript.valueToCode(block, 'i2c_addr', Blockly.JavaScript.ORDER_ATOMIC); Blockly.JavaScript.provideFunction_( - 'require_paj7620', [`const paj7620 = require('@ocogeclub/paj7620');`] + 'require_paj7620', [`const _paj7620 = require('@ocogeclub/paj7620');`] ); - var code = `paj7620.init(${elutil.i2c_bus}, ${value_i2c_addr}); + var code = `await _paj7620.init(${elutil.i2c_bus}, ${value_i2c_addr}); `; return code; }; @@ -1190,7 +1190,7 @@ Blockly.Blocks['ugj_gesture_read'] = { } }; Blockly.JavaScript['ugj_gesture_read'] = function (block) { - var code = 'await paj7620.return_gesture()'; + var code = 'await _paj7620.return_gesture()'; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.Python['ugj_gesture_read'] = function (block) { @@ -1218,7 +1218,7 @@ Blockly.Blocks['ugj_gesture_stop'] = { } }; Blockly.JavaScript['ugj_gesture_stop'] = function (block) { - var code = 'paj7620.stop();\n'; + var code = 'await _paj7620.stop();\n'; return code; }; Blockly.Python['ugj_gesture_stop'] = function (block) { @@ -1266,7 +1266,7 @@ Blockly.JavaScript['ugj_grideye_init'] = function (block) { Blockly.JavaScript.provideFunction_( 'require_amg8833', [`const _amg8833 = require('@ocogeclub/amg8833');`] ); - var code = `_amg8833.init(${elutil.i2c_bus}, ${dropdown_addr});\n`; + var code = `await _amg8833.init(${elutil.i2c_bus}, ${dropdown_addr});\n`; return code; }; Blockly.Python['ugj_grideye_init'] = function (block) { @@ -1292,7 +1292,7 @@ Blockly.Blocks['ugj_grideye_thermistor'] = { } }; Blockly.JavaScript['ugj_grideye_thermistor'] = function (block) { - var code = `_amg8833.read_thermistor()`; + var code = `await _amg8833.read_thermistor()`; return [code, Blockly.JavaScript.ORDER_NONE]; }; Blockly.Python['ugj_grideye_thermistor'] = function (block) { @@ -1320,7 +1320,7 @@ Blockly.Blocks['ugj_grideye_read'] = { } }; Blockly.JavaScript['ugj_grideye_read'] = function (block) { - var code = '_amg8833.read_temp_array()'; + var code = 'await _amg8833.read_temp_array()'; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.Python['ugj_grideye_read'] = function (block) { @@ -1348,7 +1348,7 @@ Blockly.Blocks['ugj_grideye_stop'] = { } }; Blockly.JavaScript['ugj_grideye_stop'] = function (block) { - var code = '_amg8833.stop();\n'; + var code = 'await _amg8833.stop();\n'; return code; }; Blockly.Python['ugj_grideye_stop'] = function (block) { @@ -1385,8 +1385,8 @@ Blockly.JavaScript['ugj_faceapi'] = function (block) { var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ `require('@tensorflow/tfjs-node');`, - `const faceapi = require('@vladmandic/face-api/dist/face-api.node.js');`, - `const detect_intvl = ${dropdown_interval_sec};`, + `const _faceapi = require('@vladmandic/face-api/dist/face-api.node.js');`, + `const _interval_sec = ${dropdown_interval_sec};`, statements_do, '' ].join('\n'); @@ -1406,10 +1406,10 @@ Blockly.Blocks['ugj_face_init'] = { }; Blockly.JavaScript['ugj_face_init'] = function (block) { var code = [ - "const videoEl = document.getElementById('subdisplay');", - `const displaySize = { width: videoEl.width, height: videoEl.height };`, - "const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: displaySize });", - "videoEl.srcObject = stream;", + "const _videoEl = document.getElementById('subdisplay');", + `const _displaySize = { width: videoEl.width, height: videoEl.height };`, + "const _stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: _displaySize });", + "_videoEl.srcObject = _stream;", "" ].join('\n'); return code; @@ -1428,12 +1428,12 @@ Blockly.Blocks['ugj_face_display'] = { }; Blockly.JavaScript['ugj_face_display'] = function (block) { var code = [ - "videoEl.style.display = 'inline-block';", - `const overlay = document.createElement('canvas');`, - `overlay.setAttribute('width', videoEl.width);`, - `overlay.setAttribute('height', videoEl.height);`, - `overlay.className = 'subdisplay';`, - `document.getElementById('display_area').appendChild(overlay);`, + "_videoEl.style.display = 'inline-block';", + `const _overlay = document.createElement('canvas');`, + `_overlay.setAttribute('width', _videoEl.width);`, + `_overlay.setAttribute('height', _videoEl.height);`, + `_overlay.className = 'subdisplay';`, + `document.getElementById('display_area').appendChild(_overlay);`, "" ].join('\n'); return code; @@ -1462,42 +1462,41 @@ Blockly.JavaScript['ugj_face_detect'] = function (block) { var variable_w = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('w'), Blockly.Variables.NAME_TYPE); var variable_h = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('h'), Blockly.Variables.NAME_TYPE); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); - var code_model = `await faceapi.nets.tinyFaceDetector.load('${ugj_const.library_path}models/');`; - if (with_landmark) { code_model += `\nawait faceapi.nets.faceLandmark68TinyNet.load('${ugj_const.library_path}models/');`; } - var code_detect_face = " let result = await faceapi.detectSingleFace(videoEl, options)" + var code_model = `await _faceapi.nets.tinyFaceDetector.load('${ugj_const.library_path}models/');`; + if (with_landmark) { code_model += `\nawait _faceapi.nets.faceLandmark68TinyNet.load('${ugj_const.library_path}models/');`; } + var code_detect_face = " let _result = await _faceapi.detectSingleFace(_videoEl, _options)" if (with_landmark) { code_detect_face += `.withFaceLandmarks(true);` } else { code_detect_face += `;` } var code_rect; if (with_landmark) { code_rect = [ - ` ${variable_x} = Math.round(result.detection.box.x);`, - ` ${variable_y} = Math.round(result.detection.box.y);`, - ` ${variable_w} = Math.round(result.detection.box.width);`, - ` ${variable_h} = Math.round(result.detection.box.height);`, + ` ${variable_x} = Math.round(_result.detection.box.x);`, + ` ${variable_y} = Math.round(_result.detection.box.y);`, + ` ${variable_w} = Math.round(_result.detection.box.width);`, + ` ${variable_h} = Math.round(_result.detection.box.height);`, ].join('\n'); } else { code_rect = [ - ` ${variable_x} = Math.round(result.box.x);`, - ` ${variable_y} = Math.round(result.box.y);`, - ` ${variable_w} = Math.round(result.box.width);`, - ` ${variable_h} = Math.round(result.box.height);`, + ` ${variable_x} = Math.round(_result.box.x);`, + ` ${variable_y} = Math.round(_result.box.y);`, + ` ${variable_w} = Math.round(_result.box.width);`, + ` ${variable_h} = Math.round(_result.box.height);`, ].join('\n'); } var code = [ code_model, - "const options = new faceapi.TinyFaceDetectorOptions({ inputSize: 128, scoreThreshold : 0.3 });", - // `const onPlay = async () => {`, - // `console.log('onplay');`, - ` const detectInterval = setInterval(async () => {`, + "const _options = new _faceapi.TinyFaceDetectorOptions({ inputSize: 128, scoreThreshold : 0.3 });", + // `const _onPlay = async () => {`, + ` const _detectInterval = setInterval(async () => {`, code_detect_face, - " if (result) {", + " if (_result) {", code_rect, statements_do, " }", - ` }, detect_intvl);`, + ` }, _interval_sec);`, // " setTimeout(() => onPlay())", // "}", - // "videoEl.onplay = onPlay;", + // "_videoEl.onplay = _onPlay;", "" ].join('\n'); return code; @@ -1516,11 +1515,11 @@ Blockly.Blocks['ugj_face_drawrect'] = { } }; Blockly.JavaScript['ugj_face_drawrect'] = function (block) { - var code_draw = ` faceapi.draw.drawDetections(overlay, resizedDetections);`; + var code_draw = ` _faceapi.draw.drawDetections(_overlay, _resizedDetections);`; if (with_landmark) { code_draw += `\n faceapi.draw.drawFaceLandmarks(overlay, resizedDetections);`; } var code = [ - ` faceapi.matchDimensions(overlay, displaySize);`, - ` const resizedDetections = faceapi.resizeResults(result, displaySize);`, + ` _faceapi.matchDimensions(_overlay, _displaySize);`, + ` const _resizedDetections = _faceapi.resizeResults(_result, _displaySize);`, code_draw, "" ].join('\n'); @@ -1590,9 +1589,9 @@ Blockly.Blocks['ugj_canvas_init'] = { }; Blockly.JavaScript['ugj_canvas_init'] = function (block) { var code = [ - `let canvas = document.getElementById('gcanvas');`, - `canvas.style.display = 'inline-block';`, - "let ctx = canvas.getContext('2d');", + `let _canvas = document.getElementById('gcanvas');`, + `_canvas.style.display = 'inline-block';`, + "let _ctx = _canvas.getContext('2d');", '' ].join('\n'); @@ -1640,9 +1639,9 @@ Blockly.Blocks['ugj_canvas_loadimg'] = { Blockly.JavaScript['ugj_canvas_loadimg'] = function (block) { var value_imgfilename = Blockly.JavaScript.valueToCode(block, 'imgfilename', Blockly.JavaScript.ORDER_ATOMIC); var code = [ - `let img = new Image();`, - `img.src = '${ugj_const.doc_root}' + ${value_imgfilename};`, - `img.onload = () => ctx.drawImage(img,0,0);`, + `let _img = new Image();`, + `_img.src = '${ugj_const.doc_root}' + ${value_imgfilename};`, + `_img.onload = () => _ctx.drawImage(img,0,0);`, // `ugj_canvasImg('${ugj_const.doc_root}' + ${value_imgfilename});`, '' ].join('\n'); @@ -1680,7 +1679,7 @@ Blockly.JavaScript['ugj_canvas_clearrect'] = function (block) { var value_y = Blockly.JavaScript.valueToCode(block, 'y', Blockly.JavaScript.ORDER_ATOMIC); var value_w = Blockly.JavaScript.valueToCode(block, 'w', Blockly.JavaScript.ORDER_ATOMIC); var value_h = Blockly.JavaScript.valueToCode(block, 'h', Blockly.JavaScript.ORDER_ATOMIC); - var code = `ctx.clearRect(${value_x},${value_y}, ${value_w}, ${value_h});\n`; + var code = `_ctx.clearRect(${value_x},${value_y}, ${value_w}, ${value_h});\n`; return code; }; @@ -1701,7 +1700,7 @@ Blockly.Blocks['ugj_canvas_width'] = { } }; Blockly.JavaScript['ugj_canvas_width'] = function (block) { - var code = 'canvas.width'; + var code = '_canvas.width'; return [code, Blockly.JavaScript.ORDER_NONE]; }; /*********************** */ @@ -1720,7 +1719,7 @@ Blockly.Blocks['ugj_canvas_height'] = { } }; Blockly.JavaScript['ugj_canvas_height'] = function (block) { - var code = 'canvas.height'; + var code = '_canvas.height'; return [code, Blockly.JavaScript.ORDER_NONE]; }; @@ -1759,11 +1758,11 @@ Blockly.JavaScript['ugj_canvas_drawcircle'] = function (block) { var value_r = Blockly.JavaScript.valueToCode(block, 'r', Blockly.JavaScript.ORDER_ATOMIC); var value_color = Blockly.JavaScript.valueToCode(block, 'color', Blockly.JavaScript.ORDER_ATOMIC); var code = [ - 'ctx.beginPath();', - `ctx.arc(${value_x}, ${value_y}, ${value_r}, 0, Math.PI*2);`, - `ctx.fillStyle = ${value_color};`, - 'ctx.fill();', - 'ctx.closePath();', + '_ctx.beginPath();', + `_ctx.arc(${value_x}, ${value_y}, ${value_r}, 0, Math.PI*2);`, + `_ctx.fillStyle = ${value_color};`, + '_ctx.fill();', + '_ctx.closePath();', '' ].join('\n'); return code; @@ -1806,11 +1805,11 @@ Blockly.JavaScript['ugj_canvas_drawrect'] = function (block) { var value_h = Blockly.JavaScript.valueToCode(block, 'h', Blockly.JavaScript.ORDER_ATOMIC); var value_color = Blockly.JavaScript.valueToCode(block, 'color', Blockly.JavaScript.ORDER_ATOMIC); var code = [ - `ctx.beginPath();`, - `ctx.rect(${value_x}, ${value_y}, ${value_w}, ${value_h});`, - `ctx.fillStyle = ${value_color};`, - `ctx.fill();`, - `ctx.closePath();`, + `_ctx.beginPath();`, + `_ctx.rect(${value_x}, ${value_y}, ${value_w}, ${value_h});`, + `_ctx.fillStyle = ${value_color};`, + `_ctx.fill();`, + `_ctx.closePath();`, '' ].join('\n'); return code; @@ -1906,7 +1905,7 @@ Blockly.JavaScript['ugj_draw_grideyedata'] = function (block) { var colour_color_low = block.getFieldValue('color_low'); var value_temp_low = Blockly.JavaScript.valueToCode(block, 'temp_low', Blockly.JavaScript.ORDER_ATOMIC); var functionName = Blockly.JavaScript.provideFunction_( - 'mapVal', + '_mapVal', ['const ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = (val, inMin, inMax, outMin, outMax) => {', `return (val - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;`, '}' @@ -2124,8 +2123,8 @@ Blockly.JavaScript['ugj_event_key'] = function (block) { var dropdown_updown = block.getFieldValue('updown'); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - `document.addEventListener('${dropdown_updown}', async (e) => {`, - ` ${variable_key} = e.key;`, + `document.addEventListener('${dropdown_updown}', async (_e) => {`, + ` ${variable_key} = _e.key;`, statements_do, `}, false);`, '' @@ -2193,14 +2192,14 @@ Blockly.JavaScript['ugj_socket'] = function (block) { var variable_data = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('data'), Blockly.Variables.NAME_TYPE); var statements_data = Blockly.JavaScript.statementToCode(block, 'data'); Blockly.JavaScript.provideFunction_( - 'require_net', [`const net = require('net');`] + 'require_net', [`const _net = require('net');`] ); var code = [ - `var client = net.connect(${value_port}, ${value_host});`, - `client.on('connect', async ()=>{`, + `var _client = _net.connect(${value_port}, ${value_host});`, + `_client.on('connect', async ()=>{`, statements_connect, - `}).on('data', async data=>{`, - `${variable_data} = data.toString('utf-8', 0, data.length);`, + `}).on('data', async _data=>{`, + `${variable_data} = _data.toString('utf-8', 0, _data.length);`, statements_data, `}).on('close', ()=>{`, `console.log('Connection closed.');`, @@ -2230,7 +2229,7 @@ Blockly.Blocks['ugj_socket_write'] = { Blockly.JavaScript['ugj_socket_write'] = function (block) { var value_cmd = Blockly.JavaScript.valueToCode(block, 'cmd', Blockly.JavaScript.ORDER_ATOMIC); var code = [ - `client.write(${value_cmd});`, + `_client.write(${value_cmd});`, '' ].join('\n'); return code; @@ -2264,16 +2263,16 @@ Blockly.JavaScript['ugj_network_httpserver'] = function (block) { var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var value_response = Blockly.JavaScript.valueToCode(block, 'response', Blockly.JavaScript.ORDER_ATOMIC); Blockly.JavaScript.provideFunction_( - 'require_http', [`const http = require('http');`] + 'require_http', [`const _http = require('http');`] ); var code = [ - `let req, res;`, - `http.createServer(async (req, res) => {`, - `res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });`, - `${variable_url} = req.url;`, + `let _req, _res;`, + `_http.createServer(async (_req, _res) => {`, + `_res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });`, + `${variable_url} = _req.url;`, statements_do, - // `res.write('');`, - `res.end(${value_response});`, + // `_res.write('');`, + `_res.end(${value_response});`, `}).listen(3000);`, '' ].join('\n'); @@ -2302,7 +2301,7 @@ Blockly.Blocks['ugj_network_axios_geturl'] = { Blockly.JavaScript['ugj_network_axios_geturl'] = function (block) { var value_url = Blockly.JavaScript.valueToCode(block, 'url', Blockly.JavaScript.ORDER_ATOMIC); var functionName = Blockly.JavaScript.provideFunction_( - 'getUrl', + '_getUrl', [ `const axios = require('axios');`, 'const ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = async url => {', @@ -2351,28 +2350,28 @@ Blockly.JavaScript['ugj_network_sendmail'] = function (block) { var value_subject = Blockly.JavaScript.valueToCode(block, 'subject', Blockly.JavaScript.ORDER_ATOMIC); var value_text = Blockly.JavaScript.valueToCode(block, 'text', Blockly.JavaScript.ORDER_ATOMIC); Blockly.JavaScript.provideFunction_( - 'require_sendmail', [`const nodemailer = require('nodemailer');`] + 'require_sendmail', [`const _nodemailer = require('nodemailer');`] ); var code = [ - `let smtp = nodemailer.createTransport({`, + `let _smtp = _nodemailer.createTransport({`, `host: '192.168.0.201',`, `port: 25`, `});`, - `let message = {`, + `let _message = {`, `from: 'no-reply@oc.x0.to',`, `to: ${value_to},`, `subject: ${value_subject},`, `text: ${value_text}`, `};`, `try{`, - `smtp.sendMail(message, function(error, info){`, - `if(error){`, - `alert('送信エラー:' + error.message);`, + `_smtp.sendMail(_message, function(_error, _info){`, + `if(_error){`, + `alert('送信エラー:' + _error.message);`, `return;`, `}`, `console.log('send successfully');`, `});`, - `} catch(e) {alert('Error: ',e);}`, + `} catch(_e) {alert('Error: ',_e);}`, '' ].join('\n'); return code; @@ -2415,17 +2414,17 @@ Blockly.Blocks['ugj_webchat'] = { }; Blockly.JavaScript['ugj_webchat'] = function (block) { var code = [ - `const blackboard = document.getElementById('blackboard');`, - "blackboard.style.display = 'inline-block';", - `const inputForm = document.getElementById('inputForm');`, - "inputForm.style.display = 'inline-block';", - `const inputBox = document.getElementById('inputBox');`, - "inputBox.focus();", - "const remoteVideo = document.getElementById('maindisplay');", - `remoteVideo.style.display = 'inline-block';`, - "const localVideo = document.getElementById('subdisplay');", - `localVideo.style.display = 'inline-block';`, - `var localStream;`, + `const _blackboard = document.getElementById('blackboard');`, + "_blackboard.style.display = 'inline-block';", + `const _inputForm = document.getElementById('inputForm');`, + "_inputForm.style.display = 'inline-block';", + `const _inputBox = document.getElementById('inputBox');`, + "_inputBox.focus();", + "const _remoteVideo = document.getElementById('maindisplay');", + `_remoteVideo.style.display = 'inline-block';`, + "const _localVideo = document.getElementById('subdisplay');", + `_localVideo.style.display = 'inline-block';`, + `var _localStream;`, '' ].join('\n'); return code; @@ -2446,11 +2445,11 @@ Blockly.Blocks['ugj_getusermedia'] = { Blockly.JavaScript['ugj_getusermedia'] = function (block) { var code = [ `navigator.mediaDevices.getUserMedia({video: true, audio: false})`, - ' .then(stream => {', - ' localVideo.srcObject = stream;', - ' localStream = stream;', - ' }).catch( error => {', - ' console.error(\'mediaDevice.getUserMedia() error:\', error);', + ' .then(_stream => {', + ' _localVideo.srcObject = _stream;', + ' _localStream = _stream;', + ' }).catch( _error => {', + ' console.error(\'mediaDevice.getUserMedia() error:\', _error);', ' return;', ' });', '' @@ -2481,24 +2480,24 @@ Blockly.JavaScript['ugj_skyway_newpeer'] = function (block) { // var text_name = block.getFieldValue('NAME'); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - `const peer = new Peer(${variable_my_id}, {`, + `const _peer = new Peer(${variable_my_id}, {`, " key: window.__SKYWAY_KEY__,", " debug: 3", "});", - "peer.on('open', () => {", + "_peer.on('open', () => {", // ' ugj_blackboardWrite(`SkyWay: "${peer.id}" OK`)', - `${variable_my_id} = peer.id;`, - "inputForm.addEventListener('submit', onMakeCall);", + `${variable_my_id} = _peer.id;`, + "_inputForm.addEventListener('submit', _onMakeCall);", statements_do, "});", - "peer.on('error', err => alert(err.message));", - "const onMakeCall = e => {", - " e.preventDefault();", - " const call = peer.call(inputBox.value, localStream);", - " setupCallEventHandlers(call);", - " const connect = peer.connect(inputBox.value);", - " setupConnectEventHandlers(connect);", - " inputBox.value = '';", + "_peer.on('error', _err => alert(_err.message));", + "const _onMakeCall = _e => {", + " _e.preventDefault();", + " const _call = _peer.call(_inputBox.value, _localStream);", + " setupCallEventHandlers(_call);", + " const _connect = peer.connect(_inputBox.value);", + " setupConnectEventHandlers(_connect);", + " _inputBox.value = '';", "}", '' ].join('\n'); @@ -2519,12 +2518,12 @@ Blockly.Blocks['ugj_skyway_called'] = { }; Blockly.JavaScript['ugj_skyway_called'] = function (block) { var code = [ - "peer.on('call', call => {", - " call.answer(localStream);", - " setupCallEventHandlers(call);", + "_peer.on('call', _call => {", + " _call.answer(_localStream);", + " _setupCallEventHandlers(_call);", "});", - "peer.on('connection', connect => {", - " setupConnectEventHandlers(connect);", + "_peer.on('connection', _connect => {", + " _setupConnectEventHandlers(_connect);", "});", '' ].join('\n'); @@ -2550,10 +2549,10 @@ Blockly.JavaScript['ugj_skyway_events'] = function (block) { var variable_remote_id = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('remote_id'), Blockly.Variables.NAME_TYPE); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - "const setupCallEventHandlers = call => call.on('stream', stream => remoteVideo.srcObject = stream);", - "const setupConnectEventHandlers = connect => {", - " inputForm.removeEventListener('submit', onMakeCall);", - ` ${variable_remote_id} = connect.remoteId;`, + "const _setupCallEventHandlers = _call => _call.on('stream', _stream => _remoteVideo.srcObject = _stream);", + "const _setupConnectEventHandlers = _connect => {", + " _inputForm.removeEventListener('submit', _onMakeCall);", + ` ${variable_remote_id} = _connect.remoteId;`, statements_do, "}", '' @@ -2578,8 +2577,8 @@ Blockly.Blocks['ugj_skyway_eventopen'] = { Blockly.JavaScript['ugj_skyway_eventopen'] = function (block) { var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - " connect.on('open', () => {", - " inputForm.addEventListener('submit', onSendMsg)", + " _connect.on('open', () => {", + " _inputForm.addEventListener('submit', _onSendMsg)", statements_do, " });", '' @@ -2607,8 +2606,8 @@ Blockly.JavaScript['ugj_skyway_eventdata'] = function (block) { var variable_data = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('data'), Blockly.Variables.NAME_TYPE); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - " connect.on('data', data => {", - ` ${variable_data} = data;`, + " _connect.on('data', _data => {", + ` ${variable_data} = _data;`, statements_do, " });", '' @@ -2636,10 +2635,10 @@ Blockly.JavaScript['ugj_skyway_eventsend'] = function (block) { var variable_data = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('data'), Blockly.Variables.NAME_TYPE); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - " const onSendMsg = () => {", - ` ${variable_data} = inputBox.value;`, - ` connect.send(${variable_data});`, - " inputBox.value = '';", + " const _onSendMsg = () => {", + ` ${variable_data} = _inputBox.value;`, + ` _connect.send(${variable_data});`, + " _inputBox.value = '';", statements_do, " }", '' @@ -2675,9 +2674,9 @@ Blockly.JavaScript['ugj_file_readsync'] = function (block) { var dropdown_encoding = block.getFieldValue('encoding'); let filepath = ugj_const.doc_root + value_filename.replace(/\'/g, ''); Blockly.JavaScript.provideFunction_( - 'require_fs', [`const fs = require('fs');`] + 'require_fs', [`const _fs = require('fs');`] ); - var code = `fs.readFileSync('${filepath}', '${dropdown_encoding}')`; + var code = `_fs.readFileSync('${filepath}', '${dropdown_encoding}')`; return [code, Blockly.JavaScript.ORDER_ATOMIC]; }; @@ -2779,22 +2778,22 @@ Blockly.JavaScript['ugj_event_answer'] = function (block) { var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ `ugj_fukidashi(${value_question}, 0);`, - `inputForm = document.getElementById('inputForm');`, - `inputBox = document.getElementById('inputBox');`, - "inputForm.style.display = 'inline-block'", - "inputBox.focus();", - "const inputFunc = async () => { ", - " if (inputBox.value.length > 0) {", - ` ${variable_answer} = inputBox.value;`, - ' inputForm.style.display = "none"', - " inputBox.value = '';", + `_inputForm = document.getElementById('inputForm');`, + `_inputBox = document.getElementById('inputBox');`, + "_inputForm.style.display = 'inline-block'", + "_inputBox.focus();", + "const _inputFunc = async () => { ", + " if (_inputBox.value.length > 0) {", + ` ${variable_answer} = _inputBox.value;`, + ' _inputForm.style.display = "none"', + " _inputBox.value = '';", " document.getElementById('canvas').getContext('2d').clearRect(ugj_fdRecentBox.x,ugj_fdRecentBox.y,ugj_fdRecentBox.w,ugj_fdRecentBox.h);", statements_do, " console.log('Removing listener...');", - " inputForm.removeEventListener('submit', inputFunc );", + " _inputForm.removeEventListener('submit', _inputFunc );", " }", "}", - "inputForm.addEventListener('submit', inputFunc );", + "_inputForm.addEventListener('submit', _inputFunc );", '' ].join('\n'); return code; @@ -2855,14 +2854,14 @@ Blockly.JavaScript['ugj_spawn'] = function (block) { var variable_data = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('data'), Blockly.Variables.NAME_TYPE); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - `let child = require('child_process').spawn(${value_childprocess});`, - `elutil.addChild(child);`, - "child.stderr.on('data', data => { console.error(data.toString()) })", - "child.stdout.on('data', async data => {", - `${variable_data} = data.toString();`, + `let _child = require('child_process').spawn(${value_childprocess});`, + `elutil.addChild(_child);`, + "_child.stderr.on('data', _data => { console.error(_data.toString()) })", + "_child.stdout.on('data', async _data => {", + `${variable_data} = _data.toString();`, statements_do, "})", - "child.on('close', (code, signal) => { if (code !== 0) { console.error(`process exited with code ${code}, signal ${signal}`)}", + "_child.on('close', (_code, _signal) => { if (_code !== 0) { console.error(`process exited with code ${_code}, signal ${_signal}`)}", "})", '' ].join("\n"); @@ -3106,7 +3105,7 @@ Blockly.JavaScript['ugj_blackboard_write'] = function (block) { var dropdown_style = block.getFieldValue('style'); var dropdown_line = block.getFieldValue('line'); var funcAppendDivName = Blockly.JavaScript.provideFunction_( - 'appendDiv', + '_appendDiv', ['const ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = termEl => {', `let el = document.createElement('div');`, `termEl.appendChild(el);`, @@ -3114,7 +3113,7 @@ Blockly.JavaScript['ugj_blackboard_write'] = function (block) { '}'] ); var funcTermWriteName = Blockly.JavaScript.provideFunction_( - 'blackboardWrite', + '_blackboardWrite', ['const ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = (text, color, style, line) => {', `let termEl = document.getElementById('blackboard')`, 'let el = null;', @@ -3209,7 +3208,7 @@ Blockly.Blocks['ugj_sleep'] = { Blockly.JavaScript['ugj_sleep'] = function (block) { var value_sec = Blockly.JavaScript.valueToCode(block, 'sec', Blockly.JavaScript.ORDER_ATOMIC); var functionName = Blockly.JavaScript.provideFunction_( - 'sleep', + '_sleep', ['const ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = sec =>', 'new Promise(r => setTimeout(r, sec * 1000));'] ); @@ -3325,7 +3324,7 @@ Blockly.JavaScript['ugj_set_interval'] = function (block) { var value_sec = Blockly.JavaScript.valueToCode(block, 'sec', Blockly.JavaScript.ORDER_ATOMIC); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - 'let interval = setInterval( async () => {', + 'let _interval = setInterval( async () => {', statements_do, `}, ${value_sec}*1000);`, '' @@ -3348,7 +3347,7 @@ Blockly.Blocks['ugj_special_clearinterval'] = { } }; Blockly.JavaScript['ugj_special_clearinterval'] = function (block) { - var code = 'clearInterval(interval);\n'; + var code = 'clearInterval(_interval);\n'; return code; }; /********+********/ @@ -3375,7 +3374,7 @@ Blockly.Blocks['ugj_set_timeout'] = { Blockly.JavaScript['ugj_set_timeout'] = function (block) { var value_sec = Blockly.JavaScript.valueToCode(block, 'sec', Blockly.JavaScript.ORDER_ATOMIC); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); - var code = `let interval = setTimeout(async () => {\n${statements_do}}, ${value_sec}*1000);\n`; + var code = `let _interval = setTimeout(async () => {\n${statements_do}}, ${value_sec}*1000);\n`; return code; }; @@ -3399,12 +3398,12 @@ Blockly.JavaScript['ugj_library_load'] = function (block) { var value_lib = Blockly.JavaScript.valueToCode(block, 'lib', Blockly.JavaScript.ORDER_ATOMIC); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); var code = [ - `let scriptEl = document.createElement('script');`, - `scriptEl.onload = async ev => {`, + `let _scriptEl = document.createElement('script');`, + `_scriptEl.onload = async _ev => {`, `${statements_do}`, `};`, - `scriptEl.src = ${value_lib};`, - `document.getElementsByTagName('head')[0].appendChild(scriptEl);`, + `_scriptEl.src = ${value_lib};`, + `document.getElementsByTagName('head')[0].appendChild(_scriptEl);`, '' ].join('\n'); return code;