text,length,is_long_context,metric_val,label_metric "/* SelectionList.ino Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { // U8g2 SH1106 Proto-Shield //u8g2.begin(/* menu_select_pin= */ 2, /* menu_next_pin= */ 4, /* menu_prev_pin= */ 7, /* menu_up_pin= */ 6, /* menu_down_pin= */ 5, /* menu_home_pin= */ 3); // DOGS102 Shield (http://shieldlist.org/controlconnection/dogs102) // u8g2.begin(/* menu_select_pin= */ 5, /* menu_next_pin= */ 4, /* menu_prev_pin= */ 2, /* menu_up_pin= */ U8X8_PIN_NONE, /* menu_down_pin= */ U8X8_PIN_NONE, /* menu_home_pin= */ 3); // DOGM128 Shield (http://shieldlist.org/schmelle2/dogm128) + DOGXL160 Shield //u8g2.begin(/* menu_select_pin= */ 2, /* menu_next_pin= */ 3, /* menu_prev_pin= */ 7, /* menu_up_pin= */ U8X8_PIN_NONE, /* menu_down_pin= */ U8X8_PIN_NONE, /* menu_home_pin= */ 8); // MKR Zero Test Board u8g2.begin(/*Select=*/ 0, /*Right/Next=*/ 1, /*Left/Prev=*/ 2, /*Up=*/ 4, /*Down=*/ 3, /*Home/Cancel=*/ A6); // Arduboy //u8g2.begin(/*Select=*/ A0, /*Right/Next=*/ 5, /*Left/Prev=*/ 9, /*Up=*/ 8, /*Down=*/ 10, /*Home/Cancel=*/ A1); // Arduboy DevKit //u8g2.begin(/*Select=*/ 7, /*Right/Next=*/ A1, /*Left/Prev=*/ A2, /*Up=*/ A0, /*Down=*/ A3, /*Home/Cancel=*/ 8); // Arduboy 10 (Production) u8g2.setFont(u8g2_font_6x12_tr); } const char *string_list = ""Altocumulus\\n"" ""Altostratus\\n"" ""Cirrocumulus\\n"" ""Cirrostratus\\n"" ""Cirrus\\n"" ""Cumulonimbus\\n"" ""Cumulus\\n"" ""Nimbostratus\\n"" ""Stratocumulus\\n"" ""Stratus""; uint8_t current_selection = 1; void loop(void) { current_selection = u8g2.userInterfaceSelectionList( ""Cloud Types"", current_selection, string_list); if ( current_selection == 0 ) { u8g2.userInterfaceMessage( ""Nothing selected."", """", """", "" ok ""); } else { u8g2.userInterfaceMessage( ""Selection:"", u8x8_GetStringLineStart(current_selection-1, string_list ), """", "" ok \\n cancel ""); } } ",16163,True,4621.855508488235,median "/** * This is a generated class and is not intended for modification. To customize behavior * of this service wrapper you may modify the generated sub-class of this class - Jetfire.as. */ package gov.iowadot.jetfire { import com.adobe.fiber.core.model_internal; import com.adobe.fiber.services.wrapper.WebServiceWrapper; import com.adobe.serializers.utility.TypeUtility; import mx.rpc.AbstractOperation; import mx.rpc.AsyncToken; import mx.rpc.soap.mxml.Operation; import mx.rpc.soap.mxml.WebService; [ExcludeClass] internal class _Super_Jetfire extends com.adobe.fiber.services.wrapper.WebServiceWrapper { // Constructor public function _Super_Jetfire() { // initialize service control _serviceControl = new mx.rpc.soap.mxml.WebService(); var operations:Object = new Object(); var operation:mx.rpc.soap.mxml.Operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToCoordRouteS""); operation.resultType = Object; operations[""XmlObjectToCoordRouteS""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""Reproject""); operation.resultType = Object; operations[""Reproject""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""LatLongToLrs""); operation.resultType = Object; operations[""LatLongToLrs""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""CoordRouteToDatumAP""); operation.resultType = Object; operations[""CoordRouteToDatumAP""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""CoordRouteToDatumAL""); operation.resultType = Object; operations[""CoordRouteToDatumAL""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToCoordRouteU""); operation.resultType = Object; operations[""XmlObjectToCoordRouteU""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""RefPostToDatumUP""); operation.resultType = Object; operations[""RefPostToDatumUP""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""LrsToLatLong""); operation.resultType = Object; operations[""LrsToLatLong""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""CoordRouteToDatumUL""); operation.resultType = Object; operations[""CoordRouteToDatumUL""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToLiteral""); operation.resultType = Object; operations[""XmlObjectToLiteral""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToRefPostU""); operation.resultType = Object; operations[""XmlObjectToRefPostU""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""RefPostToDatumUL""); operation.resultType = Object; operations[""RefPostToDatumUL""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetRouteIdU""); operation.resultType = Object; operations[""GetRouteIdU""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""RefPostToDatumAP""); operation.resultType = Object; operations[""RefPostToDatumAP""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetRouteLength""); operation.resultType = Object; operations[""GetRouteLength""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""CoordRouteToDatumUP""); operation.resultType = Object; operations[""CoordRouteToDatumUP""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetRouteList""); operation.resultType = Object; operations[""GetRouteList""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetGeographicExtentList""); operation.resultType = Object; operations[""GetGeographicExtentList""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetGeoExtentIdByName""); operation.resultType = Object; operations[""GetGeoExtentIdByName""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToRefPost""); operation.resultType = Object; operations[""XmlObjectToRefPost""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetBestRouteId""); operation.resultType = Object; operations[""GetBestRouteId""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetGeoExtentListByRouteSysName""); operation.resultType = Object; operations[""GetGeoExtentListByRouteSysName""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToCoordRouteA""); operation.resultType = Object; operations[""XmlObjectToCoordRouteA""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetCardinalDirection""); operation.resultType = Object; operations[""GetCardinalDirection""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetRouteSystemList""); operation.resultType = Object; operations[""GetRouteSystemList""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToRefPostA""); operation.resultType = Object; operations[""XmlObjectToRefPostA""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetRouteSysIdByName""); operation.resultType = Object; operations[""GetRouteSysIdByName""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetRefPostList""); operation.resultType = Object; operations[""GetRefPostList""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""CoordRouteToDatumSL""); operation.resultType = Object; operations[""CoordRouteToDatumSL""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""RefPostToDatumSP""); operation.resultType = Object; operations[""RefPostToDatumSP""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToCoordRoute""); operation.resultType = Object; operations[""XmlObjectToCoordRoute""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToWKT""); operation.resultType = Object; operations[""XmlObjectToWKT""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetGeoExtentListByRouteSysId""); operation.resultType = Object; operations[""GetGeoExtentListByRouteSysId""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""SnapXYToDatum""); operation.resultType = Object; operations[""SnapXYToDatum""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""RefPostToDatumAL""); operation.resultType = Object; operations[""RefPostToDatumAL""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""RefPostToDatumSL""); operation.resultType = Object; operations[""RefPostToDatumSL""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""XmlObjectToRefPostS""); operation.resultType = Object; operations[""XmlObjectToRefPostS""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""CoordRouteToDatumSP""); operation.resultType = Object; operations[""CoordRouteToDatumSP""] = operation; operation = new mx.rpc.soap.mxml.Operation(null, ""GetRouteIdA""); operation.resultType = Object; operations[""GetRouteIdA""] = operation; _serviceControl.operations = operations; try { _serviceControl.convertResultHandler = com.adobe.serializers.utility.TypeUtility.convertResultHandler; } catch (e: Error) { /* Flex 3.4 and eralier does not support the convertResultHandler functionality. */ } _serviceControl.service = ""JetFire""; _serviceControl.port = ""JetFireSoap""; wsdl = ""http://lrs/Service.asmx?wsdl""; model_internal::loadWSDLIfNecessary(); model_internal::initialize(); } /** * This method is a generated wrapper used to call the 'XmlObjectToCoordRouteS' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToCoordRouteS(vXmlObject:String, vRouteId:int, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToCoordRouteS""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vRouteId,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'Reproject' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function Reproject(vX:Number, vY:Number, vInSRID:int, vOutSRID:int) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""Reproject""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vX,vY,vInSRID,vOutSRID) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'LatLongToLrs' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function LatLongToLrs(vX:Number, vY:Number) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""LatLongToLrs""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vX,vY) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'CoordRouteToDatumAP' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function CoordRouteToDatumAP(vRouteSystemName:String, vRoutePrefix:String, vRouteName:String, vRouteType:String, vRouteSuffix:String, vRouteDirection:String, vGeographicExtentName:String, vX:Number, vY:Number, vTolerance:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""CoordRouteToDatumAP""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRoutePrefix,vRouteName,vRouteType,vRouteSuffix,vRouteDirection,vGeographicExtentName,vX,vY,vTolerance,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'CoordRouteToDatumAL' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function CoordRouteToDatumAL(vRouteSystemName:String, vRoutePrefix:String, vRouteName:String, vRouteType:String, vRouteSuffix:String, vRouteDirection:String, vGeographicExtentName:String, vStartX:Number, vStartY:Number, vEndX:Number, vEndY:Number, vTolerance:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""CoordRouteToDatumAL""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRoutePrefix,vRouteName,vRouteType,vRouteSuffix,vRouteDirection,vGeographicExtentName,vStartX,vStartY,vEndX,vEndY,vTolerance,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToCoordRouteU' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToCoordRouteU(vXmlObject:String, vRouteSystemName:String, vRouteDesignator:String, vGeographicExtentName:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToCoordRouteU""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vRouteSystemName,vRouteDesignator,vGeographicExtentName,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'RefPostToDatumUP' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function RefPostToDatumUP(vRouteSystemName:String, vRouteDesignator:String, vGeographicExtentName:String, vPostName:String, vOffset:Number, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""RefPostToDatumUP""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRouteDesignator,vGeographicExtentName,vPostName,vOffset,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'LrsToLatLong' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function LrsToLatLong(vX:Number, vY:Number) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""LrsToLatLong""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vX,vY) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'CoordRouteToDatumUL' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function CoordRouteToDatumUL(vRouteSystemName:String, vRouteDesignator:String, vGeographicExtentName:String, vStartX:Number, vStartY:Number, vEndX:Number, vEndY:Number, vTolerance:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""CoordRouteToDatumUL""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRouteDesignator,vGeographicExtentName,vStartX,vStartY,vEndX,vEndY,vTolerance,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToLiteral' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToLiteral(vXmlObject:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToLiteral""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToRefPostU' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToRefPostU(vXmlObject:String, vRouteSystemName:String, vRouteDesignator:String, vGeographicExtentName:String, vOffsetType:int, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToRefPostU""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vRouteSystemName,vRouteDesignator,vGeographicExtentName,vOffsetType,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'RefPostToDatumUL' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function RefPostToDatumUL(vRouteSystemName:String, vRouteDesignator:String, vGeographicExtentName:String, vStartPostName:String, vStartOffset:Number, vEndPostName:String, vEndOffset:Number, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""RefPostToDatumUL""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRouteDesignator,vGeographicExtentName,vStartPostName,vStartOffset,vEndPostName,vEndOffset,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetRouteIdU' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetRouteIdU(vRouteSystemName:String, vRouteDesignator:String, vGeographicExtentName:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetRouteIdU""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRouteDesignator,vGeographicExtentName) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'RefPostToDatumAP' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function RefPostToDatumAP(vRouteSystemName:String, vRoutePrefix:String, vRouteName:String, vRouteType:String, vRouteSuffix:String, vRouteDirection:String, vGeographicExtentName:String, vPostName:String, vOffset:Number, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""RefPostToDatumAP""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRoutePrefix,vRouteName,vRouteType,vRouteSuffix,vRouteDirection,vGeographicExtentName,vPostName,vOffset,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetRouteLength' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetRouteLength(vRouteId:int) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetRouteLength""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteId) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'CoordRouteToDatumUP' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function CoordRouteToDatumUP(vRouteSystemName:String, vRouteDesignator:String, vGeographicExtentName:String, vX:Number, vY:Number, vTolerance:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""CoordRouteToDatumUP""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRouteDesignator,vGeographicExtentName,vX,vY,vTolerance,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetRouteList' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetRouteList(vSystemId:String, vExtentId:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetRouteList""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vSystemId,vExtentId) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetGeographicExtentList' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetGeographicExtentList() : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetGeographicExtentList""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send() ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetGeoExtentIdByName' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetGeoExtentIdByName(vExtentName:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetGeoExtentIdByName""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vExtentName) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToRefPost' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToRefPost(vXmlObject:String, vRouteId:int, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToRefPost""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vRouteId,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetBestRouteId' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetBestRouteId(vXmlObject:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetBestRouteId""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetGeoExtentListByRouteSysName' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetGeoExtentListByRouteSysName(vSystemName:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetGeoExtentListByRouteSysName""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vSystemName) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToCoordRouteA' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToCoordRouteA(vXmlObject:String, vRouteSystemName:String, vRoutePrefix:String, vRouteName:String, vRouteType:String, vRouteSuffix:String, vRouteDirection:String, vGeographicExtentName:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToCoordRouteA""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vRouteSystemName,vRoutePrefix,vRouteName,vRouteType,vRouteSuffix,vRouteDirection,vGeographicExtentName,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetCardinalDirection' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetCardinalDirection(vSystemId:int, vExtentId:int, vRouteName:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetCardinalDirection""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vSystemId,vExtentId,vRouteName) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetRouteSystemList' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetRouteSystemList() : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetRouteSystemList""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send() ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToRefPostA' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToRefPostA(vXmlObject:String, vRouteSystemName:String, vRoutePrefix:String, vRouteName:String, vRouteType:String, vRouteSuffix:String, vRouteDirection:String, vGeographicExtentName:String, vOffsetType:int, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToRefPostA""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vRouteSystemName,vRoutePrefix,vRouteName,vRouteType,vRouteSuffix,vRouteDirection,vGeographicExtentName,vOffsetType,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetRouteSysIdByName' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetRouteSysIdByName(vSystemName:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetRouteSysIdByName""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vSystemName) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetRefPostList' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetRefPostList(vRouteId:int) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetRefPostList""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteId) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'CoordRouteToDatumSL' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function CoordRouteToDatumSL(vRouteId:int, vStartX:Number, vStartY:Number, vEndX:Number, vEndY:Number, vTolerance:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""CoordRouteToDatumSL""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteId,vStartX,vStartY,vEndX,vEndY,vTolerance,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'RefPostToDatumSP' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function RefPostToDatumSP(vRouteId:int, vPostName:String, vOffset:Number, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""RefPostToDatumSP""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteId,vPostName,vOffset,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToCoordRoute' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToCoordRoute(vXmlObject:String, vRouteId:int, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToCoordRoute""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vRouteId,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToWKT' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToWKT(vXmlObject:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToWKT""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetGeoExtentListByRouteSysId' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetGeoExtentListByRouteSysId(vSystemId:int) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetGeoExtentListByRouteSysId""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vSystemId) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'SnapXYToDatum' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function SnapXYToDatum(vX:Number, vY:Number, vTolerance:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""SnapXYToDatum""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vX,vY,vTolerance,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'RefPostToDatumAL' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function RefPostToDatumAL(vRouteSystemName:String, vRoutePrefix:String, vRouteName:String, vRouteType:String, vRouteSuffix:String, vRouteDirection:String, vGeographicExtentName:String, vStartPostName:String, vStartOffset:Number, vEndPostName:String, vEndOffset:Number, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""RefPostToDatumAL""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRoutePrefix,vRouteName,vRouteType,vRouteSuffix,vRouteDirection,vGeographicExtentName,vStartPostName,vStartOffset,vEndPostName,vEndOffset,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'RefPostToDatumSL' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function RefPostToDatumSL(vRouteId:int, vStartPostName:String, vStartOffset:Number, vEndPostName:String, vEndOffset:Number, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""RefPostToDatumSL""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteId,vStartPostName,vStartOffset,vEndPostName,vEndOffset,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'XmlObjectToRefPostS' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function XmlObjectToRefPostS(vXmlObject:String, vRouteId:int, vOffsetType:int, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""XmlObjectToRefPostS""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vXmlObject,vRouteId,vOffsetType,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'CoordRouteToDatumSP' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function CoordRouteToDatumSP(vRouteId:int, vX:Number, vY:Number, vTolerance:String, vDate:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""CoordRouteToDatumSP""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteId,vX,vY,vTolerance,vDate) ; return _internal_token; } /** * This method is a generated wrapper used to call the 'GetRouteIdA' operation. It returns an mx.rpc.AsyncToken whose * result property will be populated with the result of the operation when the server response is received. * To use this result from MXML code, define a CallResponder component and assign its token property to this method's return value. * You can then bind to CallResponder.lastResult or listen for the CallResponder.result or fault events. * * @see mx.rpc.AsyncToken * @see mx.rpc.CallResponder * * @return an mx.rpc.AsyncToken whose result property will be populated with the result of the operation when the server response is received. */ public function GetRouteIdA(vRouteSystemName:String, vRoutePrefix:String, vRouteName:String, vRouteType:String, vRouteSuffix:String, vRouteDirection:String, vGeographicExtentName:String) : mx.rpc.AsyncToken { model_internal::loadWSDLIfNecessary(); var _internal_operation:mx.rpc.AbstractOperation = _serviceControl.getOperation(""GetRouteIdA""); var _internal_token:mx.rpc.AsyncToken = _internal_operation.send(vRouteSystemName,vRoutePrefix,vRouteName,vRouteType,vRouteSuffix,vRouteDirection,vGeographicExtentName) ; return _internal_token; } } } ",12344,True,4160.4830705575305,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.containers { /* import flash.display.DisplayObject; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import mx.containers.dividedBoxClasses.BoxDivider; import mx.core.EdgeMetrics; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.IInvalidating; */ import mx.core.IUIComponent; import mx.core.UIComponent; /* import mx.core.mx_internal; import mx.events.ChildExistenceChangedEvent; import mx.events.DividerEvent; import mx.managers.CursorManager; import mx.managers.CursorManagerPriority; import mx.styles.IStyleManager2; import mx.styles.StyleManager; use namespace mx_internal; */ //-------------------------------------- // Events //-------------------------------------- /** * Dispatched multiple times as the user drags any divider. * * The dividerDrag event is dispatched * after the dividerPress event * and before the dividerRelease event. * * @eventType mx.events.DividerEvent.DIVIDER_DRAG * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Event(name=""dividerDrag"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user presses any divider in this container. * * The dividerPress event is dispatched * before any dividerDrag events are dispatched. * * @eventType mx.events.DividerEvent.DIVIDER_PRESS * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Event(name=""dividerPress"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user releases a divider. * * The dividerRelease event is dispatched * after the dividerDrag events, * but before the container's children are resized. * The divider's x and y properties are not updated until * after this event is triggered. As a result, a call to * hDividerBox.getDividerAt(0).x will return * the value of the original x position of the first divider. If you want the * position of the divider after the move, you can access it when the * DividerBox's updateComplete event has been triggered. * * @eventType mx.events.DividerEvent.DIVIDER_RELEASE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ Event(name=""dividerRelease"", type=""mx.events.DividerEvent"")] /** * A DividedBox container measures and lays out its children * horizontally or vertically in exactly the same way as a * Box container, but it inserts * draggable dividers in the gaps between the children. * Users can drag any divider to resize the children on each side. * *

The DividedBox class is the base class for the more commonly used * HDividedBox and VDividedBox classes.

* *

The direction property of a DividedBox container, inherited * from Box container, determines whether it has horizontal * or vertical layout.

* *

A DividedBox, HDividedBox, or VDividedBox container has the following default sizing characteristics:

* * * * * * * * * * * * * * * * * *
CharacteristicDescription
Default sizeVertical DividedBox Height is large enough to hold all of its children at the default or explicit * heights of the children, plus any vertical gap between the children, plus the top and bottom padding of the * container. The width is the default or explicit width of the widest child, plus the left and right padding of * the container. *
Horizontal DividedBox Width is large enough to hold all of its children at the * default or explicit widths of the children, plus any horizontal gap between the children, plus the left and * right padding of the container. Height is the default or explicit height of the tallest child * plus the top and bottom padding of the container.
Default padding0 pixels for the top, bottom, left, and right values.
Default gap10 pixels for the horizontal and vertical gaps.
* * @mxml * *

The <mx:DividedBox> tag inherits all of the tag * attributes of its superclass, and adds the following tag attributes:

* *
 *  <mx:DividedBox
 *    Properties
 *    liveDragging=""false|true""
 *    resizeToContent=""false|true""
 *  
 *    Styles
 *    dividerAffordance=""6""
 *    dividerAlpha=""0.75""
 *    dividerColor=""0x6F7777""
 *    dividerSkin=""'mx.skins.BoxDividerSkin' symbol in Assets.swf""
 *    dividerThickness=""3""
 *    horizontalDividerCursor=""'mx.skins.cursor.HBoxDivider' symbol in Assets.swf""
 *    verticalDividerCursor=""'mx.skins.cursor.VBoxDivider' symbol in Assets.swf""
 * 
 *    Events
 *    dividerPress=""No default""
 *    dividerDrag=""No default""
 *    dividerRelease=""No default""
 *    >
 *      ...
 *      child tags
 *      ...
 *  </mx:DividedBox>
 *  
* * @see mx.containers.HDividedBox * @see mx.containers.VDividedBox * * @includeExample examples/DividedBoxExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DividedBox extends Box { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static const PROXY_DIVIDER_INDEX:int = 999; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function DividedBox() { super(); // addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler); // addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, // childRemoveHandler); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Container for holding divider objects. */ private var dividerLayer:UIComponent = null; /** * @private */ //mx_internal var activeDivider:BoxDivider; /** * @private */ private var activeDividerIndex:int = -1; /** * @private */ private var activeDividerStartPosition:Number; /** * @private */ private var dragStartPosition:Number; /** * @private */ private var dragDelta:Number; /** * @private */ private var oldChildSizes:Array /* of ChildSizeInfo */; /** * @private */ private var minDelta:Number; /** * @private */ private var maxDelta:Number; /** * @private * Only allow a single divider to move at a time. */ private var dontCoalesceDividers:Boolean; /** * @private */ //private var cursorID:int = CursorManager.NO_CURSOR; /** * @private * We'll measure ourselves once and then store the results here * for the lifetime of the DividedBox. */ private var dbMinWidth:Number; private var dbMinHeight:Number; private var dbPreferredWidth:Number; private var dbPreferredHeight:Number; /** * @private */ private var layoutStyleChanged:Boolean = false; /** * @private */ private var _resizeToContent:Boolean = false; /** * @private * Number of children with their includeInLayout set to true. The rest of * the children don't count. */ private var numLayoutChildren:int = 0; //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- /** * @private */ // override public function set moduleFactory(moduleFactory:IFlexModuleFactory):void // { // super.moduleFactory = moduleFactory; // // styleManager.registerSizeInvalidatingStyle(""dividerAffordance""); // styleManager.registerSizeInvalidatingStyle(""dividerThickness""); // } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // direction //---------------------------------- /** * @private */ override public function set direction(value:String):void { if (super.direction != value) { super.direction = value; // Need to invalidate all our dividers // if (dividerLayer) // { // for (var i:int = 0; i < dividerLayer.numChildren; i++) // getDividerAt(i).invalidateDisplayList(); // } } } //---------------------------------- // dividerClass //---------------------------------- /** * The class for the divider between the children. * * @default mx.containers.dividedBoxClasses.BoxDivider * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // protected var dividerClass:Class = BoxDivider; //---------------------------------- // liveDragging //---------------------------------- // [Inspectable(category=""General"")] /** * If true, the children adjacent to a divider * are continuously resized while the user drags it. * If false, they are not resized * until the user releases the divider. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public var liveDragging:Boolean = false; //---------------------------------- // numDividers //---------------------------------- /** * The number of dividers. * The count is always numChildren - 1. * * @return The number of dividers. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get numDividers():int { // if (dividerLayer) // if (!liveDragging && activeDivider) // return dividerLayer.numChildren-1; // else // return dividerLayer.numChildren; // else // return 0; trace(""numDividers not implemented""); return 0; } //---------------------------------- // resizeToContent //---------------------------------- /** * If true, the DividedBox automatically resizes to the size * of its children. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get resizeToContent():Boolean { return _resizeToContent; } /** * @private */ public function set resizeToContent(value:Boolean):void { if (value != _resizeToContent) { _resizeToContent = value; if (value) invalidateSize(); } } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private * Override of the measure method of Box. * *

This function is almost identical to the Box version except * that more extensive testing of the min, max * boundary conditions is performed. This is because the DividedBox allows * default values to be less than the min value of a control.

*/ // override protected function measure():void // { // super.measure(); // // // We only measure ourselves once, since as we change the // // size of children, they in turn change the preferred sizes // // // // We need to copy the cached values into the measured fields // // again to handle the case where scaleX or scaleY is not 1.0. // // When the ViewStack is zoomed, code in UIComponent.measureSizes // // scales the measuredWidth/Height values every time that // // measureSizes is called. (Bug 100749) // if (!isNaN(dbPreferredWidth) && !_resizeToContent && !layoutStyleChanged) // { // measuredMinWidth = dbMinWidth; // measuredMinHeight = dbMinHeight; // measuredWidth = dbPreferredWidth; // measuredHeight = dbPreferredHeight; // return; // } // // layoutStyleChanged = false; // // var isVertical:Boolean = this.isVertical(); // var minWidth:Number = 0; // var minHeight:Number = 0; // var preferredWidth:Number = 0; // var preferredHeight:Number = 0; // // var n:int = numChildren; // for (var i:int = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // var prefW:Number = child.getExplicitOrMeasuredWidth(); // var prefH:Number = child.getExplicitOrMeasuredHeight(); // // var minW:Number = child.minWidth; // var minH:Number = child.minHeight; // // var wFlex:Boolean = !isNaN(child.percentWidth); // var hFlex:Boolean = !isNaN(child.percentHeight); // // // Make sure we take the lowest of the low, since pref < min. // var smallestMinW:Number = Math.min(prefW, minW); // var smallestMinH:Number = Math.min(prefH, minH); // // if (isVertical) // { // minWidth = Math.max(wFlex ? minW : prefW, minWidth); // preferredWidth = Math.max(prefW, preferredWidth); // minHeight += hFlex ? smallestMinH : prefH; // preferredHeight += prefH; // } // else // { // minWidth += wFlex ? smallestMinW : prefW; // preferredWidth += prefW; // minHeight = Math.max(hFlex ? minH : prefH, minHeight); // preferredHeight = Math.max(prefH, preferredHeight); // } // } // // var wPadding:Number = layoutObject.widthPadding(numLayoutChildren); // var hPadding:Number = layoutObject.heightPadding(numLayoutChildren); // // measuredMinWidth = dbMinWidth = minWidth + wPadding; // measuredMinHeight = dbMinHeight = minHeight + hPadding; // measuredWidth = dbPreferredWidth = preferredWidth + wPadding; // measuredHeight = dbPreferredHeight = preferredHeight + hPadding; // } /** * @private */ // override protected function updateDisplayList(unscaledWidth:Number, // unscaledHeight:Number):void // { // var n:int; // var i:int; // // // This method gets called while dragging a divider, // // but we don't want to do anything then. // if (!liveDragging && activeDivider) // { // n = numChildren; // for (i = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // // Clear out measured min/max // // so super.layout() doesn't use them. // child.measuredMinWidth = 0; // child.measuredMinHeight = 0; // } // return; // } // // // Before we allow layout, let's clear out any measured min // // values of our children so that they don't restrict us. // // We only honour explicitly set mins/maxs. // // We also try to remove any excess space, but tweaking // // the % values on the flexible components. // preLayoutAdjustment(); // // // Let Box lay out the children. // super.updateDisplayList(unscaledWidth, unscaledHeight); // // postLayoutAdjustment(); // // // Lay out the dividers. // if (!dividerLayer) // return; // // var vm:EdgeMetrics = viewMetrics; // // dividerLayer.x = vm.left; // dividerLayer.y = vm.top; // // var prevChild:IUIComponent = null; // var dividerIndex:int = 0; // n = numChildren; // for (i = 0; i < n; i++) // { // child = UIComponent(getChildAt(i)); // if (child.includeInLayout) // { // if (prevChild) // { // layoutDivider(dividerIndex, unscaledWidth, unscaledHeight, prevChild, child); // dividerIndex++; // } // prevChild = child; // } // } // } /** * @private */ // override protected function scrollChildren():void // { // super.scrollChildren(); // // // Scroll divider layer. // if (contentPane && dividerLayer) // dividerLayer.scrollRect = contentPane.scrollRect; // } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Returns a reference to the specified BoxDivider object * in this DividedBox container or null if it doesn't exist. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @return A BoxDivider object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public function getDividerAt(i:int):BoxDivider // { // if (dividerLayer) { // // Check whether this is a valid divider index. // if (i < 0 || i >= dividerLayer.numChildren) // return null; // else // return BoxDivider(dividerLayer.getChildAt(i)); // } // else { // return null; // } // } /** * Move a specific divider a given number of pixels. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @param amt The number of pixels to move the divider. * A negative number can be specified in order to move * a divider up or left. The divider movement is * constrained in the same manner as if a user * had moved it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public function moveDivider(i:int, amt:Number):void // { // // Check whether this is a valid divider index. // if (i < 0 || i >= numDividers) // return; // // // Make sure the user is not currently dragging. // if (activeDividerIndex >= 0) // return; // // // We have to first hit the children if we haven't // // yet done so since the first movement . // // // Mimic a divider moving. // activeDividerIndex = i; // // // Store away child sizes, // // then determine the limits on our movement. // cacheChildSizes(); // computeMinAndMaxDelta(); // dragDelta = limitDelta(amt); // // // Now update the children sizes accordingly. // adjustChildSizes(); // // invalidateSize(); // invalidateDisplayList(); // // // Reset the divider tracking stuff. // resetDividerTracking(); // } /** * @private */ // private function createDivider(i:int):BoxDivider // { // // Create separate layer for holding divider objects. // if (!dividerLayer) // { // dividerLayer = UIComponent(rawChildren.addChild(new UIComponent())); // } // // var divider:BoxDivider = BoxDivider(new dividerClass()); // dividerLayer.addChild(divider); // // // if we are creating the active divider bring the divider layer // // to the top most so that users can see the divider line over // // the other children // if (i == PROXY_DIVIDER_INDEX) // { // rawChildren.setChildIndex(dividerLayer, // rawChildren.numChildren-1); // } // // // Tell BoxDivider to use DividedBox's styles, // // unless we are sliding the divider; in that case, // // use the styles of the divider we are sliding. // var basedOn:IFlexDisplayObject = (i == PROXY_DIVIDER_INDEX) ? // getDividerAt(activeDividerIndex) : // this; // // divider.styleName = basedOn; // // divider.owner = this; // // return divider; // } /** * @private */ private function layoutDivider(i:int, unscaledWidth:Number, unscaledHeight:Number, prevChild:IUIComponent, nextChild:IUIComponent):void { // The mouse-over thickness of the divider is normally determined // by the dividerAffordance style, and the visible thickness is // normally determined by the dividerThickness style, assuming that // the relationship thickness <= affordance <= gap applies. But if // one of the other five orderings applies, here is a table of what // happens: // // divider divider horizontalGap/ dividerWidth/ visible width/ // Thickness Affordance verticalGap dividerHeight visible height // // 4 6 8 6 4 // 4 8 6 6 4 // 6 4 8 6 6 // 6 8 4 4 4 // 8 4 6 6 6 // 8 6 4 4 4 // var divider:BoxDivider = BoxDivider(getDividerAt(i)); // // var vm:EdgeMetrics = viewMetrics; // // var verticalGap:Number = getStyle(""verticalGap""); // var horizontalGap:Number = getStyle(""horizontalGap""); // // var thickness:Number = divider.getStyle(""dividerThickness""); // var affordance:Number = divider.getStyle(""dividerAffordance""); // // if (isVertical()) // { // var dividerHeight:Number = affordance; // // dividerHeight is the mouse-over height, // // not necessarily the visible height. // // // The specified affordance should be greater than the thickness. // // But if it isn't, use the thickness instead to determine the // // divider height. // if (dividerHeight < thickness) // dividerHeight = thickness; // // // Don't let the divider overlap the children. // if (dividerHeight > verticalGap) // dividerHeight = verticalGap; // // divider.setActualSize(unscaledWidth - vm.left - vm.right, dividerHeight); // // divider.move(vm.left, // Math.round((prevChild.y + prevChild.height + // nextChild.y - dividerHeight) / 2)); // } // else // { // var dividerWidth:Number = affordance; // // dividerWidth is the mouse-over width, // // not necessarily the visible width. // // // The specified affordance should be greater than the thickness. // // But if it isn't, use the thickness instead to determine the // // divider width. // if (dividerWidth < thickness) // dividerWidth = thickness; // // // Don't let the divider overlap the children. // if (dividerWidth > horizontalGap) // dividerWidth = horizontalGap; // // divider.setActualSize(dividerWidth, unscaledHeight - vm.top - vm.bottom); // // divider.move(Math.round((prevChild.x + prevChild.width + // nextChild.x - dividerWidth) / 2), // vm.top); // } // // divider.invalidateDisplayList(); } /** * @private */ // mx_internal function changeCursor(divider:BoxDivider):void // { // if (cursorID == CursorManager.NO_CURSOR) // { // // If a cursor skin has been set for the specified BoxDivider, // // use it. Otherwise, use the cursor skin for the DividedBox. // var cursorClass:Class = isVertical() ? // getStyle(""verticalDividerCursor"") as Class : // getStyle(""horizontalDividerCursor"") as Class; // // cursorID = cursorManager.setCursor(cursorClass, // CursorManagerPriority.HIGH, 0, 0); // } // } /** * @private */ // mx_internal function restoreCursor():void // { // if (cursorID != CursorManager.NO_CURSOR) // { // cursorManager.removeCursor(cursorID); // cursorID = CursorManager.NO_CURSOR; // } // } /** * @private */ // mx_internal function getDividerIndex(divider:BoxDivider):int // { // var n:int = numChildren; // for (var i:int = 0; i < n - 1; i++) // { // if (getDividerAt(i) == divider) // return i; // } // return -1; // } /** * @private */ // private function getMousePosition(event:MouseEvent):Number // { // var point:Point = new Point(event.stageX, event.stageY); // point = globalToLocal(point); // return isVertical() ? point.y : point.x; // } /** * @private */ // mx_internal function startDividerDrag(divider:BoxDivider, // trigger:MouseEvent):void // { // // Make sure the user is not currently dragging. // if (activeDividerIndex >= 0) // return; // // activeDividerIndex = getDividerIndex(divider); // // var event:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_PRESS); // event.dividerIndex = activeDividerIndex; // dispatchEvent(event); // // if (liveDragging) // activeDivider = divider; // else // { // activeDivider = createDivider(PROXY_DIVIDER_INDEX); // activeDivider.visible = false; // activeDivider.state = DividerState.DOWN; // activeDivider.setActualSize(divider.width, divider.height); // activeDivider.move(divider.x, divider.y); // activeDivider.visible = true; // divider.state = DividerState.UP; // } // // if (isVertical()) // activeDividerStartPosition = activeDivider.y; // else // activeDividerStartPosition = activeDivider.x; // // dragStartPosition = getMousePosition(trigger); // dragDelta = 0; // // cacheChildSizes(); // adjustChildSizes(); // // computeMinAndMaxDelta(); // // systemManager.getSandboxRoot().addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); // systemManager.deployMouseShields(true); // } /** * @private * Store away some important information about * each child for us to use while we move the divider. */ // private function cacheSizes():void // { // oldChildSizes = []; // empty array // // var vertical:Boolean = isVertical(); // // var smallest:Number = Number.MAX_VALUE; // use a big number // // var n:int = numChildren; // for (var i:int = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // if (!child.includeInLayout) // continue; // // var sz:Number = vertical ? child.height : child.width; // // var mx:Number = vertical ? child.maxHeight : child.maxWidth; // // var umn:Number = vertical ? // child.explicitMinHeight : // child.explicitMinWidth; // avoid measured values // // // A NaN min means 0. // var mn:Number = (isNaN(umn)) ? 0 : umn; // // // Compute these for later use. // var dMin:Number = Math.max(0, sz - mn); // var dMax:Number = Math.max(0, mx - sz); // // if (sz > 0 && sz < smallest) // smallest = sz; // // oldChildSizes.push(new ChildSizeInfo(sz, mn, mx, dMin, dMax)); // } // // // Remember the smallest child size we saw. // oldChildSizes.push(new ChildSizeInfo((smallest == Number.MAX_VALUE) ? 1 : smallest)); // } /** * @private */ // private function cacheChildSizes():void // { // oldChildSizes = []; // clear or store // // cacheSizes(); // } /** * @private */ // private function mouseMoveHandler(event:MouseEvent):void // { // dragDelta = limitDelta(getMousePosition(event) - dragStartPosition); // // var dividerEvent:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_DRAG); // dividerEvent.dividerIndex = activeDividerIndex; // dividerEvent.delta = dragDelta; // dispatchEvent(dividerEvent); // // if (liveDragging) // { // adjustChildSizes(); // // invalidateDisplayList(); // // updateDisplayList(unscaledWidth, unscaledHeight); // } // else // { // if (isVertical()) // activeDivider.move(0, activeDividerStartPosition + dragDelta); // else // activeDivider.move(activeDividerStartPosition + dragDelta, 0); // } // } /** * @private * * @param trigger May be null if the event is not a MouseEvent but * a mouse event from another sandbox. */ // mx_internal function stopDividerDrag(divider:BoxDivider, // trigger:MouseEvent):void // { // if (trigger) // dragDelta = limitDelta(getMousePosition(trigger) - dragStartPosition); // // var event:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_RELEASE); // event.dividerIndex = activeDividerIndex; // event.delta = dragDelta; // dispatchEvent(event); // // if (!liveDragging) // { // if (dragDelta == 0) // getDividerAt(activeDividerIndex).state = DividerState.OVER; // // if (activeDivider) // dividerLayer.removeChild(activeDivider); // activeDivider = null; // // adjustChildSizes(); // // invalidateSize(); // invalidateDisplayList(); // } // // resetDividerTracking(); // systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); // systemManager.deployMouseShields(false); // } /** * @private */ // private function resetDividerTracking():void // { // activeDivider = null; // activeDividerIndex = -1; // activeDividerStartPosition = NaN; // dragStartPosition = NaN; // dragDelta = NaN; // oldChildSizes = null; // minDelta = NaN; // maxDelta = NaN; // } /** * @private * Determine the maximum amount of movement that * a divider, i, can move both up and down. * * We base this calculation on the amount of * travel that each divider supports, assuming * that as one divider reaches its limits, the next * divider will move. In this way dividers will * cascade. */ // private function computeAllowableMovement(at:int):void // { // // We break the computation into two loops, // // so that we can calc min and max travel // // independently as one would move the divider // // either up or down. // var deltaMinAbove:Number = 0; // var deltaMaxAbove:Number = 0; // var deltaMinBelow:Number = 0; // var deltaMaxBelow:Number = 0; // // var n:int = numLayoutChildren; // var i:int; // var child:ChildSizeInfo; // // if (at < 0) // return; // // for (i = at; i >= 0; i--) // { // child = ChildSizeInfo(oldChildSizes[i]); // // deltaMinAbove += (dontCoalesceDividers && deltaMinAbove) ? // 0 : child.deltaMin; // // deltaMaxAbove += (dontCoalesceDividers && deltaMaxAbove) ? // 0 : child.deltaMax; // } // // for (i = at + 1; i < n; i++) // { // child = ChildSizeInfo(oldChildSizes[i]); // // deltaMinBelow += (dontCoalesceDividers && deltaMinBelow) ? // 0 : child.deltaMin; // // deltaMaxBelow += (dontCoalesceDividers && deltaMaxBelow) ? // 0 : child.deltaMax; // } // // // Now the maximum movement we can have if // // the divider is moved up is equal to the // // smaller of how much we can shrink all // // components above our divider or the // // maximum of how much the components below // // our divider can grow. Similarly for the // // divider moving in the opposite direction. // var deltaUp:Number = Math.min(deltaMinAbove, deltaMaxBelow); // var deltaDn:Number = Math.min(deltaMinBelow, deltaMaxAbove); // // // deltaUp needs to be in -ve in order for our // // update logic to work // minDelta = -deltaUp; // maxDelta = deltaDn; // } /** * @private */ // private function computeMinAndMaxDelta():void // { // computeAllowableMovement(activeDividerIndex); // } /** * @private */ // private function limitDelta(delta:Number):Number // { // if (delta < minDelta) // delta = minDelta; // else if (delta > maxDelta) // delta = maxDelta; // // // Make sure it is not fractional, // // otherwise we lose pixels. (Bug 87339) // delta = Math.round(delta); // return delta; // } /** * @private * We distribute the delta space in the same * fashion that we calculated it. That is we * start at the divider and give out space * until we hit a limit on the component or * we run out of space to distribute. * We need to do this in both directions since * in one direction we are shrinking and * in the other we are growing. */ // private function distributeDelta():void // { // // if there is no movement of divider we need not // // do any child resizing. // if (!dragDelta) // return; // // var vertical:Boolean = isVertical(); // var n:int = numLayoutChildren; // var k:int = activeDividerIndex; // var smallest:Number = oldChildSizes[n].size - // Math.abs(dragDelta); // smallest possible child size // // if (smallest <= 0 || isNaN(smallest)) // smallest = 1; // // var i:int; // var size:ChildSizeInfo; // var move:Number; // var newSize:Number; // var child:IUIComponent; // var childSize:Number; // // // Find the index of the child before the active divider // var activeDividerChildIndex:int = -1; // var dividerIndex:int = -1; // while (dividerIndex < activeDividerIndex) // { // if (UIComponent(getChildAt(++activeDividerChildIndex)).includeInLayout) // ++dividerIndex; // } // // // Distribute space starting from the center and // // moving upwards. // var curChildIndex:int = activeDividerChildIndex; // var amt:Number = dragDelta; // for (i = k; i >= 0; i--) // { // // If dragDelta -ve => shrink upper components // // otherwise grow them. // size = ChildSizeInfo(oldChildSizes[i]); // move = (amt < 0) ? // -Math.min(-amt, size.deltaMin) : // Math.min(amt, size.deltaMax); // // // Adjust the component and reduce the remaining delta // newSize = size.size + move; // amt -= move; // // // Find the previous child included in the layout // do // { // child = IUIComponent(getChildAt(curChildIndex--)); // } // while (!child.includeInLayout); // // // Adjust the child size. // childSize = (newSize / smallest) * 100; // // if (vertical) // child.percentHeight = childSize; // else // child.percentWidth = childSize; // // // Force a re-measure. // if (child is IInvalidating) // IInvalidating(child).invalidateSize(); // } // // // assert(amt == 0) // // // Now do the same distribution but moving downwards. // curChildIndex = activeDividerChildIndex + 1; // amt = dragDelta; // for (i = k + 1; i < n; i++) // { // // If dragDelta -ve => grow lower components // // otherwise shrink them. // size = ChildSizeInfo(oldChildSizes[i]); // move = (amt < 0) ? // Math.min(-amt, size.deltaMax) : // -Math.min(amt, size.deltaMin); // // // Adjust the component and reduce the remaining delta. // newSize = size.size + move; // amt += move; // // // Find the next child included in the layout // do // { // child = IUIComponent(getChildAt(curChildIndex++)); // } // while (!child.includeInLayout); // // childSize = (newSize / smallest) * 100; // // if (vertical) // child.percentHeight = childSize; // else // child.percentWidth = childSize; // // // Force a re-measure. // if (child is IInvalidating) // IInvalidating(child).invalidateSize(); // } // } /** * @private * For 1.5 we normalize all children to the smallest one * So that we can remove n-1 children and still guarantee * one child can consume 100%. * Also we support the concept of fixed sized children, * which allows us to have one or more children be rigid * in the DividedBox in this case, the dividers above * and below the fixed component move in unison. */ // private function adjustChildSizes():void // { // distributeDelta(); // } /** * @private * Algorithm employed pre-layout to ensure that * we don't leave any dangling space and to ensure * that only explicit min/max values are honored. * * We first compute the sum of %'s across all * children to ensure that we have at least 100%. * If so, we are done. If not, then we attempt * to attach the remaining amount to the last * component, if not, then we distribute the * percentages evenly across all % components. * */ // private function preLayoutAdjustment():void // { // // Calculate the total % // var vertical:Boolean = isVertical(); // // var totalPerc:Number = 0; // var percCount:Number = 0; // // var n:int = numChildren; // var i:int; // var child:IUIComponent; // var perc:Number; // // for (i = 0; i < n; i++) // { // child = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // // Clear out measured min/max // // so super.layout() doesn't use them. // child.measuredMinWidth = 0; // child.measuredMinHeight = 0; // // perc = vertical ? child.percentHeight : child.percentWidth; // // if (!isNaN(perc)) // { // totalPerc += perc; // percCount++; // } // } // // // during preLayoutAdjustment, we make some changes to the children's // // widths and heights. We keep track of the original values in postLayoutChanges // // so we can later go back and reset them so another layout pass is working // // with the correct values rather than these modified values. // postLayoutChanges = []; // var changeObject:Object; // // // No flexible children, so we make the last one 100%. // if (totalPerc == 0 && percCount == 0) // { // // Everyone is fixed and we can give 100% to the last // // included in layout one without concern. // for (i = n-1; i >= 0; i--) // { // child = UIComponent(getChildAt(i)); // if (child.includeInLayout) // { // // create a changeObject to keep track of the original values // // that this child had for width and height // changeObject = {child: child}; // if (vertical) // { // // we know there's no percentHeight originally // if (child.explicitHeight) // changeObject.explicitHeight = child.explicitHeight; // else // changeObject.percentHeight = NaN; // // child.percentHeight = 100; // } // else // { // // we know there's no percentWidth originally // if (child.explicitWidth) // changeObject.explicitWidth = child.explicitWidth; // else if (child.percentWidth) // changeObject.percentWidth = NaN; // // child.percentWidth = 100; // } // postLayoutChanges.push(changeObject); // break; // } // } // } // else if (totalPerc < 100) // { // // We have some %s but they don't total to 100, so lets // // distribute the delta across all of them and in the // // meantime normalize all %s to unscaledHeight/Width. // // The normalization takes care of the case where any one // // of the components hits a min/max limit on their size, // // which could result in the others filling less than 100%. // var delta:Number = Math.ceil((100 - totalPerc) / percCount); // for (i = 0; i < n; i++) // { // child = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // changeObject = {child: child}; // // if (vertical) // { // perc = child.percentHeight; // if (!isNaN(perc)) // { // changeObject.percentHeight = child.percentHeight; // postLayoutChanges.push(changeObject); // // child.percentHeight = (perc + delta) * unscaledHeight; // } // } // else // { // perc = child.percentWidth; // if (!isNaN(perc)) // { // changeObject.percentWidth = child.percentWidth; // postLayoutChanges.push(changeObject); // // child.percentWidth = (perc + delta) * unscaledWidth; // } // } // } // } // // // OK after all this magic we still can't guarantee that the space is // // entirely filled. For example, all percent components hit their max // // values. In this case, the layout will include empty space at the end, // // and once the divider is touched, the non-percent based components // // will be converted into percent based ones and fill the remaining // // space. It seems to me that this scenario is highly unlikely. // // Thus I've choosen the route of stretching the percent based // // components and not touching the explicitly sized or default // // sized ones. // // // // Another option would be to stretch the default sized components // // either in addition to the percent based ones or instead of. // // This seemed a little odd to me as the user never indicated // // that these components are to be stretched initially, so in the end // // I choose to tweak the components that the user has indicated // // as being stretchable. // } /** * @private * During preLayoutAdjustment, we make some changes to the children's * widths and heights. We keep track of the original values in postLayoutChanges * so we can later go back and reset them so another layout pass is working * with the correct values rather than these modified values. */ // private var postLayoutChanges:Array; /** * @private * Post layout work. In preLayoutAdjustment() * sometimes we set a child's percentWidth/percentHeight. * postLayoutAdjustment() will reset the child's width or height * back to what it was. */ // private function postLayoutAdjustment():void // { // // each object has a child property and may have a set of width/height // // properties that it would like to be set // var len:int = postLayoutChanges.length; // for (var i:int = 0; i < len; i++) // { // var changeObject:Object = postLayoutChanges[i]; // // if (changeObject.percentWidth !== undefined) // changeObject.child.percentWidth = changeObject.percentWidth; // // if (changeObject.percentHeight !== undefined) // changeObject.child.percentHeight = changeObject.percentHeight; // // if (changeObject.explicitWidth !== undefined) // changeObject.child.explicitWidth = changeObject.explicitWidth; // // if (changeObject.explicitHeight !== undefined) // changeObject.child.explicitHeight = changeObject.explicitHeight; // } // postLayoutChanges = null; // } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ // private function childAddHandler(event:ChildExistenceChangedEvent):void // { // var child:DisplayObject = event.relatedObject; // // child.addEventListener(""includeInLayoutChanged"", // child_includeInLayoutChangedHandler); // // if (!IUIComponent(child).includeInLayout) // return; // // numLayoutChildren++; // // if (numLayoutChildren > 1) // createDivider(numLayoutChildren - 2); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // } /** * @private */ // private function childRemoveHandler(event:ChildExistenceChangedEvent):void // { // var child:DisplayObject = event.relatedObject; // // child.removeEventListener(""includeInLayoutChanged"", // child_includeInLayoutChangedHandler); // // if (!IUIComponent(child).includeInLayout) // return; // // numLayoutChildren--; // // if (numLayoutChildren > 0) // dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // invalidateSize(); // } /** * @private * When a child's includeInLayout changes, we either remove or add a * divider. */ // private function child_includeInLayoutChangedHandler(event:Event):void // { // var child:UIComponent = UIComponent(event.target); // // if (child.includeInLayout && ++numLayoutChildren > 1) // createDivider(numLayoutChildren - 2); // // else if (!child.includeInLayout && --numLayoutChildren > 0) // dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // invalidateSize(); // } } } //////////////////////////////////////////////////////////////////////////////// // // Helper class: ChildSizeInfo // //////////////////////////////////////////////////////////////////////////////// /** * @private */ //class ChildSizeInfo //{ // //-------------------------------------------------------------------------- // // // // Constructor // // // //-------------------------------------------------------------------------- // // /** // * @private // */ // public function ChildSizeInfo(size:Number, // min:Number = 0, max:Number = 0, // deltaMin:Number = 0, deltaMax:Number = 0) // { // super(); // // this.size = size; // this.min = min; // this.max = max; // this.deltaMin = deltaMin; // this.deltaMax = deltaMax; // } // // //-------------------------------------------------------------------------- // // // // Properties // // // //-------------------------------------------------------------------------- // // //---------------------------------- // // deltaMin // //---------------------------------- // // /** // * @private // */ // public var deltaMin:Number; // // //---------------------------------- // // deltaMax // //---------------------------------- // // /** // * @private // */ // public var deltaMax:Number; // // //---------------------------------- // // min // //---------------------------------- // // /** // * @private // */ // public var min:Number; // // //---------------------------------- // // max // //---------------------------------- // // /** // * @private // */ // public var max:Number; // // //---------------------------------- // // size // //---------------------------------- // // /** // * @private // */ // public var size:Number; //} ",12351,False,2344.9311025574375,median "/* Terminal.ino Use display terminal to output text (using Arduino print) Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2018, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list U8G2LOG u8g2log; // setup the terminal (U8G2LOG) and connect to u8g2 for automatic refresh of the display // The size (width * height) depends on the selected font and the display // assume 4x6 font #define U8LOG_WIDTH 32 #define U8LOG_HEIGHT 10 uint8_t u8log_buffer[U8LOG_WIDTH*U8LOG_HEIGHT]; void setup(void) { /* U8g2 Project: SSD1306 Test Board */ pinMode(10, OUTPUT); pinMode(9, OUTPUT); digitalWrite(10, 0); digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); u8g2.setFont(u8g2_font_tom_thumb_4x6_mf); // set the font for the terminal window u8g2log.begin(u8g2, U8LOG_WIDTH, U8LOG_HEIGHT, u8log_buffer); u8g2log.setLineHeightOffset(0); // set extra space between lines in pixel, this can be negative u8g2log.setRedrawMode(0); // 0: Update screen with newline, 1: Update screen for every char } unsigned long t = 0; // print the output of millis() to the terminal every second void loop(void) { if ( t < millis() ) { t = millis() + 15000; // every 15 seconds u8g2log.print(""\\f""); // \\f = form feed: clear the screen } u8g2log.print(""millis=""); u8g2log.print(millis()); u8g2log.print(""\\n""); delay(500); } ",16144,True,4912.666318697777,median "/* S&T GeoTronics LLC **** OPEN ENIGMA **** This code is provided as is. S&T GeoTronics LLC, it's Partners and Associates provide it freely, with no warranty of it's functionality, fitness for use or usefulness. In no way shall S&T GeoTronics LLC, it's Partners and Associates be liable for the use, misuse, or damages of any kind due to the use or misuse of this code or any associated hardware provided. Enigma Code. This Arduino Mega custom shield is programmed to replicate exactly the behavior of a true German M4 Enigma machine. It uses 4 16-Segment units, 5 LEDs, 26 Lamps setup as keyboard, 26 keyboard buttons & 10 Function keys. The 115 light emitting diodes are multi-plexed to minimize the amount of pins needed down to 38 and all 36 pushbuttons keys are sharing a total of 4 pins. Designed, assembled & programmed by Marc Tessier & James Sanderson 9/20/13 Modified for our Prototype PCB pair on 12/4/13. Modified to obey doublesteping and have M3 function 22 MAR 14 This code shall remain in public domain as regulated under the creative commons licence. */ // Define the variables unsigned long time = millis(); unsigned long otime = time; int inpin[4] = {A0, A1, A2, A3}; int inval[4] = {0, 0, 0, 0}; int keyval = 100; int kvalo = 100; boolean windex = 0; boolean windex1 = 0; boolean windex2 = 0; int lampval = 100; int procesval = 0; int procesvala = 0; int mode = 0; unsigned long mtime; int mdex =0; int behavior = 1; int plugred = 0; //Define Plug Board Pins int plug[26] = {A14, 49, A12, A15, 7, 53, 50, 52, 3, A6, A4, A11, A9, A10, 8, A7, 6, 4, 51, 10, 9, A5, 5, A8, A13, 2} ; // Define each Nixie character int dig1 = 37; int dig2 = 37; int dig3 = 37; int dig4 = 37; int data[3][40] ={ {36,36,36,36,18,39,19,36,6,4,14,19,17,14,13,8,2,18,36,4,13,8,6,12,0,36,12,0,17,10,36,30,36,13,3,19,36,36,36,36}, {36,36,36,36,18,39,19,36,6,4,14,19,17,14,13,8,2,18,36,4,13,8,6,12,0,36,12,0,17,10,36,30,36,36,3,19,36,36,36,36}, {36,36,36,36,18,39,19,36,6,4,14,19,17,14,13,8,2,18,36,4,13,8,6,12,0,36,12,0,17,10,36,29,36,36,3,19,36,36,36,36} }; // Define the 16-Segments Pins as 2 Arrays int segment[17] = {24,22,25,31,38,36,32,30,28,26,23,27,33,35,34,29,37}; //cathode array int anode[4] = {39,41,43,45}; //annode array commin annode // Define the 26 Lamps as a 2D Array int lamparray[26] [2] = {{12,38},{13,29},{13,33},{12,35},{11,35},{12,33},{12,31},{12,29},{11,25},{12,27}, {12,25},{13,23},{13,25},{13,27},{11,23},{13,38},{11,38},{11,33},{12,37},{11,31}, {11,27},{13,31},{11,37},{13,35},{13,37},{11,29}}; // Define the 12 Lamp Pins for initialization //int lamppin[12] = {2,3,4,5,6,7,8,9,10,11,12,13}; //2 to 10 cathode, 11 to 13 common annode int lamppin[3] = {11,12,13}; // Define each LTP587P Segments: A,B,C,D,E,F,G,H,K,M,N,P,R,S,T,U,dp boolean segmentvals[40][17] = { { 0,0,0,0,1,1,0,0,1,1,1,0,1,1,1,0,1 }, // = A 0 { 0,0,0,0,0,0,1,1,1,0,1,0,1,0,1,1,1 }, // = B 1 { 0,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1 }, // = C 2 { 0,0,0,0,0,0,1,1,1,0,1,1,1,0,1,1,1 }, // = D 3 { 0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,0,1 }, // = E 4 { 0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,0,1 }, // = F 5 { 0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1 }, // = G 6 { 1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,0,1 }, // = H 7 { 0,0,1,1,0,0,1,1,1,0,1,1,1,0,1,1,1 }, // = I 8 { 1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1 }, // = J 9 { 1,1,1,1,1,1,0,0,1,1,0,1,0,1,1,0,1 }, // = K 10 { 1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1 }, // = L 11 { 1,1,0,0,1,1,0,0,0,1,0,1,1,1,1,1,1 }, // = M 12 { 1,1,0,0,1,1,0,0,0,1,1,1,0,1,1,1,1 }, // = N 13 { 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1 }, // = O 14 { 0,0,0,1,1,1,0,0,1,1,1,0,1,1,1,0,1 }, // = P 15 { 0,0,0,0,0,0,0,0,1,1,1,1,0,1,1,1,1 }, // = Q 16 { 0,0,0,1,1,1,0,0,1,1,1,0,0,1,1,0,1 }, // = R 17 { 0,0,1,0,0,0,1,0,1,1,1,0,1,1,1,0,1 }, // = S 18 { 0,0,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1 }, // = T 19 { 1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1 }, // = U 20 { 1,1,1,1,1,1,0,0,1,1,0,1,1,1,0,1,1 }, // = V 21 { 1,1,0,0,1,1,0,0,1,1,1,1,0,1,0,1,1 }, // = W 22 { 1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1 }, // = X 23 { 1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1 }, // = Y 24 { 0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,1,1 }, // = Z 25 { 0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,1,1 }, // = 0 26 { 1,1,0,0,1,1,1,1,1,1,0,1,1,1,1,1,1 }, // = 1 27 { 0,0,0,1,0,0,0,1,1,1,1,0,1,1,1,0,1 }, // = 2 28 { 0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,1,1 }, // = 3 29 { 1,1,0,0,1,1,1,0,1,1,1,0,1,1,1,0,1 }, // = 4 30 { 0,0,1,0,0,0,1,0,1,1,1,0,1,1,1,0,1 }, // = 5 31 { 0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,0,1 }, // = 6 32 { 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // = 7 33 { 0,0,0,0,0,0,0,0,1,1,1,0,1,1,1,0,1 }, // = 8 34 { 0,0,0,0,0,0,1,0,1,1,1,0,1,1,1,0,1 }, // = 9 35 { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, // = Space 36 { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }, // = Full Lit 37 { 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1 }, // = SS 38 { 0,1,1,1,0,0,0,1,0,0,1,1,0,1,1,0,1} }; // = & 39 // LTP587P Segments: A,B,C,D,E,F,G,H,K,M,N,P,R,S,T,U,dp // Define the 5 Mode LEDs int led1 = 40; int led2 = 42; int led3 = 44; int led4 = 46; int led5 = 48; //4,10,12, 5,11, 6, 3,16,21,25,13,19,14,22,24, 7,23,20,18,15, 0, 8, 1,17, 2, 9 //Define the rotor values A B C D E F G H I J K L M N O P Q static const int rotorvals[12][78] = { { 4,10,12, 5,11, 6, 3,16,21,25,13,19,14,22,24, 7,123,20,18,15, 0, 8, 1,17, 2, 9, 4,10,12, 5,11, 6, 3,16,21,25,13,19,14,22,24, 7,123,20,18,15, 0, 8, 1,17, 2, 9, 4,10,12, 5,11, 6, 3,16,21,25,13,19,14,22,24, 7,123,20,18,15, 0, 8, 1,17, 2, 9 }, // wheel 1 { 0, 9, 3,10,118, 8,17,20,23, 1,11, 7,22,19,12, 2,16, 6,25,13,15,24, 5,21,14, 4, 0, 9, 3,10,118, 8,17,20,23, 1,11, 7,22,19,12, 2,16, 6,25,13,15,24, 5,21,14, 4, 0, 9, 3,10,118, 8,17,20,23, 1,11, 7,22,19,12, 2,16, 6,25,13,15,24, 5,21,14, 4 }, // wheel 2 { 1, 3, 5, 7, 9,11, 2,15,17,19,23,21,25,13,24, 4, 8,22, 6, 0,10,112,20,18,16,14, 1, 3, 5, 7, 9,11, 2,15,17,19,23,21,25,13,24, 4, 8,22, 6, 0,10,112,20,18,16,14, 1, 3, 5, 7, 9,11, 2,15,17,19,23,21,25,13,24, 4, 8,22, 6, 0,10,112,20,18,16,14 }, // wheel 3 { 4,18,14,21,15,25, 9, 0,24,116,20, 8,17, 7,23,11,13, 5,19, 6,10, 3, 2,12,22, 1, 4,18,14,21,15,25, 9, 0,24,116,20, 8,17, 7,23,11,13, 5,19, 6,10, 3, 2,12,22, 1, 4,18,14,21,15,25, 9, 0,24,116,20, 8,17, 7,23,11,13, 5,19, 6,10, 3, 2,12,22, 1 }, // wheel 4 { 21,25, 1,17, 6, 8,19,24,20,15,18, 3,13, 7,11,23, 0,22,12, 9,16,14, 5, 4, 2,110, 21,25, 1,17, 6, 8,19,24,20,15,18, 3,13, 7,11,23, 0,22,12, 9,16,14, 5, 4, 2,110, 21,25, 1,17, 6, 8,19,24,20,15,18, 3,13, 7,11,23, 0,22,12, 9,16,14, 5, 4, 2,110 }, // wheel 5 { 9,15, 6,21,14,20,12, 5,24,16, 1, 4,113, 7,25,17, 3,10, 0,18,23,11, 8, 2,19,122, 9,15, 6,21,14,20,12, 5,24,16, 1, 4,113, 7,25,17, 3,10, 0,18,23,11, 8, 2,19,122, 9,15, 6,21,14,20,12, 5,24,16, 1, 4,113, 7,25,17, 3,10, 0,18,23,11, 8, 2,19,122 }, // wheel 6 { 13,25, 9, 7, 6,17, 2,23,12,24,18,22,101,14,20, 5, 0, 8,21,11,15, 4,10,16, 3,119, 13,25, 9, 7, 6,17, 2,23,12,24,18,22,101,14,20, 5, 0, 8,21,11,15, 4,10,16, 3,119, 13,25, 9, 7, 6,17, 2,23,12,24,18,22,101,14,20, 5, 0, 8,21,11,15, 4,10,16, 3,119 }, // wheel 7 { 5,10,16, 7,19,11,23,14, 2, 1, 9,18,115, 3,25,17, 0,12, 4,22,13, 8,20,24, 6,121, 5,10,16, 7,19,11,23,14, 2, 1, 9,18,115, 3,25,17, 0,12, 4,22,13, 8,20,24, 6,121, 5,10,16, 7,19,11,23,14, 2, 1, 9,18,115, 3,25,17, 0,12, 4,22,13, 8,20,24, 6,121 }, // wheel 8 { 11,4,24,9,21,2,13,8,23,22,15,1,16,12,3,17,19,0,10,25,6,5,20,7,14,18, 11,4,24,9,21,2,13,8,23,22,15,1,16,12,3,17,19,0,10,25,6,5,20,7,14,18, 11,4,24,9,21,2,13,8,23,22,15,1,16,12,3,17,19,0,10,25,6,5,20,7,14,18 }, // Beta { 5,18,14,10,0,13,20,4,17,7,12,1,19,8,24,2,22,11,16,15,25,23,21,6,9,3, 5,18,14,10,0,13,20,4,17,7,12,1,19,8,24,2,22,11,16,15,25,23,21,6,9,3, 5,18,14,10,0,13,20,4,17,7,12,1,19,8,24,2,22,11,16,15,25,23,21,6,9,3 }, // Gamma { 4,13,10,16,0,20,24,22,9,8,2,14,15,1,11,12,3,23,25,21,5,19,7,17,6,18, 4,13,10,16,0,20,24,22,9,8,2,14,15,1,11,12,3,23,25,21,5,19,7,17,6,18, 4,13,10,16,0,20,24,22,9,8,2,14,15,1,11,12,3,23,25,21,5,19,7,17,6,18}, // = UKW-B { 17,3,14,1,9,13,19,10,21,4,7,12,11,5,2,22,25,0,23,6,24,8,15,18,20,16, 17,3,14,1,9,13,19,10,21,4,7,12,11,5,2,22,25,0,23,6,24,8,15,18,20,16, 17,3,14,1,9,13,19,10,21,4,7,12,11,5,2,22,25,0,23,6,24,8,15,18,20,16 } // = UKW-C }; static const int rotorvali[10][78] = { { 20,22,24, 6, 0, 3, 5,15,21,25, 1, 4, 2,10,12,19, 7,23,18,11,17, 8,13,16,14, 9, 20,22,24, 6, 0, 3, 5,15,21,25, 1, 4, 2,10,12,19, 7,23,18,11,17, 8,13,16,14, 9, 20,22,24, 6, 0, 3, 5,15,21,25, 1, 4, 2,10,12,19, 7,23,18,11,17, 8,13,16,14, 9 }, //wheel 1 i // { 0, 9,15, 2,25,22,17,11, 5, 1, 3,10,14,19,24,20,16, 6, 4,13, 7,23,12, 8,21,18, 0, 9,15, 2,25,22,17,11, 5, 1, 3,10,14,19,24,20,16, 6, 4,13, 7,23,12, 8,21,18, 0, 9,15, 2,25,22,17,11, 5, 1, 3,10,14,19,24,20,16, 6, 4,13, 7,23,12, 8,21,18 }, //wheel 2 i { 19, 0, 6, 1,15, 2,18, 3,16, 4,20, 5,21,13,25, 7,24, 8,23, 9,22,11,17,10,14,12, 19, 0, 6, 1,15, 2,18, 3,16, 4,20, 5,21,13,25, 7,24, 8,23, 9,22,11,17,10,14,12, 19, 0, 6, 1,15, 2,18, 3,16, 4,20, 5,21,13,25, 7,24, 8,23, 9,22,11,17,10,14,12 }, //wheel 3 i { 7,25,22,21, 0,17,19,13,11, 6,20,15,23,16, 2, 4, 9,12, 1,18,10, 3,24,14, 8, 5, 7,25,22,21, 0,17,19,13,11, 6,20,15,23,16, 2, 4, 9,12, 1,18,10, 3,24,14, 8, 5, 7,25,22,21, 0,17,19,13,11, 6,20,15,23,16, 2, 4, 9,12, 1,18,10, 3,24,14, 8, 5 }, //wheel 4 i { 16, 2,24,11,23,22, 4,13, 5,19,25,14,18,12,21, 9,20, 3,10, 6, 8, 0,17,15, 7, 1, 16, 2,24,11,23,22, 4,13, 5,19,25,14,18,12,21, 9,20, 3,10, 6, 8, 0,17,15, 7, 1, 16, 2,24,11,23,22, 4,13, 5,19,25,14,18,12,21, 9,20, 3,10, 6, 8, 0,17,15, 7, 1 }, //wheel 5 i { 18,10,23,16,11, 7, 2,13,22, 0,17,21,06,12, 4, 1, 9,15,19,24, 5, 3, 25,20, 8,14, 18,10,23,16,11, 7, 2,13,22, 0,17,21,06,12, 4, 1, 9,15,19,24, 5, 3, 25,20, 8,14, 18,10,23,16,11, 7, 2,13,22, 0,17,21,06,12, 4, 1, 9,15,19,24, 5, 3, 25,20, 8,14 }, //wheel 6 i { 16,12,6,24,21,15,4,3,17,2,22,19,8,0,13,20,23,5,10,25,14,18,11,7,9,1, 16,12,6,24,21,15,4,3,17,2,22,19,8,0,13,20,23,5,10,25,14,18,11,7,9,1, 16,12,6,24,21,15,4,3,17,2,22,19,8,0,13,20,23,5,10,25,14,18,11,7,9,1 }, //wheel 7 i { 16,9,8,13,18,0,24,3,21,10,1,5,17,20,7,12,2,15,11,4,22,25,19,6,23,14, 16,9,8,13,18,0,24,3,21,10,1,5,17,20,7,12,2,15,11,4,22,25,19,6,23,14, 16,9,8,13,18,0,24,3,21,10,1,5,17,20,7,12,2,15,11,4,22,25,19,6,23,14 }, //wheel 8 i { 17,11,5,14,1,21,20,23,7,3,18,0,13,6,24,10,12,15,25,16,22,4,9,8,2,19, 17,11,5,14,1,21,20,23,7,3,18,0,13,6,24,10,12,15,25,16,22,4,9,8,2,19, 17,11,5,14,1,21,20,23,7,3,18,0,13,6,24,10,12,15,25,16,22,4,9,8,2,19 }, //Beta i { 4,11,15,25,7,0,23,9,13,24,3,17,10,5,2,19,18,8,1,12,6,22,16,21,14,20, 4,11,15,25,7,0,23,9,13,24,3,17,10,5,2,19,18,8,1,12,6,22,16,21,14,20, 4,11,15,25,7,0,23,9,13,24,3,17,10,5,2,19,18,8,1,12,6,22,16,21,14,20 } }; //Gamma i // Define a 2D Array for keeping the wheel locations & positions int wheel[4][3] = {{29,0,0},{28,0,0},{27,0,0},{1,0,0}}; int reflect[2] = {1,0}; // Define Array for plugbord values 25 x2 position 0 holds use position 1 holds value int plugu holds the total nomber of plugs used (10 max) int plugval [2][26] = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}}; int pluguse = 0; int paindex = 0; int pbindex = 1; int prindex = 0; int prtindex =0; void setup() { // Initialize all 29 LED pins as Output for (int index = 0; index <= 2; index++) { pinMode(lamppin[index], OUTPUT); digitalWrite(lamppin[index],1); } for (int index = 0 ; index <= 3; index++) { pinMode (anode[index], OUTPUT); digitalWrite (anode[index], 1); } for (int index = 0 ; index <= 16; index++) { pinMode (segment[index], OUTPUT); digitalWrite (segment[index], 1); } pinMode(led1,OUTPUT); pinMode(led2,OUTPUT); pinMode(led3,OUTPUT); pinMode(led4,OUTPUT); pinMode(led5,OUTPUT); //Set Initial Pin Mode For Plug Board Pins for (int index = 0 ; index <= 25; index++) { pinMode (plug[index], INPUT); } Serial.begin(9600); Serial3.begin(19200); delay(500); Serial3.write(29); Serial3.write(33); Serial3.write(0); Serial3.println(""""); Serial3.print("" S&T GeoTronics ENIGMA MARK 5 ""); Serial3.println(""""); Serial3.println(""""); Serial3.println(""""); // Serial3.write(27); // Serial3.write(14); Serial3.write(29); Serial3.write(33); Serial3.write(17); // Initialize all 4 pusbutton pins as Input for (int index = 0; index <= 3; index++) { pinMode(inpin[index], INPUT); } } void loop() { // Keyboard debounce & test for new key pressed time = millis(); if (time > otime + 100) {keyval = readkbde();} if(keyval == kvalo) {windex = 0;} kvalo = keyval; if ((mode == 0) && (keyval == 46) && (windex ==1)){ behavior ++; windex =0; if(behavior > 2) {behavior = 0; } } if((keyval == 45) && (windex ==1)) {modeselect();} // The whole Enigma machine operation revolves around which Operating Mode is current if(mode == 0) {mode0();} else if(mode == 1) {mode1();} else if(mode == 2) {mode2();} else if(mode == 3) {mode3();} else if(mode == 4) {mode4();} else if(mode == 5) {mode5();} else { } Serial.println(keyval); // for debuging prints keybord value to serial monitor// for run or del } // This function takes care of figuring out which key has been pressed & returns a unique Integer int readkbde() { int kval = 100; for (int index = 0; index <= 3; index++) { inval[index] = analogRead(inpin[index]); } //Reads analog input values if((inval[0] > 982) && (inval[1] > 973) && (inval[2] > 966) && (inval[3] > 973)) {kval = 100;} // no key press else if((inval[0] < 981) && (inval[0] > 903)) {kval = 49;} //up arrow 4 else if((inval[0] < 902) && (inval[0] > 831)) {kval = 48;} //up arrow 3 else if((inval[0] < 830) && (inval[0] > 762)) {kval = 47;} //up arrow 2 else if((inval[0] < 761) && (inval[0] > 693)) {kval = 46;} //up arrow 1 else if((inval[0] < 692) && (inval[0] > 622)) {kval = 45;} //mode else if((inval[0] < 621) && (inval[0] > 545)) {kval = 44;} //enter else if((inval[0] < 544) && (inval[0] > 458)) {kval = 43;} else if((inval[0] < 457) && (inval[0] > 358)) {kval = 42;} else if((inval[0] < 357) && (inval[0] > 237)) {kval = 41;} else if(inval[0] < 236 ) {kval = 40;} else if((inval[1] < 972) && (inval[1] > 875)) {kval = 16;} else if((inval[1] < 874) && (inval[1] > 784)) {kval = 22;} else if((inval[1] < 783) && (inval[1] > 696)) {kval = 4;} else if((inval[1] < 695) && (inval[1] > 605)) {kval = 17;} else if((inval[1] < 604) && (inval[1] > 507)) {kval = 19;} else if((inval[1] < 506) && (inval[1] > 395)) {kval = 25;} else if((inval[1] < 394) && (inval[1] > 261)) {kval = 20;} else if((inval[1] < 260) && (inval[1] > 94)) {kval = 8;} else if(inval[1] < 93 ) {kval = 14;} else if((inval[2] < 965) && (inval[2] > 855)) {kval = 0;} else if((inval[2] < 854) && (inval[2] > 752)) {kval = 18;} else if((inval[2] < 751) && (inval[2] > 650)) {kval = 3;} else if((inval[2] < 649) && (inval[2] > 542)) {kval = 5;} else if((inval[2] < 541) && (inval[2] > 421)) {kval = 6;} else if((inval[2] < 420) && (inval[2] > 278)) {kval = 7;} else if((inval[2] < 277) && (inval[2] > 100)) {kval = 9;} else if(inval[2] < 99 ) {kval = 10;} else if((inval[3] < 972) && (inval[3] > 875)) {kval = 15;} else if((inval[3] < 874) && (inval[3] > 784)) {kval = 24;} else if((inval[3] < 783) && (inval[3] > 696)) {kval = 23;} else if((inval[3] < 695) && (inval[3] > 605)) {kval = 2;} else if((inval[3] < 604) && (inval[3] > 507)) {kval = 21;} else if((inval[3] < 506) && (inval[3] > 395)) {kval = 1;} else if((inval[3] < 394) && (inval[3] > 261)) {kval = 13;} else if((inval[3] < 260) && (inval[3] > 94)) {kval = 12;} else if(inval[3] < 93 ) {kval = 11;} else {kval = 100;} if(kval < 99) {otime = millis();} //Starts key debounce timer if((kval >= 0) && (kval <= 99)) {windex = 1;} //windex showing true (1) indicates the return of a fresh key stroke Serial.println(kval); return kval; } // Function to change operating Mode void modeselect() { mode++; if(mode >=6) {mode = 0;} windex = 0; } // Default Mode: Enigma is a Typewriter void mode0() { if((keyval >= 0) && (keyval <= 25)) {lampval = keyval;} else {lampval = 100;} lampita(); delay(3); lampitb(); marquee(); } // Select the Rotors & the Reflector void mode1() { int index; digitalWrite(led1, HIGH); if(windex == 1) {if((keyval == 43) || (keyval == 46)){ if(behavior != 2) {wheel[3][0]++;windex = 0; if (wheel[3][0] > 2) {wheel[3][0] = 1; reflect[0]++; if (reflect[0] > 2) {reflect[0] = 1;}} } else {reflect[0]++; windex = 0; if (reflect[0] > 2) {reflect[0] = 1;} }}} if(windex == 1) {if(keyval == 47) { for(index = wheel[2][0];(index == wheel[1][0]) || (index == wheel[0][0]) || (index == wheel[2][0]); index++) {if(index > 33) {index = 26;} }wheel[2][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 48) { for(index = wheel[1][0];(index == wheel[2][0]) || (index == wheel[0][0]) || (index == wheel[1][0]); index++) {if(index > 33) {index = 26;} }wheel[1][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 49) { for(index = wheel[0][0];(index == wheel[2][0]) || (index == wheel[1][0]) || (index == wheel[0][0]); index++) {if(index > 33) {index = 26;} }wheel[0][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 42) { for(index = wheel[2][0];(index == wheel[1][0]) || (index == wheel[0][0]) || (index == wheel[2][0]); index--) {if(index < 28) {index = 35;} }wheel[2][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 41) { for(index = wheel[1][0];(index == wheel[2][0]) || (index == wheel[0][0]) || (index == wheel[1][0]); index--) {if(index < 28) {index = 35;} }wheel[1][0] = index; windex = 0;}} if(windex == 1) {if(keyval == 40) { for(index = wheel[0][0];(index == wheel[2][0]) || (index == wheel[1][0]) || (index == wheel[0][0]); index--) {if(index < 28) {index = 35;} }wheel[0][0] = index; windex = 0;}} dig2 = wheel[2][0]; dig3 = wheel[1][0]; dig4 = wheel[0][0]; if(behavior != 2) { if( wheel[3][0] == 1 ) { dig1 = 1;} else {dig1 = 6;}} else{ dig1 = 36;} lampval = reflect[0]; lampita(); delay(3); lampitb(); nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; digitalWrite(led1, LOW); } // Position the Inner setting of each Rotor void mode2() { digitalWrite(led2, HIGH); if(windex == 1){ if(behavior != 2) { if(keyval == 46) {wheel[3][1]++; if(wheel[3][1] > 25) {wheel[3][1] = 0;}}} if(keyval == 47) {wheel[2][1]++; if(wheel[2][1] > 25) {wheel[2][1] = 0;}} if(keyval == 48) {wheel[1][1]++; if(wheel[1][1] > 25) {wheel[1][1] = 0;}} if(keyval == 49) {wheel[0][1]++; if(wheel[0][1] > 25) {wheel[0][1] = 0;}} if(behavior != 2) {if(keyval == 43) {wheel[3][1]--; if(wheel[3][1] < 0) {wheel[3][1] = 25;}}} if(keyval == 42) {wheel[2][1]--; if(wheel[2][1] < 0) {wheel[2][1] = 25;}} if(keyval == 41) {wheel[1][1]--; if(wheel[1][1] < 0) {wheel[1][1] = 25;}} if(keyval == 40) {wheel[0][1]--; if(wheel[0][1] < 0) {wheel[0][1] = 25;}} windex = 0; } dig2 = wheel[2][1]; dig3 = wheel[1][1]; dig4 = wheel[0][1]; if(behavior != 2) {dig1 =wheel[3][1];} else {dig1 = 36;} nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; digitalWrite(led2, LOW); } // Position the Start character of each Wheel void mode3() { digitalWrite(led3, HIGH); if(windex == 1){ if(behavior != 2) { if(keyval == 46) {wheel[3][2]++; if(wheel[3][2] > 25) {wheel[3][2] = 0;}}} // {reflect[1]++; if(reflect[1] > 25) {reflect[1] = 0;}}} if(keyval == 47) {wheel[2][2]++; if(wheel[2][2] > 25) {wheel[2][2] = 0;}} if(keyval == 48) {wheel[1][2]++; if(wheel[1][2] > 25) {wheel[1][2] = 0;}} if(keyval == 49) {wheel[0][2]++; if(wheel[0][2] > 25) {wheel[0][2] = 0;}} if(behavior != 2) {if(keyval == 43) {wheel[3][2]--; if(wheel[3][2] < 0) {wheel[3][2] = 25;}}} // {reflect[1]--; if(reflect[1] < 0) {reflect[1] = 25;}}} if(keyval == 42) {wheel[2][2]--; if(wheel[2][2] < 0) {wheel[2][2] = 25;}} if(keyval == 41) {wheel[1][2]--; if(wheel[1][2] < 0) {wheel[1][2] = 25;}} if(keyval == 40) {wheel[0][2]--; if(wheel[0][2] < 0) {wheel[0][2] = 25;}} windex = 0; } dig2 = wheel[2][2]; dig3 = wheel[1][2]; dig4 = wheel[0][2]; dig1 = wheel[3][2]; if (behavior == 2) {dig1 = 36;} nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; digitalWrite(led3, LOW); } // Define the Plugboard pairs void mode4() { if(plugred == 0) {readplugs(); } int index = 0; digitalWrite(led4, HIGH); if(pluguse <= 9) { if(plugval[0][paindex] == 1) {for(index = paindex;(index == paindex) || (index == pbindex) || (plugval[0][index] == 1); index++) {if(index > 24) {index = -1;}} paindex = index;} if(plugval[0][pbindex] == 1) {for(index = pbindex;(index == pbindex) || (index == paindex) || (plugval[0][index] == 1); index++) {if(index > 24) {index = -1;}} pbindex = index;} if(windex == 1) { if(keyval == 46) { for(index = paindex;(index == paindex) || (index == pbindex) || (plugval[0][index] == 1); index++) {if(index > 24) {index = -1;}} paindex = index; windex = 0; } if(keyval == 43) { for(index = paindex;(index == paindex) || (index == pbindex) || (plugval[0][index] == 1); index--) {if(index < 1) {index = 26;}} paindex = index; windex = 0; } if(keyval == 49) { for(index = pbindex;(index == pbindex) || (index == paindex) || (plugval[0][index] == 1); index++) {if(index > 24) {index = -1;}} pbindex = index; windex = 0; } if(keyval == 40) { for(index = pbindex;(index == pbindex) || (index == paindex) || (plugval[0][index] == 1); index--) {if(index < 1) {index = 26;}} pbindex = index; windex = 0; } if(keyval == 44) { plugval[0][paindex] = 1; plugval[1][paindex] = pbindex; plugval[0][pbindex] = 1; plugval[1][pbindex] = paindex; windex = 0; pluguse++;} } dig2 = 19; dig3 = 14; dig4 = pbindex; dig1 = paindex; nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; } else {done();} digitalWrite(led4, LOW); } // This is Normal Operation Mode to Encrypt/Decrypt void mode5() { int pv = 0; digitalWrite(led5, HIGH); if(keyval >= 26) {lampval = 100;} else { int windexb = windex; if((keyval >= 0) && (keyval <= 25)) { if(windex == 1){procesvala = keyval; indexwheels();}} procesval = procesvala; procesval = plugval[1][procesval]; // Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[0][2] - wheel[0][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvals[wheel[0][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[0][2] - wheel[0][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[1][2] - wheel[1][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvals[wheel[1][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[1][2] - wheel[1][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[2][2] - wheel[2][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvals[wheel[2][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[2][2] - wheel[2][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[3][2] - wheel[3][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvals[wheel[3][0] +7][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[3][2] - wheel[3][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); procesval = rotorvals[reflect[0] + 9][procesval]; //Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[3][2] - wheel[3][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvali[wheel[3][0] +7][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[3][2] - wheel[3][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} //Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[2][2] - wheel[2][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvali[wheel[2][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[2][2] - wheel[2][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} //Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[1][2] - wheel[1][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvali[wheel[1][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[1][2] - wheel[1][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} //Serial.print (procesval); Serial.print("" ""); pv = (procesval + (wheel[0][2] - wheel[0][1])); if(pv < 0) {pv = pv + 26;} procesval = rotorvali[wheel[0][0] -27][pv]; if(procesval >= 100) {procesval = procesval - 100;} procesval = (procesval - (wheel[0][2] - wheel[0][1])); if(procesval < 0) {procesval = procesval + 26;}if(procesval > 25) {procesval = procesval - 26;} // Serial.print (procesval); Serial.print("" ""); procesval = plugval[1][procesval]; if(windexb == 1) { Serial3.write(procesval + 65); prindex ++; if(prindex > 3) {Serial3.print("" ""); prtindex ++; prindex = 0; } if(prtindex > 2) {Serial3.println(""""); Serial3.println(""""); prtindex = 0;} } lampval = procesval; } windex = 0; //Serial.println(lampval); dig2 = wheel[2][2]; dig3 = wheel[1][2]; dig4 = wheel[0][2]; dig1 = wheel[3][2]; if (behavior == 2) {dig1 = 36;} lampita(); delay(3); lampitb(); nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; digitalWrite(led5, LOW); } // Helper Function to light the proper key void lampita() { if(lampval <= 25) { digitalWrite(lamparray[lampval][0],0); digitalWrite(lamparray[lampval][1],0); delay(1); }} void lampitb(){ if(lampval <= 25) { digitalWrite(lamparray[lampval][0],1); digitalWrite(lamparray[lampval][1],1); }} // Help Function to illuminate ""Nixies"" void nixisend() { sixteenSegWrite(0, dig1); sixteenSegWrite(1, dig2); sixteenSegWrite(2, dig3); sixteenSegWrite(3, dig4); } void marquee() { time = millis(); if( mtime < time) { mtime = time + 400; mdex++;} dig1 = data[behavior][mdex]; dig2 = data[behavior][mdex + 1]; dig3 = data[behavior][mdex + 2]; dig4 = data[behavior][mdex + 3]; if (mdex >= 35) {mdex = 0;} nixisend(); } // Function that actually turns on each of 17 appropriate segments on each ""Nixie"" void sixteenSegWrite(int digit, int character) { digitalWrite(anode[digit],0); for (int index = 0; index < 17; index++) { digitalWrite(segment[index], segmentvals[character][index]); } delay(3); for (int index =0; index <= 16; index++) { digitalWrite(segment[index], 1); } digitalWrite(anode[digit], 1); } void done() { dig1 = 3; dig2 = 14; dig3 = 13; dig4 = 4; nixisend(); dig1 =37; dig2 = 37; dig3 = 37; dig4 = 37; } void indexwheels() { if (behavior > 0){ if(rotorvals[wheel[1][0]-27][wheel[1][2]] >= 100) {windex1 = 1;if (behavior < 2) { windex2 = 1;}}} // Serial.print(rotorvals[wheel[0][0]-27][wheel[0][2]]); // Serial.print("" ""); Serial.print(wheel[0][0]-27); Serial.print("" ""); Serial.println(wheel[0][2]); if(rotorvals[wheel[0][0]-27][wheel[0][2]] >= 100) {windex1 = 1;} wheel[0][2]++; if(wheel[0][2] > 25) {wheel[0][2] = 0;} windex = 0; if(windex1 == 1){ if(rotorvals[wheel[1][0]-27][wheel[1][2]] >= 100) {windex2 = 1;} wheel[1][2]++; if(wheel[1][2] > 25) {wheel[1][2] = 0;}} windex1 = 0; if(windex2 == 1){ wheel[2][2]++; if(wheel[2][2] > 25) {wheel[2][2] = 0;} windex2 = 0; } } void readplugs() { for (int index = 0 ; index <= 24; index++) { pinMode(plug[index], OUTPUT); digitalWrite(plug[index], LOW); for (int indexb = (index +1); indexb <= 25; indexb++) { int plugvar = digitalRead(plug[indexb]); if (plugvar == 0) { pluguse ++; plugval[0] [index] = 1; plugval[0] [indexb] = 1; plugval[1] [index] = indexb; plugval[1] [indexb] = index; } } pinMode(plug[index], INPUT); } plugred = 1; } ",16301,True,2565.350505378218,median "/* HelloWorld.ino Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 Oct 2018: U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2 make -f Makefile.184.uno text 8732 default, all active 8500 -232 -2.65% no U8G2_WITH_CLIP_WINDOW_SUPPORT 8316 -416 -4.76% no U8G2_WITH_FONT_ROTATION 8606 -126 -1.44% no U8G2_WITH_UNICODE 8692 -40 -0.45% no U8G2_WITH_INTERSECTION 8328 -404 -4.62% no U8G2_WITH_INTERSECTION no U8G2_WITH_CLIP_WINDOW_SUPPORT 8718 -14 -4.86% no U8G2_WITH_HVLINE_SPEED_OPTIMIZATION 8026 -706 -8.08% no U8G2_WITH_FONT_ROTATION no U8G2_WITH_INTERSECTION no U8G2_WITH_CLIP_WINDOW_SUPPORT Some flags depend on each other: `U8G2_WITH_INTERSECTION` is required for `U8G2_WITH_CLIP_WINDOW_SUPPORT`, so `U8G2_WITH_INTERSECTION` is partly active as long as `U8G2_WITH_CLIP_WINDOW_SUPPORT` is requested. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); } int x = 20; void loop(void) { u8g2.firstPage(); do { u8g2.setFont(u8g2_font_ncenB14_tr); u8g2.drawStr(0,x,""Hello World!""); } while ( u8g2.nextPage() ); delay(4000); x = x + 20; if (x == 200) {x = 20;} } ",16272,True,4951.33794778977,median "/* Terminal.ino Use display terminal to output text (using Arduino print) Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2018, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list U8G2LOG u8g2log; // setup the terminal (U8G2LOG) and connect to u8g2 for automatic refresh of the display // The size (width * height) depends on the selected font and the display // assume 4x6 font #define U8LOG_WIDTH 32 #define U8LOG_HEIGHT 10 uint8_t u8log_buffer[U8LOG_WIDTH*U8LOG_HEIGHT]; void setup(void) { /* U8g2 Project: SSD1306 Test Board */ pinMode(10, OUTPUT); pinMode(9, OUTPUT); digitalWrite(10, 0); digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); u8g2.setFont(u8g2_font_tom_thumb_4x6_mf); // set the font for the terminal window u8g2log.begin(u8g2, U8LOG_WIDTH, U8LOG_HEIGHT, u8log_buffer); u8g2log.setLineHeightOffset(0); // set extra space between lines in pixel, this can be negative u8g2log.setRedrawMode(0); // 0: Update screen with newline, 1: Update screen for every char } unsigned long t = 0; // print the output of millis() to the terminal every second void loop(void) { if ( t < millis() ) { t = millis() + 15000; // every 15 seconds u8g2log.print(""\\f""); // \\f = form feed: clear the screen } u8g2log.print(""millis=""); u8g2log.print(millis()); u8g2log.print(""\\n""); delay(500); } ",16284,True,4968.331585295379,median "/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package Box2D.Dynamics{ import Box2D.Common.Math.*; import Box2D.Common.*; import Box2D.Collision.*; import Box2D.Collision.Shapes.*; import Box2D.Dynamics.*; import Box2D.Dynamics.Contacts.*; import Box2D.Dynamics.Controllers.b2Controller; import Box2D.Dynamics.Controllers.b2ControllerEdge; import Box2D.Dynamics.Joints.*; import Box2D.Common.b2internal; use namespace b2internal; /** * The world class manages all physics entities, dynamic simulation, * and asynchronous queries. */ public class b2World { // Construct a world object. /** * @param gravity the world gravity vector. * @param doSleep improve performance by not simulating inactive bodies. */ public function b2World(gravity:b2Vec2, doSleep:Boolean){ m_destructionListener = null; m_debugDraw = null; m_bodyList = null; m_contactList = null; m_jointList = null; m_controllerList = null; m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_controllerCount = 0; m_warmStarting = true; m_continuousPhysics = true; m_allowSleep = doSleep; m_gravity = gravity; m_inv_dt0 = 0.0; m_contactManager.m_world = this; var bd:b2BodyDef = new b2BodyDef(); m_groundBody = CreateBody(bd); } /** * Destruct the world. All physics entities are destroyed and all heap memory is released. */ //~b2World(); /** * Register a destruction listener. */ public function SetDestructionListener(listener:b2DestructionListener) : void{ m_destructionListener = listener; } /** * Register a contact filter to provide specific control over collision. * Otherwise the default filter is used (b2_defaultFilter). */ public function SetContactFilter(filter:b2ContactFilter) : void{ m_contactManager.m_contactFilter = filter; } /** * Register a contact event listener */ public function SetContactListener(listener:b2ContactListener) : void{ m_contactManager.m_contactListener = listener; } /** * Register a routine for debug drawing. The debug draw functions are called * inside the b2World::Step method, so make sure your renderer is ready to * consume draw commands when you call Step(). */ public function SetDebugDraw(debugDraw:b2DebugDraw) : void{ m_debugDraw = debugDraw; } /** * Use the given object as a broadphase. * The old broadphase will not be cleanly emptied. * @warning It is not recommended you call this except immediately after constructing the world. * @warning This function is locked during callbacks. */ public function SetBroadPhase(broadPhase:IBroadPhase) : void { var oldBroadPhase:IBroadPhase = m_contactManager.m_broadPhase; m_contactManager.m_broadPhase = broadPhase; for (var b:b2Body = m_bodyList; b; b = b.m_next) { for (var f:b2Fixture = b.m_fixtureList; f; f = f.m_next) { f.m_proxy = broadPhase.CreateProxy(oldBroadPhase.GetFatAABB(f.m_proxy), f); } } } /** * Perform validation of internal data structures. */ public function Validate() : void { m_contactManager.m_broadPhase.Validate(); } /** * Get the number of broad-phase proxies. */ public function GetProxyCount() : int { return m_contactManager.m_broadPhase.GetProxyCount(); } /** * Create a rigid body given a definition. No reference to the definition * is retained. * @warning This function is locked during callbacks. */ public function CreateBody(def:b2BodyDef) : b2Body{ //b2Settings.b2Assert(m_lock == false); if (IsLocked() == true) { return null; } //void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); var b:b2Body = new b2Body(def, this); // Add to world doubly linked list. b.m_prev = null; b.m_next = m_bodyList; if (m_bodyList) { m_bodyList.m_prev = b; } m_bodyList = b; ++m_bodyCount; return b; } /** * Destroy a rigid body given a definition. No reference to the definition * is retained. This function is locked during callbacks. * @warning This automatically deletes all associated shapes and joints. * @warning This function is locked during callbacks. */ public function DestroyBody(b:b2Body) : void{ //b2Settings.b2Assert(m_bodyCount > 0); //b2Settings.b2Assert(m_lock == false); if (IsLocked() == true) { return; } // Delete the attached joints. var jn:b2JointEdge = b.m_jointList; while (jn) { var jn0:b2JointEdge = jn; jn = jn.next; if (m_destructionListener) { m_destructionListener.SayGoodbyeJoint(jn0.joint); } DestroyJoint(jn0.joint); } // Detach controllers attached to this body var coe:b2ControllerEdge = b.m_controllerList; while (coe) { var coe0:b2ControllerEdge = coe; coe = coe.nextController; coe0.controller.RemoveBody(b); } // Delete the attached contacts. var ce:b2ContactEdge = b.m_contactList; while (ce) { var ce0:b2ContactEdge = ce; ce = ce.next; m_contactManager.Destroy(ce0.contact); } b.m_contactList = null; // Delete the attached fixtures. This destroys broad-phase // proxies. var f:b2Fixture = b.m_fixtureList; while (f) { var f0:b2Fixture = f; f = f.m_next; if (m_destructionListener) { m_destructionListener.SayGoodbyeFixture(f0); } f0.DestroyProxy(m_contactManager.m_broadPhase); f0.Destroy(); //f0->~b2Fixture(); //m_blockAllocator.Free(f0, sizeof(b2Fixture)); } b.m_fixtureList = null; b.m_fixtureCount = 0; // Remove world body list. if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == m_bodyList) { m_bodyList = b.m_next; } --m_bodyCount; //b->~b2Body(); //m_blockAllocator.Free(b, sizeof(b2Body)); } /** * Create a joint to constrain bodies together. No reference to the definition * is retained. This may cause the connected bodies to cease colliding. * @warning This function is locked during callbacks. */ public function CreateJoint(def:b2JointDef) : b2Joint{ //b2Settings.b2Assert(m_lock == false); var j:b2Joint = b2Joint.Create(def, null); // Connect to the world list. j.m_prev = null; j.m_next = m_jointList; if (m_jointList) { m_jointList.m_prev = j; } m_jointList = j; ++m_jointCount; // Connect to the bodies' doubly linked lists. j.m_edgeA.joint = j; j.m_edgeA.other = j.m_bodyB; j.m_edgeA.prev = null; j.m_edgeA.next = j.m_bodyA.m_jointList; if (j.m_bodyA.m_jointList) j.m_bodyA.m_jointList.prev = j.m_edgeA; j.m_bodyA.m_jointList = j.m_edgeA; j.m_edgeB.joint = j; j.m_edgeB.other = j.m_bodyA; j.m_edgeB.prev = null; j.m_edgeB.next = j.m_bodyB.m_jointList; if (j.m_bodyB.m_jointList) j.m_bodyB.m_jointList.prev = j.m_edgeB; j.m_bodyB.m_jointList = j.m_edgeB; var bodyA:b2Body = def.bodyA; var bodyB:b2Body = def.bodyB; // If the joint prevents collisions, then flag any contacts for filtering. if (def.collideConnected == false ) { var edge:b2ContactEdge = bodyB.GetContactList(); while (edge) { if (edge.other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge.contact.FlagForFiltering(); } edge = edge.next; } } // Note: creating a joint doesn't wake the bodies. return j; } /** * Destroy a joint. This may cause the connected bodies to begin colliding. * @warning This function is locked during callbacks. */ public function DestroyJoint(j:b2Joint) : void{ //b2Settings.b2Assert(m_lock == false); var collideConnected:Boolean = j.m_collideConnected; // Remove from the doubly linked list. if (j.m_prev) { j.m_prev.m_next = j.m_next; } if (j.m_next) { j.m_next.m_prev = j.m_prev; } if (j == m_jointList) { m_jointList = j.m_next; } // Disconnect from island graph. var bodyA:b2Body = j.m_bodyA; var bodyB:b2Body = j.m_bodyB; // Wake up connected bodies. bodyA.SetAwake(true); bodyB.SetAwake(true); // Remove from body 1. if (j.m_edgeA.prev) { j.m_edgeA.prev.next = j.m_edgeA.next; } if (j.m_edgeA.next) { j.m_edgeA.next.prev = j.m_edgeA.prev; } if (j.m_edgeA == bodyA.m_jointList) { bodyA.m_jointList = j.m_edgeA.next; } j.m_edgeA.prev = null; j.m_edgeA.next = null; // Remove from body 2 if (j.m_edgeB.prev) { j.m_edgeB.prev.next = j.m_edgeB.next; } if (j.m_edgeB.next) { j.m_edgeB.next.prev = j.m_edgeB.prev; } if (j.m_edgeB == bodyB.m_jointList) { bodyB.m_jointList = j.m_edgeB.next; } j.m_edgeB.prev = null; j.m_edgeB.next = null; b2Joint.Destroy(j, null); //b2Settings.b2Assert(m_jointCount > 0); --m_jointCount; // If the joint prevents collisions, then flag any contacts for filtering. if (collideConnected == false) { var edge:b2ContactEdge = bodyB.GetContactList(); while (edge) { if (edge.other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge.contact.FlagForFiltering(); } edge = edge.next; } } } /** * Add a controller to the world list */ public function AddController(c:b2Controller) : b2Controller { c.m_next = m_controllerList; c.m_prev = null; m_controllerList = c; c.m_world = this; m_controllerCount++; return c; } public function RemoveController(c:b2Controller) : void { //TODO: Remove bodies from controller if (c.m_prev) c.m_prev.m_next = c.m_next; if (c.m_next) c.m_next.m_prev = c.m_prev; if (m_controllerList == c) m_controllerList = c.m_next; m_controllerCount--; } public function CreateController(controller:b2Controller):b2Controller { if (controller.m_world != this) throw new Error(""Controller can only be a member of one world""); controller.m_next = m_controllerList; controller.m_prev = null; if (m_controllerList) m_controllerList.m_prev = controller; m_controllerList = controller; ++m_controllerCount; controller.m_world = this; return controller; } public function DestroyController(controller:b2Controller):void { //b2Settings.b2Assert(m_controllerCount > 0); controller.Clear(); if (controller.m_next) controller.m_next.m_prev = controller.m_prev; if (controller.m_prev) controller.m_prev.m_next = controller.m_next; if (controller == m_controllerList) m_controllerList = controller.m_next; --m_controllerCount; } /** * Enable/disable warm starting. For testing. */ public function SetWarmStarting(flag: Boolean) : void { m_warmStarting = flag; } /** * Enable/disable continuous physics. For testing. */ public function SetContinuousPhysics(flag: Boolean) : void { m_continuousPhysics = flag; } /** * Get the number of bodies. */ public function GetBodyCount() : int { return m_bodyCount; } /** * Get the number of joints. */ public function GetJointCount() : int { return m_jointCount; } /** * Get the number of contacts (each may have 0 or more contact points). */ public function GetContactCount() : int { return m_contactCount; } /** * Change the global gravity vector. */ public function SetGravity(gravity: b2Vec2): void { m_gravity = gravity; } /** * Get the global gravity vector. */ public function GetGravity():b2Vec2{ return m_gravity; } /** * The world provides a single static ground body with no collision shapes. * You can use this to simplify the creation of joints and static shapes. */ public function GetGroundBody() : b2Body{ return m_groundBody; } private static var s_timestep2:b2TimeStep = new b2TimeStep(); /** * Take a time step. This performs collision detection, integration, * and constraint solution. * @param timeStep the amount of time to simulate, this should not vary. * @param velocityIterations for the velocity constraint solver. * @param positionIterations for the position constraint solver. */ public function Step(dt:Number, velocityIterations:int, positionIterations:int) : void{ if (m_flags & e_newFixture) { m_contactManager.FindNewContacts(); m_flags &= ~e_newFixture; } m_flags |= e_locked; var step:b2TimeStep = s_timestep2; step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; if (dt > 0.0) { step.inv_dt = 1.0 / dt; } else { step.inv_dt = 0.0; } step.dtRatio = m_inv_dt0 * dt; step.warmStarting = m_warmStarting; // Update contacts. m_contactManager.Collide(); // Integrate velocities, solve velocity constraints, and integrate positions. if (step.dt > 0.0) { Solve(step); } // Handle TOI events. if (m_continuousPhysics && step.dt > 0.0) { SolveTOI(step); } if (step.dt > 0.0) { m_inv_dt0 = step.inv_dt; } m_flags &= ~e_locked; } /** * Call this after you are done with time steps to clear the forces. You normally * call this after each call to Step, unless you are performing sub-steps. */ public function ClearForces() : void { for (var body:b2Body = m_bodyList; body; body = body.m_next) { body.m_force.SetZero(); body.m_torque = 0.0; } } static private var s_xf:b2Transform = new b2Transform(); /** * Call this to draw shapes and other debug draw data. */ public function DrawDebugData() : void{ if (m_debugDraw == null) { return; } m_debugDraw.m_sprite.graphics.clear(); var flags:uint = m_debugDraw.GetFlags(); var i:int; var b:b2Body; var f:b2Fixture; var s:b2Shape; var j:b2Joint; var bp:IBroadPhase; var invQ:b2Vec2 = new b2Vec2; var x1:b2Vec2 = new b2Vec2; var x2:b2Vec2 = new b2Vec2; var xf:b2Transform; var b1:b2AABB = new b2AABB(); var b2:b2AABB = new b2AABB(); var vs:Array = [new b2Vec2(), new b2Vec2(), new b2Vec2(), new b2Vec2()]; // Store color here and reuse, to reduce allocations var color:b2Color = new b2Color(0, 0, 0); if (flags & b2DebugDraw.e_shapeBit) { for (b = m_bodyList; b; b = b.m_next) { xf = b.m_xf; for (f = b.GetFixtureList(); f; f = f.m_next) { s = f.GetShape(); if (b.IsActive() == false) { color.Set(0.5, 0.5, 0.3); DrawShape(s, xf, color); } else if (b.GetType() == b2Body.b2_staticBody) { color.Set(0.5, 0.9, 0.5); DrawShape(s, xf, color); } else if (b.GetType() == b2Body.b2_kinematicBody) { color.Set(0.5, 0.5, 0.9); DrawShape(s, xf, color); } else if (b.IsAwake() == false) { color.Set(0.6, 0.6, 0.6); DrawShape(s, xf, color); } else { color.Set(0.9, 0.7, 0.7); DrawShape(s, xf, color); } } } } if (flags & b2DebugDraw.e_jointBit) { for (j = m_jointList; j; j = j.m_next) { DrawJoint(j); } } if (flags & b2DebugDraw.e_controllerBit) { for (var c:b2Controller = m_controllerList; c; c = c.m_next) { c.Draw(m_debugDraw); } } if (flags & b2DebugDraw.e_pairBit) { color.Set(0.3, 0.9, 0.9); for (var contact:b2Contact = m_contactManager.m_contactList; contact; contact = contact.GetNext()) { var fixtureA:b2Fixture = contact.GetFixtureA(); var fixtureB:b2Fixture = contact.GetFixtureB(); var cA:b2Vec2 = fixtureA.GetAABB().GetCenter(); var cB:b2Vec2 = fixtureB.GetAABB().GetCenter(); m_debugDraw.DrawSegment(cA, cB, color); } } if (flags & b2DebugDraw.e_aabbBit) { bp = m_contactManager.m_broadPhase; vs = [new b2Vec2(),new b2Vec2(),new b2Vec2(),new b2Vec2()]; for (b= m_bodyList; b; b = b.GetNext()) { if (b.IsActive() == false) { continue; } for (f = b.GetFixtureList(); f; f = f.GetNext()) { var aabb:b2AABB = bp.GetFatAABB(f.m_proxy); vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); m_debugDraw.DrawPolygon(vs, 4, color); } } } if (flags & b2DebugDraw.e_centerOfMassBit) { for (b = m_bodyList; b; b = b.m_next) { xf = s_xf; xf.R = b.m_xf.R; xf.position = b.GetWorldCenter(); m_debugDraw.DrawTransform(xf); } } } /** * Query the world for all fixtures that potentially overlap the * provided AABB. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @param aabb the query box. */ public function QueryAABB(callback:Function, aabb:b2AABB):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { return callback(broadPhase.GetUserData(proxy)); } broadPhase.Query(WorldQueryWrapper, aabb); } /** * Query the world for all fixtures that precisely overlap the * provided transformed shape. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @asonly */ public function QueryShape(callback:Function, shape:b2Shape, transform:b2Transform = null):void { if (transform == null) { transform = new b2Transform(); transform.SetIdentity(); } var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { var fixture:b2Fixture = broadPhase.GetUserData(proxy) as b2Fixture if(b2Shape.TestOverlap(shape, transform, fixture.GetShape(), fixture.GetBody().GetTransform())) return callback(fixture); return true; } var aabb:b2AABB = new b2AABB(); shape.ComputeAABB(aabb, transform); broadPhase.Query(WorldQueryWrapper, aabb); } /** * Query the world for all fixtures that contain a point. * @param callback a user implemented callback class. It should match signature * function Callback(fixture:b2Fixture):Boolean * Return true to continue to the next fixture. * @asonly */ public function QueryPoint(callback:Function, p:b2Vec2):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; function WorldQueryWrapper(proxy:*):Boolean { var fixture:b2Fixture = broadPhase.GetUserData(proxy) as b2Fixture if(fixture.TestPoint(p)) return callback(fixture); return true; } // Make a small box. var aabb:b2AABB = new b2AABB(); aabb.lowerBound.Set(p.x - b2Settings.b2_linearSlop, p.y - b2Settings.b2_linearSlop); aabb.upperBound.Set(p.x + b2Settings.b2_linearSlop, p.y + b2Settings.b2_linearSlop); broadPhase.Query(WorldQueryWrapper, aabb); } /** * Ray-cast the world for all fixtures in the path of the ray. Your callback * Controls whether you get the closest point, any point, or n-points * The ray-cast ignores shapes that contain the starting point * @param callback A callback function which must be of signature: * function Callback(fixture:b2Fixture, // The fixture hit by the ray * point:b2Vec2, // The point of initial intersection * normal:b2Vec2, // The normal vector at the point of intersection * fraction:Number // The fractional length along the ray of the intersection * ):Number * * Callback should return the new length of the ray as a fraction of the original length. * By returning 0, you immediately terminate. * By returning 1, you continue wiht the original ray. * By returning the current fraction, you proceed to find the closest point. * @param point1 the ray starting point * @param point2 the ray ending point */ public function RayCast(callback:Function, point1:b2Vec2, point2:b2Vec2):void { var broadPhase:IBroadPhase = m_contactManager.m_broadPhase; var output:b2RayCastOutput = new b2RayCastOutput; function RayCastWrapper(input:b2RayCastInput, proxy:*):Number { var userData:* = broadPhase.GetUserData(proxy); var fixture:b2Fixture = userData as b2Fixture; var hit:Boolean = fixture.RayCast(output, input); if (hit) { var fraction:Number = output.fraction; var point:b2Vec2 = new b2Vec2( (1.0 - fraction) * point1.x + fraction * point2.x, (1.0 - fraction) * point1.y + fraction * point2.y); return callback(fixture, point, output.normal, fraction); } return input.maxFraction; } var input:b2RayCastInput = new b2RayCastInput(point1, point2); broadPhase.RayCast(RayCastWrapper, input); } public function RayCastOne(point1:b2Vec2, point2:b2Vec2):b2Fixture { var result:b2Fixture; function RayCastOneWrapper(fixture:b2Fixture, point:b2Vec2, normal:b2Vec2, fraction:Number):Number { result = fixture; return fraction; } RayCast(RayCastOneWrapper, point1, point2); return result; } public function RayCastAll(point1:b2Vec2, point2:b2Vec2):Vector. { var result:Vector. = new Vector.(); function RayCastAllWrapper(fixture:b2Fixture, point:b2Vec2, normal:b2Vec2, fraction:Number):Number { result[result.length] = fixture; return 1; } RayCast(RayCastAllWrapper, point1, point2); return result; } /** * Get the world body list. With the returned body, use b2Body::GetNext to get * the next body in the world list. A NULL body indicates the end of the list. * @return the head of the world body list. */ public function GetBodyList() : b2Body{ return m_bodyList; } /** * Get the world joint list. With the returned joint, use b2Joint::GetNext to get * the next joint in the world list. A NULL joint indicates the end of the list. * @return the head of the world joint list. */ public function GetJointList() : b2Joint{ return m_jointList; } /** * Get the world contact list. With the returned contact, use b2Contact::GetNext to get * the next contact in the world list. A NULL contact indicates the end of the list. * @return the head of the world contact list. * @warning contacts are */ public function GetContactList():b2Contact { return m_contactList; } /** * Is the world locked (in the middle of a time step). */ public function IsLocked():Boolean { return (m_flags & e_locked) > 0; } //--------------- Internals Below ------------------- // Internal yet public to make life easier. // Find islands, integrate and solve constraints, solve position constraints private var s_stack:Vector. = new Vector.(); b2internal function Solve(step:b2TimeStep) : void{ var b:b2Body; // Step all controllers for(var controller:b2Controller= m_controllerList;controller;controller=controller.m_next) { controller.Step(step); } // Size the island for the worst case. var island:b2Island = m_island; island.Initialize(m_bodyCount, m_contactCount, m_jointCount, null, m_contactManager.m_contactListener, m_contactSolver); // Clear all the island flags. for (b = m_bodyList; b; b = b.m_next) { b.m_flags &= ~b2Body.e_islandFlag; } for (var c:b2Contact = m_contactList; c; c = c.m_next) { c.m_flags &= ~b2Contact.e_islandFlag; } for (var j:b2Joint = m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } // Build and simulate all awake islands. var stackSize:int = m_bodyCount; //b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); var stack:Vector. = s_stack; for (var seed:b2Body = m_bodyList; seed; seed = seed.m_next) { if (seed.m_flags & b2Body.e_islandFlag ) { continue; } if (seed.IsAwake() == false || seed.IsActive() == false) { continue; } // The seed can be dynamic or kinematic. if (seed.GetType() == b2Body.b2_staticBody) { continue; } // Reset island and stack. island.Clear(); var stackCount:int = 0; stack[stackCount++] = seed; seed.m_flags |= b2Body.e_islandFlag; // Perform a depth first search (DFS) on the constraint graph. while (stackCount > 0) { // Grab the next body off the stack and add it to the island. b = stack[--stackCount]; //b2Assert(b.IsActive() == true); island.AddBody(b); // Make sure the body is awake. if (b.IsAwake() == false) { b.SetAwake(true); } // To keep islands as small as possible, we don't // propagate islands across static bodies. if (b.GetType() == b2Body.b2_staticBody) { continue; } var other:b2Body; // Search all contacts connected to this body. for (var ce:b2ContactEdge = b.m_contactList; ce; ce = ce.next) { // Has this contact already been added to an island? if (ce.contact.m_flags & b2Contact.e_islandFlag) { continue; } // Is this contact solid and touching? if (ce.contact.IsSensor() == true || ce.contact.IsEnabled() == false || ce.contact.IsTouching() == false) { continue; } island.AddContact(ce.contact); ce.contact.m_flags |= b2Contact.e_islandFlag; //var other:b2Body = ce.other; other = ce.other; // Was the other body already added to this island? if (other.m_flags & b2Body.e_islandFlag) { continue; } //b2Settings.b2Assert(stackCount < stackSize); stack[stackCount++] = other; other.m_flags |= b2Body.e_islandFlag; } // Search all joints connect to this body. for (var jn:b2JointEdge = b.m_jointList; jn; jn = jn.next) { if (jn.joint.m_islandFlag == true) { continue; } other = jn.other; // Don't simulate joints connected to inactive bodies. if (other.IsActive() == false) { continue; } island.AddJoint(jn.joint); jn.joint.m_islandFlag = true; if (other.m_flags & b2Body.e_islandFlag) { continue; } //b2Settings.b2Assert(stackCount < stackSize); stack[stackCount++] = other; other.m_flags |= b2Body.e_islandFlag; } } island.Solve(step, m_gravity, m_allowSleep); // Post solve cleanup. for (var i:int = 0; i < island.m_bodyCount; ++i) { // Allow static bodies to participate in other islands. b = island.m_bodies[i]; if (b.GetType() == b2Body.b2_staticBody) { b.m_flags &= ~b2Body.e_islandFlag; } } } //m_stackAllocator.Free(stack); for (i = 0; i < stack.length;++i) { if (!stack[i]) break; stack[i] = null; } // Synchronize fixutres, check for out of range bodies. for (b = m_bodyList; b; b = b.m_next) { if (b.IsAwake() == false || b.IsActive() == false) { continue; } if (b.GetType() == b2Body.b2_staticBody) { continue; } // Update fixtures (for broad-phase). b.SynchronizeFixtures(); } // Look for new contacts. m_contactManager.FindNewContacts(); } private static var s_backupA:b2Sweep = new b2Sweep(); private static var s_backupB:b2Sweep = new b2Sweep(); private static var s_timestep:b2TimeStep = new b2TimeStep(); private static var s_queue:Vector. = new Vector.(); // Find TOI contacts and solve them. b2internal function SolveTOI(step:b2TimeStep) : void{ var b:b2Body; var fA:b2Fixture; var fB:b2Fixture; var bA:b2Body; var bB:b2Body; var cEdge:b2ContactEdge; var j:b2Joint; // Reserve an island and a queue for TOI island solution. var island:b2Island = m_island; island.Initialize(m_bodyCount, b2Settings.b2_maxTOIContactsPerIsland, b2Settings.b2_maxTOIJointsPerIsland, null, m_contactManager.m_contactListener, m_contactSolver); //Simple one pass queue //Relies on the fact that we're only making one pass //through and each body can only be pushed/popped one. //To push: // queue[queueStart+queueSize++] = newElement; //To pop: // poppedElement = queue[queueStart++]; // --queueSize; var queue:Vector. = s_queue; for (b = m_bodyList; b; b = b.m_next) { b.m_flags &= ~b2Body.e_islandFlag; b.m_sweep.t0 = 0.0; } var c:b2Contact; for (c = m_contactList; c; c = c.m_next) { // Invalidate TOI c.m_flags &= ~(b2Contact.e_toiFlag | b2Contact.e_islandFlag); } for (j = m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } // Find TOI events and solve them. for (;;) { // Find the first TOI. var minContact:b2Contact = null; var minTOI:Number = 1.0; for (c = m_contactList; c; c = c.m_next) { // Can this contact generate a solid TOI contact? if (c.IsSensor() == true || c.IsEnabled() == false || c.IsContinuous() == false) { continue; } // TODO_ERIN keep a counter on the contact, only respond to M TOIs per contact. var toi:Number = 1.0; if (c.m_flags & b2Contact.e_toiFlag) { // This contact has a valid cached TOI. toi = c.m_toi; } else { // Compute the TOI for this contact. fA = c.m_fixtureA; fB = c.m_fixtureB; bA = fA.m_body; bB = fB.m_body; if ((bA.GetType() != b2Body.b2_dynamicBody || bA.IsAwake() == false) && (bB.GetType() != b2Body.b2_dynamicBody || bB.IsAwake() == false)) { continue; } // Put the sweeps onto the same time interval. var t0:Number = bA.m_sweep.t0; if (bA.m_sweep.t0 < bB.m_sweep.t0) { t0 = bB.m_sweep.t0; bA.m_sweep.Advance(t0); } else if (bB.m_sweep.t0 < bA.m_sweep.t0) { t0 = bA.m_sweep.t0; bB.m_sweep.Advance(t0); } //b2Settings.b2Assert(t0 < 1.0f); // Compute the time of impact. toi = c.ComputeTOI(bA.m_sweep, bB.m_sweep); b2Settings.b2Assert(0.0 <= toi && toi <= 1.0); // If the TOI is in range ... if (toi > 0.0 && toi < 1.0) { // Interpolate on the actual range. //toi = Math.min((1.0 - toi) * t0 + toi, 1.0); toi = (1.0 - toi) * t0 + toi; if (toi > 1) toi = 1; } c.m_toi = toi; c.m_flags |= b2Contact.e_toiFlag; } if (Number.MIN_VALUE < toi && toi < minTOI) { // This is the minimum TOI found so far. minContact = c; minTOI = toi; } } if (minContact == null || 1.0 - 100.0 * Number.MIN_VALUE < minTOI) { // No more TOI events. Done! break; } // Advance the bodies to the TOI. fA = minContact.m_fixtureA; fB = minContact.m_fixtureB; bA = fA.m_body; bB = fB.m_body; s_backupA.Set(bA.m_sweep); s_backupB.Set(bB.m_sweep); bA.Advance(minTOI); bB.Advance(minTOI); // The TOI contact likely has some new contact points. minContact.Update(m_contactManager.m_contactListener); minContact.m_flags &= ~b2Contact.e_toiFlag; // Is the contact solid? if (minContact.IsSensor() == true || minContact.IsEnabled() == false) { // Restore the sweeps bA.m_sweep.Set(s_backupA); bB.m_sweep.Set(s_backupB); bA.SynchronizeTransform(); bB.SynchronizeTransform(); continue; } // Did numerical issues prevent;,ontact pointjrom being generated if (minContact.IsTouching() == false) { // Give up on this TOI continue; } // Build the TOI island. We need a dynamic seed. var seed:b2Body = bA; if (seed.GetType() != b2Body.b2_dynamicBody) { seed = bB; } // Reset island and queue. island.Clear(); var queueStart:int = 0; //start index for queue var queueSize:int = 0; //elements in queue queue[queueStart + queueSize++] = seed; seed.m_flags |= b2Body.e_islandFlag; // Perform a breadth first search (BFS) on the contact graph. while (queueSize > 0) { // Grab the next body off the stack and add it to the island. b = queue[queueStart++]; --queueSize; island.AddBody(b); // Make sure the body is awake. if (b.IsAwake() == false) { b.SetAwake(true); } // To keep islands as small as possible, we don't // propagate islands across static or kinematic bodies. if (b.GetType() != b2Body.b2_dynamicBody) { continue; } // Search all contacts connected to this body. for (cEdge = b.m_contactList; cEdge; cEdge = cEdge.next) { // Does the TOI island still have space for contacts? if (island.m_contactCount == island.m_contactCapacity) { break; } // Has this contact already been added to an island? if (cEdge.contact.m_flags & b2Contact.e_islandFlag) { continue; } // Skip sperate, sensor, or disabled contacts. if (cEdge.contact.IsSensor() == true || cEdge.contact.IsEnabled() == false || cEdge.contact.IsTouching() == false) { continue; } island.AddContact(cEdge.contact); cEdge.contact.m_flags |= b2Contact.e_islandFlag; // Update other body. var other:b2Body = cEdge.other; // Was the other body already added to this island? if (other.m_flags & b2Body.e_islandFlag) { continue; } // Synchronize the connected body. if (other.GetType() != b2Body.b2_staticBody) { other.Advance(minTOI); other.SetAwake(true); } //b2Settings.b2Assert(queueStart + queueSize < queueCapacity); queue[queueStart + queueSize] = other; ++queueSize; other.m_flags |= b2Body.e_islandFlag; } for (var jEdge:b2JointEdge = b.m_jointList; jEdge; jEdge = jEdge.next) { if (island.m_jointCount == island.m_jointCapacity) continue; if (jEdge.joint.m_islandFlag == true) continue; other = jEdge.other; if (other.IsActive() == false) { continue; } island.AddJoint(jEdge.joint); jEdge.joint.m_islandFlag = true; if (other.m_flags & b2Body.e_islandFlag) continue; // Synchronize the connected body. if (other.GetType() != b2Body.b2_staticBody) { other.Advance(minTOI); other.SetAwake(true); } //b2Settings.b2Assert(queueStart + queueSize < queueCapacity); queue[queueStart + queueSize] = other; ++queueSize; other.m_flags |= b2Body.e_islandFlag; } } var subStep:b2TimeStep = s_timestep; subStep.warmStarting = false; subStep.dt = (1.0 - minTOI) * step.dt; subStep.inv_dt = 1.0 / subStep.dt; subStep.dtRatio = 0.0; subStep.velocityIterations = step.velocityIterations; subStep.positionIterations = step.positionIterations; island.SolveTOI(subStep); var i:int; // Post solve cleanup. for (i = 0; i < island.m_bodyCount; ++i) { // Allow bodies to participate in future TOI islands. b = island.m_bodies[i]; b.m_flags &= ~b2Body.e_islandFlag; if (b.IsAwake() == false) { continue; } if (b.GetType() != b2Body.b2_dynamicBody) { continue; } // Update fixtures (for broad-phase). b.SynchronizeFixtures(); // Invalidate all contact TOIs associated with this body. Some of these // may not be in the island because they were not touching. for (cEdge = b.m_contactList; cEdge; cEdge = cEdge.next) { cEdge.contact.m_flags &= ~b2Contact.e_toiFlag; } } for (i = 0; i < island.m_contactCount; ++i) { // Allow contacts to participate in future TOI islands. c = island.m_contacts[i]; c.m_flags &= ~(b2Contact.e_toiFlag | b2Contact.e_islandFlag); } for (i = 0; i < island.m_jointCount;++i) { // Allow joints to participate in future TOI islands j = island.m_joints[i]; j.m_islandFlag = false; } // Commit fixture proxy movements to the broad-phase so that new contacts are created. // Also, some contacts can be destroyed. m_contactManager.FindNewContacts(); } //m_stackAllocator.Free(queue); } static private var s_jointColor:b2Color = new b2Color(0.5, 0.8, 0.8); // b2internal function DrawJoint(joint:b2Joint) : void{ var b1:b2Body = joint.GetBodyA(); var b2:b2Body = joint.GetBodyB(); var xf1:b2Transform = b1.m_xf; var xf2:b2Transform = b2.m_xf; var x1:b2Vec2 = xf1.position; var x2:b2Vec2 = xf2.position; var p1:b2Vec2 = joint.GetAnchorA(); var p2:b2Vec2 = joint.GetAnchorB(); //b2Color color(0.5f, 0.8f, 0.8f); var color:b2Color = s_jointColor; switch (joint.m_type) { case b2Joint.e_distanceJoint: m_debugDraw.DrawSegment(p1, p2, color); break; case b2Joint.e_pulleyJoint: { var pulley:b2PulleyJoint = (joint as b2PulleyJoint); var s1:b2Vec2 = pulley.GetGroundAnchorA(); var s2:b2Vec2 = pulley.GetGroundAnchorB(); m_debugDraw.DrawSegment(s1, p1, color); m_debugDraw.DrawSegment(s2, p2, color); m_debugDraw.DrawSegment(s1, s2, color); } break; case b2Joint.e_mouseJoint: m_debugDraw.DrawSegment(p1, p2, color); break; default: if (b1 != m_groundBody) m_debugDraw.DrawSegment(x1, p1, color); m_debugDraw.DrawSegment(p1, p2, color); if (b2 != m_groundBody) m_debugDraw.DrawSegment(x2, p2, color); } } b2internal function DrawShape(shape:b2Shape, xf:b2Transform, color:b2Color) : void{ switch (shape.m_type) { case b2Shape.e_circleShape: { var circle:b2CircleShape = (shape as b2CircleShape); var center:b2Vec2 = b2Math.MulX(xf, circle.m_p); var radius:Number = circle.m_radius; var axis:b2Vec2 = xf.R.col1; m_debugDraw.DrawSolidCircle(center, radius, axis, color); } break; case b2Shape.e_polygonShape: { var i:int; var poly:b2PolygonShape = (shape as b2PolygonShape); var vertexCount:int = poly.GetVertexCount(); var localVertices:Vector. = poly.GetVertices(); var vertices:Vector. = new Vector.(vertexCount); for (i = 0; i < vertexCount; ++i) { vertices[i] = b2Math.MulX(xf, localVertices[i]); } m_debugDraw.DrawSolidPolygon(vertices, vertexCount, color); } break; case b2Shape.e_edgeShape: { var edge: b2EdgeShape = shape as b2EdgeShape; m_debugDraw.DrawSegment(b2Math.MulX(xf, edge.GetVertex1()), b2Math.MulX(xf, edge.GetVertex2()), color); } break; } } b2internal var m_flags:int; b2internal var m_contactManager:b2ContactManager = new b2ContactManager(); // These two are stored purely for efficiency purposes, they don't maintain // any data outside of a call to Step private var m_contactSolver:b2ContactSolver = new b2ContactSolver(); private var m_island:b2Island = new b2Island(); b2internal var m_bodyList:b2Body; private var m_jointList:b2Joint; b2internal var m_contactList:b2Contact; private var m_bodyCount:int; b2internal var m_contactCount:int; private var m_jointCount:int; private var m_controllerList:b2Controller; private var m_controllerCount:int; private var m_gravity:b2Vec2; private var m_allowSleep:Boolean; b2internal var m_groundBody:b2Body; private var m_destructionListener:b2DestructionListener; private var m_debugDraw:b2DebugDraw; // This is used to compute the time step ratio to support a variable time step. private var m_inv_dt0:Number; // This is for debugging the solver. static private var m_warmStarting:Boolean; // This is for debugging the solver. static private var m_continuousPhysics:Boolean; // m_flags public static const e_newFixture:int = 0x0001; public static const e_locked:int = 0x0002; }; } ",12199,False,2272.2666713109493,median "package com.tinyspeck.engine.view.gameoverlay.maps { import com.tinyspeck.core.beacon.StageBeacon; import com.tinyspeck.debug.Console; import com.tinyspeck.engine.control.TSFrontController; import com.tinyspeck.engine.data.client.Activity; import com.tinyspeck.engine.data.location.Hub; import com.tinyspeck.engine.data.location.Location; import com.tinyspeck.engine.data.location.SignPost; import com.tinyspeck.engine.data.map.MapData; import com.tinyspeck.engine.data.map.Street; import com.tinyspeck.engine.data.pc.PC; import com.tinyspeck.engine.data.transit.Transit; import com.tinyspeck.engine.data.transit.TransitLine; import com.tinyspeck.engine.data.transit.TransitStatus; import com.tinyspeck.engine.event.TSEvent; import com.tinyspeck.engine.loader.SmartLoader; import com.tinyspeck.engine.net.NetOutgoingMapGetVO; import com.tinyspeck.engine.net.NetResponseMessageVO; import com.tinyspeck.engine.ns.client; import com.tinyspeck.engine.port.AssetManager; import com.tinyspeck.engine.port.IMoveListener; import com.tinyspeck.engine.port.RightSideManager; import com.tinyspeck.engine.port.TransitManager; import com.tinyspeck.engine.port.WindowBorder; import com.tinyspeck.engine.sound.SoundMaster; import com.tinyspeck.engine.util.DrawUtil; import com.tinyspeck.engine.util.SpriteUtil; import com.tinyspeck.engine.util.TFUtil; import com.tinyspeck.engine.util.URLUtil; import com.tinyspeck.engine.view.ui.Button; import com.tinyspeck.engine.view.ui.Dialog; import com.tinyspeck.engine.view.ui.TSLinkedTextField; import com.tinyspeck.engine.view.ui.TSScroller; import com.tinyspeck.engine.view.ui.Toast; import com.tinyspeck.engine.view.ui.map.LocationSearchMap; import com.tinyspeck.engine.view.ui.map.MapChatArea; import com.tinyspeck.engine.view.util.StaticFilters; import com.tinyspeck.tstweener.TSTweener; import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.MovieClip; import flash.display.Sprite; import flash.events.TextEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.text.TextField; import flash.utils.Dictionary; public class HubMapDialog extends Dialog implements IMoveListener { /* singleton boilerplate */ public static const instance:HubMapDialog = new HubMapDialog(); public static const MAP_ACTUAL_W:int = 760; // this is the w of the loaded coordinate space public static const MAP_ACTUAL_H:int = 460; // this is the h of the loaded coordinate space public static const MAP_W:int = 760; public static const MAP_H:int = 460; private static const RESULTS_WIDTH:uint = 235; private static const RESULTS_HEIGHT:uint = 150; private static const STAR_COLOR:uint = 0xc50202; private static const STREET_ROTATION_BUFFER:uint = 5; //how many degrees from 90 does this mean the street is vertical private static const TRANSIT_PADD:uint = 5; //px between transit buttons public var current_street:Street; private var header_h:int = 60; private var next_transit_bt_x:int; private var map_hubsD:Dictionary = new Dictionary(); private var map_transitsD:Dictionary = new Dictionary(); private var loc_name_tf:TextField = new TextField(); private var extra_tf:TextField = new TextField(); private var search_results_tf:TSLinkedTextField = new TSLinkedTextField(); private var current_hub_id:String; private var current_transit_tsid:String; private var current_location_id:String; private var hub_click_hub_id:String; private var hub_click_location_id:String; private var transition_direction:String; private var world_map_url:String; private var you_view_holder:Sprite = new Sprite(); private var you_view_world_holder:Sprite = new Sprite(); private var transit_you_view_holder:Sprite = new Sprite(); private var all_maps_container:Sprite = new Sprite(); private var all_maps_container_mask:Sprite = new Sprite(); private var search_results_holder:Sprite = new Sprite(); private var load_blocker:Sprite = new Sprite(); private var transit_bt:Button; private var world_map_in_bt:Button; private var world_map_out_bt:Button; private var recenter_bt:Button; private var displayed_map_hub:MapHub; private var displayed_map_transit:MapTransit; private var location_search:LocationSearchMap; private var search_scroller:TSScroller; private var toast:Toast; private var region_rect:Rectangle; private var animate_transit_map:Boolean; private var hub_click_flash_loc:Boolean; private var showing_transit_map:Boolean; private var cancel_transit_display:Boolean; private var showing_world_map:Boolean; private var is_built:Boolean; private var is_map_loading:Boolean; private var _open_map_chat_when_closed:Boolean; private var start_with_world_map:Boolean; private var world_map_mc:MovieClip; private var world_map_clicked_region:DisplayObject; public function HubMapDialog() { CONFIG::god { if(instance) throw new Error('Singleton'); } _w = MAP_W+(_border_w*2); _h = MAP_H+header_h+(_border_w*2); _draggable = true; close_on_editing = false; close_on_move = false; _construct(); } override protected function _construct() : void { super._construct(); all_maps_container_mask.y = _border_w; all_maps_container_mask.x = _border_w; //draw the mask, and when using a complex rect the corner_rad var needs to be divided by 2 var g:Graphics = all_maps_container_mask.graphics; g.beginFill(0, 1); g.drawRoundRectComplex(0, header_h, _w-(_border_w*2), _h-header_h-(_border_w*2), 0, 0, corner_rad/2, corner_rad/2); addChild(all_maps_container_mask); all_maps_container.y = header_h+_border_w; all_maps_container.x = _border_w; all_maps_container.mask = all_maps_container_mask; addChild(all_maps_container); // loc_name_tf TFUtil.prepTF(loc_name_tf); loc_name_tf.width = _w; loc_name_tf.mouseEnabled = false; addChild(loc_name_tf); // extra_tf TFUtil.prepTF(extra_tf, false); CONFIG::god { extra_tf.htmlText = 'ADMIN: Edit Map'; addChild(extra_tf); } /*CONFIG::debugging { Console.warn(CONFIG::god+' ---- '+extra_tf.htmlText) }*/ extra_tf.x = _base_padd; extra_tf.y = header_h-extra_tf.height+5; extra_tf.addEventListener(TextEvent.LINK, tfLinkHandler); recenter_bt = new Button({ name: 'recenter', size: Button.SIZE_TINY, type: Button.TYPE_MINOR, graphic: new AssetManager.instance.assets.recenter_link(), graphic_disabled: new AssetManager.instance.assets.recenter_disabled(), graphic_hover: new AssetManager.instance.assets.recenter_hover(), graphic_padd_w: 11, x: _base_padd+9, y: _base_padd+10, w: 36, h: 27, tip: { txt: 'Go to my location', pointer: WindowBorder.POINTER_BOTTOM_CENTER } }); recenter_bt.addEventListener(TSEvent.CHANGED, onRecenterClick, false, 0, true); addChild(recenter_bt); //make sure the next button is in the right place next_transit_bt_x = recenter_bt.x + recenter_bt.width + TRANSIT_PADD; //search field location_search = new LocationSearchMap(); location_search.x = int(_w - location_search.width - 53); location_search.y = int((header_h+_border_w*2)/2 - location_search.height/2); location_search.holder_offset = location_search.height + 17; addChild(location_search); //setup the scroller search_scroller = new TSScroller({ name: 'search_scroller', w:RESULTS_WIDTH - 10, h:RESULTS_HEIGHT - 10, bar_wh: 12, bar_color: 0xecf0f1, bar_border_color: 0xd2dadc, bar_border_width: 1, bar_handle_color: 0xcfdcdd, bar_handle_border_color: 0xb0bfc2, bar_handle_stripes_alpha: 0, bar_handle_min_h: 36, scrolltrack_always: false, maintain_scrolling_at_max_y: true, use_auto_scroll: false, show_arrows: true }); search_scroller.y = 2; search_results_holder.addChild(search_scroller); //throw the TF in the scroller TFUtil.prepTF(search_results_tf); search_results_tf.embedFonts = false; search_results_tf.x = 10; search_results_tf.width = RESULTS_WIDTH - 24; search_results_tf.addEventListener(TextEvent.LINK, closeResults, false, 0, true); search_scroller.body.addChild(search_results_tf); //make sure the results are available g = search_results_holder.graphics; g.beginFill(0xffffff); g.drawRoundRectComplex(0, 0, RESULTS_WIDTH, RESULTS_HEIGHT, 0, 0, 8, 8); search_results_holder.x = int(_w - search_results_holder.width - _border_w - 2); search_results_holder.y = int(-RESULTS_HEIGHT-10); search_results_holder.filters = StaticFilters.black2px90Degrees_DropShadowA; //load blocker, to show when transit maps are loading and you don't want to see what's behind it load_blocker.mouseEnabled = false; g = load_blocker.graphics; g.beginFill(0xffffff); g.drawRect(0, 0, MAP_W, MAP_H); const spinner:DisplayObject = new AssetManager.instance.assets.spinner(); spinner.x = int(MAP_W/2 - spinner.width/2); spinner.y = int(MAP_H/2 - spinner.height/2); load_blocker.addChild(spinner); } private function buildBase():void { TSFrontController.instance.registerMoveListener(this); //hub you are here image buildYouView(you_view_holder); //transit you are here image var transit_star:DisplayObject = new AssetManager.instance.assets.subway_map_star(); if(transit_star){ SpriteUtil.setRegistrationPoint(transit_star); transit_you_view_holder.addChild(transit_star); } is_built = true; } public function loadWorldMapIfNeeded(swf_url:String):void { if (!swf_url || swf_url == world_map_url) { //nothing has changed, but make sure the regions are properly setup worldMapSetRegions(); return; } world_map_url = swf_url; if (world_map_mc && world_map_mc.parent) world_map_mc.parent.removeChild(world_map_mc); world_map_mc = null; var sl:SmartLoader = new SmartLoader(world_map_url); sl.complete_sig.add(doneLoadingWorldMap); sl.load(new URLRequest(world_map_url)); } private function doneLoadingWorldMap(sl:SmartLoader):void { world_map_mc = sl.content as MovieClip; if (!world_map_mc) return; //world_map_mc.setConsole(Console); world_map_mc.addClickCallback(worldMapClickHandler); world_map_mc.addHoverCallback(worldMapHoverHandler); world_map_mc.visible = false; worldMapSetRegions(); all_maps_container.addChild(world_map_mc); } private function worldMapSetRegions():void { if (!world_map_mc) { //try again real fast StageBeacon.waitForNextFrame(worldMapSetRegions); return; } try { //tell the world map which hubs are allowed to be clicked const allowed_hub_ids:Array = []; var k:String; var location:Location; for(k in model.worldModel.search_locations){ //if this ISN'T a location, then it's a hub ID (could also check if it's a number, but that's not future proof) location = model.worldModel.getLocationByTsid(k); if(!location){ allowed_hub_ids.push(k); } } world_map_mc.buildRegions(allowed_hub_ids); //build a you star for the world map buildYouView(you_view_world_holder); you_view_world_holder.mouseEnabled = false; //let's see if our current location has a region showYouOnWorld(); } catch(e:Error){ CONFIG::debugging { Console.warn('World Map shit the bed, probably the old SWF', e.message); } } } private function worldMapClickHandler(target:DisplayObject):void { if (world_map_clicked_region) return; if (!target) return; var region_str:String = target.name; /* CONFIG::debugging { Console.info('region_str:'+region_str); }*/ if (!region_str) return; var region_id:String = region_str.replace('region_', ''); /*CONFIG::debugging { Console.info('region_id:'+region_id); }*/ world_map_clicked_region = target; goToHubFromClick(region_id); SoundMaster.instance.playSound('CLICK_SUCCESS'); } private function worldMapHoverHandler(target:MovieClip, is_hover:Boolean):void { if (!target) return; //if the star is on this region, we need to toggle it's visibility if(target.contains(you_view_world_holder)){ //tween the time on hover since the over state doesn't animate right away TSTweener.removeTweens(you_view_world_holder); TSTweener.addTween(you_view_world_holder, {alpha:is_hover ? 0 : 1, time:is_hover ? .2 : 0, transition:'linear'}); } } private function showYouOnWorld():void { if(!world_map_mc) return; //reset you_view_world_holder.alpha = 1; const region_mc:MovieClip = world_map_mc.getRegion(model.worldModel.location.hub_id); if(region_mc){ //throw the star on there region_mc.gotoAndStop(1); region_rect = region_mc.getBounds(region_mc); you_view_world_holder.x = int(region_rect.x + region_rect.width/2); you_view_world_holder.y = int(region_rect.y + region_rect.height/2); region_mc.addChild(you_view_world_holder); } else if(you_view_world_holder.parent){ //not on a region anymore, toss'r you_view_world_holder.parent.removeChild(you_view_world_holder); } } /* override public function init():void { super.init(); TSFrontController.instance.registerMoveLister(this); //hub you are here image buildYouView(you_view_holder); //transit you are here image var transit_star:DisplayObject = new AssetManager.instance.assets.subway_map_star(); if(transit_star){ SpriteUtil.setRegistrationPoint(transit_star); transit_you_view_holder.addChild(transit_star); } } */ public function buildYouView(sp:Sprite):Sprite { if(!sp) sp = new Sprite(); var g:Graphics = sp.graphics; g.beginFill(STAR_COLOR); g.lineStyle(0,0,0); DrawUtil.drawStar(10, g); g.endFill(); sp.filters = StaticFilters.white3px_GlowA; return sp; } public function onLocationPathStarted():void { if (displayed_map_hub) displayed_map_hub.updateLocPath(); } public function onLocationPathEnded():void { if (displayed_map_hub) displayed_map_hub.updateLocPath(); } // IMoveListener funcs // ----------------------------------------------------------------- public function moveLocationHasChanged():void { } public function moveLocationAssetsAreReady():void { } public function moveMoveStarted():void { } public function moveMoveEnded():void { const hub:Hub = model.worldModel.getHubByTsid(model.worldModel.location.hub_id); if(hub && hub.map_data){ loadWorldMapIfNeeded(hub.map_data.world_map); } else { //this is a hub map and we don't have a hub with data?! Bail out!! if(parent) end(false); return; } //update the hub map if (parent) { if (current_location_id != model.worldModel.location.tsid) { updateMapHub(model.worldModel.location.hub_id); } //place our star where it needs to go showYouOnWorld(); } } // ----------------------------------------------------------------- // END IMoveListener funcs public function goToHubFromClick(hub_id:String, loc_tsid:String='', transition_direction:String='', flash_loc:Boolean=false):void { if (!model.worldModel.location.show_hubmap) { SoundMaster.instance.playSound('CLICK_FAILURE'); TSFrontController.instance.growl('The map is not available in this location'); return; } //because mart has a link to a place in hell and you must be dead to see it //I'm putting a special case here if(hub_id == Hub.HELL_TSID){ const pc:PC = model.worldModel.pc; if(!pc.is_dead){ var msg_txt:String = 'You can only see the map of Naraka when you\\'re dead.'; model.activityModel.activity_message = Activity.createFromCurrentPlayer(msg_txt); TSFrontController.instance.growl(msg_txt); if(transitioning) end(true); SoundMaster.instance.playSound('CLICK_FAILURE'); return; } } //if we are already loading a map (or animating one out of the way), bail out if((is_map_loading || hub_click_hub_id == hub_id) && !world_map_clicked_region){ SoundMaster.instance.playSound('CLICK_FAILURE'); return; } this.transition_direction = transition_direction; hub_click_hub_id = hub_id; hub_click_location_id = loc_tsid; hub_click_flash_loc = flash_loc; //close the search thing closeResults(); //disable the go to my location button recenter_bt.disabled = true; //make sure we don't see the transit map cancel_transit_display = true; hideTransitMap(); if (!world_map_clicked_region) { simpleHideWorldMap(); all_maps_container.addChildAt(load_blocker, 0); } is_map_loading = true; TSFrontController.instance.genericSend(new NetOutgoingMapGetVO(hub_id, loc_tsid), onMapData, onMapData); } public function changeSignpostVisibility(signpost:SignPost):void { var map_hub:MapHub = map_hubsD[current_hub_id]; if (map_hub) map_hub.changeSignpostVisibility(signpost); } private function tfLinkHandler(e:TextEvent):void { var which:String = e.text; switch(which){ case 'geo': CONFIG::god { navigateToURL(new URLRequest(model.flashVarModel.root_url+'god/world_hub_map.php?id='+current_hub_id), URLUtil.getTarget('loc')); } } } override public function end(release:Boolean):void { if (release && !transitioning) { transitioning = true; var self:HubMapDialog = this; var pt:Point = new Point(model.layoutModel.loc_vp_w-120, 50); pt.x += model.layoutModel.gutter_w; pt.y += model.layoutModel.header_h; //stop listening to move changes TransitManager.instance.removeEventListener(TSEvent.CHANGED, onTransitStatus); //play a sound if(parent) SoundMaster.instance.playSound('CLOSE_HUB_MAP'); TSTweener.removeTweens(self); TSTweener.addTween(self, {y:pt.y, x:pt.x, scaleX:.02, scaleY:.02, time:.3, transition:'easeOutCubic', onComplete:function():void{ self.end(true); self.scaleX = self.scaleY = 1; self.transitioning = false; if (displayed_map_hub) { displayed_map_hub.visible = false; displayed_map_hub = null; } if (displayed_map_transit) { displayed_map_transit.visible = false; displayed_map_transit = null; } //reset some stuff if(world_map_mc) world_map_mc.visible = false; showing_world_map = false; showing_transit_map = false; //close the search thing closeResults(); //clean out the holder SpriteUtil.clean(all_maps_container); //maybe open the chat map if(_open_map_chat_when_closed){ RightSideManager.instance.right_view.setChatMapTab(MapChatArea.TAB_MAP); _open_map_chat_when_closed = false; } }}); } else { super.end(release); //close the search thing closeResults(); } } private function closeResults():void { if(location_search){ location_search.show(); location_search.blurInput(); } } public function onEnterFrame(ms_elapsed:int):void { updateYou(); } private function updateYou():void { if (!parent) return; if (!is_built) buildBase(); if (!you_view_holder) return; if (!current_street) return; //place it where it needs to go placeYouMarker(you_view_holder); //update the path on the street if(model.stateModel.current_path){ const map_hub:MapHub = map_hubsD[current_hub_id]; if(map_hub) map_hub.updateLocPath(); } } public function placeYouMarker(you_holder:Sprite):void { use namespace client; const loc:Location = model.worldModel.location; if (loc.mapInfo && loc.mapInfo.showStreet && loc.mapInfo.showStreet != loc.tsid) { // we are in a street not represented on the map you_holder.y = -14; you_holder.x = Math.round(loc.mapInfo.showPos*current_street.scaled_distance) - (current_street.scaled_distance/2); } else { you_holder.y = -6; //check for vertical streets if(current_street.rotation >= 90 - STREET_ROTATION_BUFFER && current_street.rotation <= 90 + STREET_ROTATION_BUFFER && loc.h > loc.w){ //probably a vertical street //we want the bottom of the level to be the right most X you_holder.x = Math.round(((model.worldModel.pc.y-loc.b)/loc.h)*current_street.scaled_distance) + (current_street.scaled_distance/2); } else { you_holder.x = Math.round(((model.worldModel.pc.x-loc.l)/loc.w)*current_street.scaled_distance) - (current_street.scaled_distance/2); } } //update the path on the street if(model.stateModel.current_path){ model.stateModel.current_path.you_pt.x = you_holder.x; model.stateModel.current_path.you_pt.y = you_holder.y; } } public function updateMapHubIfWeClickedOnIt(hub_id:String, flash_loc:Boolean=false):void { if (hub_click_hub_id == hub_id) { updateMapHub(hub_id, flash_loc) } } public function updateMapIfShowingHub(hub_id:String):void { if (current_hub_id == hub_id) { updateMapHub(hub_id) } } private function changeTitle(str:String):void { loc_name_tf.htmlText = '

'+str+'

'; loc_name_tf.x = int((_w-loc_name_tf.width)/2); loc_name_tf.y = 10 + int((header_h-10-loc_name_tf.height)/2); } private function updateMapHub(hub_id:String, flash_loc:Boolean = false):void { //Console.warn('updateMap '+hub_id); current_hub_id = hub_id; current_location_id = model.worldModel.location.tsid; if (displayed_map_hub) { TSTweener.addTween(displayed_map_hub, {alpha:0, time:.5, delay:0, transition:'linear'}); } var map_hub:MapHub = map_hubsD[current_hub_id]; if (!map_hub) { map_hub = map_hubsD[current_hub_id] = new MapHub(current_hub_id, you_view_holder); map_hub.addEventListener(TSEvent.COMPLETE, newMapHubReady); } map_hub.visible = false; if(showing_transit_map){ all_maps_container.addChildAt(map_hub, displayed_map_transit ? Math.max(0, all_maps_container.getChildIndex(displayed_map_transit)-1) : 0); } else { all_maps_container.addChild(map_hub); } map_hub.build(hub_click_location_id, flash_loc); // will fire TSEvent.COMPLETE when done loading, and call newMapHubReady } private function doneTransitionFromWorldToHub():void { if (showing_world_map) { simpleHideWorldMap(); showing_world_map = false; } if (displayed_map_hub) displayed_map_hub.unHideAllButGraphics(); } private function newMapHubReady(e:TSEvent):void { // ignore this if not on stage http://bugs.tinyspeck.com/5945 if (!parent) return; var map_hub:MapHub = map_hubsD[current_hub_id]; map_hub.visible = true; var animation_delay:Number = .3; //how much time to wait before animating search street/you if (current_hub_id){ var hub:Hub = model.worldModel.getHubByTsid(current_hub_id); if(hub && !showing_transit_map){ changeTitle(hub.label); } } //if we are showing the transit map, and there is a region, kill the region since you won't see the animation anyways if(showing_transit_map) world_map_clicked_region = null; if(load_blocker.parent) load_blocker.parent.removeChild(load_blocker); if (world_map_clicked_region) { // this is from a click in the worldmap //Console.warn(1); //Console.info(getQualifiedClassName(e.data)+' '+e.data.name); var pt:Point = world_map_clicked_region.localToGlobal(new Point()); // ideally we would measure these better, but that involves digging down the display list of world_map_clicked_region const mw:int = 135; const mh:int = 85; pt.x-= 10; pt = map_hub.parent.globalToLocal(pt); map_hub.x = pt.x; map_hub.y = pt.y; map_hub.width = mw; map_hub.height = mh; map_hub.alpha = 0; map_hub.hideAllButGraphics(); TSTweener.addTween(map_hub, {alpha:1, time:.3, delay:0, transition:'linear'}); TSTweener.addTween(map_hub, {x:0, y:0, time:.5, delay:.3, transition:'easeOutCubic'}); TSTweener.addTween(map_hub, {width:MAP_ACTUAL_W, height:MAP_ACTUAL_H, time:.5, delay:.3, transition:'easeOutCubic', onComplete:doneTransitionFromWorldToHub}); world_map_clicked_region = null; animation_delay += .8; //time + delay } else { // this is not from a world map click //Console.warn(getQualifiedClassName(e.data)+' '+e.data.name); //Console.error(2); if (displayed_map_hub && transition_direction) { map_hub.alpha = 1; switch (transition_direction) { case 'right': map_hub.x = MAP_W; map_hub.y = 0; break; case 'bottom': map_hub.x = 0; map_hub.y = MAP_H; break; case 'left': map_hub.x = -MAP_W; map_hub.y = 0; break; case 'top': map_hub.x = 0; map_hub.y = -MAP_H; break; default: CONFIG::debugging { Console.error('wtf'); } break; } TSTweener.addTween(displayed_map_hub, {time:.2, delay:0, transition:'linear'}); TSTweener.addTween(map_hub, {x:0, y:0, time:.3, delay:.3, transition:'linear'}); animation_delay += .6; //time + delay } else { map_hub.x = 0; map_hub.y = 0; TSTweener.addTween(map_hub, {alpha:1, time:.3, delay:0, transition:'linear'}); } showing_world_map = false; if(world_map_mc) world_map_mc.visible = false; } //if we need to flash a street, take care of that here if(!hub_click_hub_id || (map_hub.name == hub_click_hub_id)){ map_hub.animateSearchOrYou(animation_delay); } displayed_map_hub = map_hub; transition_direction = ''; //refresh the nav refreshNavButtons(); } private function updateMapTransit(transit_tsid:String, animate:Boolean = false):void { var transit:Transit = model.worldModel.getTransitByTsid(transit_tsid); var transit_line:TransitLine; changeTitle(transit.name); showing_transit_map = true; current_transit_tsid = transit_tsid; var map_transit:MapTransit = map_transitsD[current_transit_tsid]; if (!map_transit) { map_transit = map_transitsD[current_transit_tsid] = new MapTransit(current_transit_tsid, transit_you_view_holder); map_transit.addEventListener(TSEvent.COMPLETE, newMapTransitRdy); } //are we going to animate this? animate_transit_map = animate; map_transit.visible = false; all_maps_container.addChild(map_transit); //if(animate_transit_map) all_maps_container.addChild(load_blocker); //let's see if we are already riding a line, and show that line by default if(TransitManager.instance.current_location_tsid){ transit_line = transit.getLineByCurrentAndNext(TransitManager.instance.current_location_tsid, TransitManager.instance.next_location_tsid); } map_transit.build(transit_line); // will fire TSEvent.COMPLETE when done loading, and call newMapTransitRdy } private function newMapTransitRdy(event:TSEvent):void { if(cancel_transit_display){ cancel_transit_display = false; return; } var map_transit:MapTransit = map_transitsD[current_transit_tsid]; map_transit.visible = true; //remove the load blocker if(all_maps_container.contains(load_blocker)) all_maps_container.removeChild(load_blocker); //if this is a new map, animate it in if(displayed_map_transit != map_transit){ displayed_map_transit = map_transit; displayed_map_transit.y = -MAP_H; } //animate this bad boy if(displayed_map_transit.y < 0 && animate_transit_map){ TSTweener.removeTweens(displayed_map_transit); TSTweener.addTween(displayed_map_transit, {y:0, time:.5, transition:'easeOutQuad', onComplete:function():void { //if we have a hub map if(displayed_map_hub && displayed_map_hub.parent && !showing_world_map){ all_maps_container.setChildIndex(displayed_map_hub, Math.max(0, all_maps_container.getChildIndex(displayed_map_transit)-1)); displayed_map_hub.visible = true; } //simpleHideWorldMap(); } }); } else { displayed_map_transit.y = 0; } //make sure we have the right title again! if(current_transit_tsid){ var transit:Transit = model.worldModel.getTransitByTsid(current_transit_tsid); if(transit){ changeTitle(transit.name); } } } override public function start():void { use namespace client; if (!model.worldModel.location.show_hubmap) { return; } const animate_in:Boolean = parent == null; if (!canStart(false)) return; if(!is_built) buildBase(); //model.stateModel.loc_pathA[0] = model.worldModel.location.tsid; const hub:Hub = model.worldModel.getHubByTsid(model.worldModel.location.hub_id); if (!hub) { model.activityModel.growl_message = 'there is no hub for the current location!' end(true); return; } if (!hub.map_data){ CONFIG::debugging { Console.warn('there is no map_data for this hub!!!'); } end(true); return; } loadWorldMapIfNeeded(hub.map_data.world_map); buildWorldMapButtons(); buildTransitButtons(); //reset the current transit ID current_transit_tsid = null; showing_transit_map = false; //reset the old hub ID stuff hub_click_hub_id = null; hub_click_location_id = null; hub_click_flash_loc = false; //is our current location on a transit map?! var transit_tsid:String = model.worldModel.getTransitTsidByLocationTsid(model.worldModel.location.tsid); //no? how about the parent street if(!transit_tsid && model.worldModel.location.mapInfo && model.worldModel.location.mapInfo.showStreet){ transit_tsid = model.worldModel.getTransitTsidByLocationTsid(model.worldModel.location.mapInfo.showStreet); } //maybe we are already on the transit line! if(!transit_tsid){ transit_tsid = TransitManager.instance.current_transit_tsid; } //if we are on the transit, update the map based on where we are, otherwise go normal if(TransitManager.instance.current_status){ showing_transit_map = true; current_transit_tsid = TransitManager.instance.current_transit_tsid; onTransitStatus(); } //build out the transit map if(transit_tsid && !start_with_world_map){ updateMapTransit(transit_tsid); } //show the hub map if we are not on the transit system if(!TransitManager.instance.current_status && !model.worldModel.location.is_pol && !start_with_world_map){ updateMapHub(hub.tsid); } //if we are in POL land, open the world map if(!model.worldModel.location.no_world_map && (model.worldModel.location.is_pol || start_with_world_map)){ if(!showing_world_map) onWorldMapBtClick(); recenter_bt.disabled = !start_with_world_map || model.worldModel.location.is_pol; } refreshNavButtons(); //listen for transit updates TransitManager.instance.addEventListener(TSEvent.CHANGED, onTransitStatus, false, 0, true); super.start(); tweenOpen(animate_in); //play a sound if(parent && animate_in) SoundMaster.instance.playSound('OPEN_HUB_MAP'); } public function startWithTransitTsid(tsid:String):void { var transit:Transit = model.worldModel.getTransitByTsid(tsid); if(transit){ start(); if(parent) updateMapTransit(transit.tsid); } else { CONFIG::debugging { Console.warn('Could not find transit system with tsid: '+tsid); } end(true); } } public function startWithWorldMap():void { start_with_world_map = true; start(); start_with_world_map = false; } public function refreshNavButtons():void { const loc:Location = model.worldModel.location; //are we allowed to see the buttons? if(loc.no_world_map){ world_map_in_bt.visible = false; world_map_out_bt.visible = false; } else if(world_map_mc && world_map_mc.visible){ world_map_in_bt.visible = false; world_map_out_bt.visible = true; } else { world_map_in_bt.visible = true; world_map_out_bt.visible = false; } //no hubs in pols! //world_map_in_bt.disabled = loc.is_pol; world_map_out_bt.disabled = loc.is_pol; transit_bt.visible = !loc.no_world_map; // no map search on Gentle Island const hub:Hub = model.worldModel.getHubByTsid(loc.hub_id); location_search.visible = (hub.label != 'Gentle Island'); } public function showError(txt:String):void { if(!parent) return; //allows the dialog to show an error toast if(!toast){ toast = new Toast(_w - _base_padd*2); toast.x = _base_padd; toast.y = _h - _border_w; } toast.show(txt, 5); addChild(toast); } private function buildWorldMapButtons():void { if (world_map_in_bt) { return; } world_map_in_bt = new Button({ name: 'world_map_in', size: Button.SIZE_TINY, type: Button.TYPE_MINOR, graphic: new AssetManager.instance.assets.world_map_zoomin_link(), graphic_disabled: new AssetManager.instance.assets.world_map_zoomin_disabled(), graphic_hover: new AssetManager.instance.assets.world_map_zoomin_hover(), graphic_padd_w: 7, graphic_padd_t: 5, x: recenter_bt.x + recenter_bt.width + TRANSIT_PADD, y: _base_padd+10, w: 41, h: 27, tip: { txt: 'World Map', pointer: WindowBorder.POINTER_BOTTOM_CENTER } }); world_map_in_bt.addEventListener(TSEvent.CHANGED, onWorldMapBtClick, false, 0, true); world_map_in_bt.visible = false; addChild(world_map_in_bt); world_map_out_bt = new Button({ name: 'world_map_out', size: Button.SIZE_TINY, type: Button.TYPE_MINOR, graphic: new AssetManager.instance.assets.world_map_link(), graphic_disabled: new AssetManager.instance.assets.world_map_disabled(), graphic_hover: new AssetManager.instance.assets.world_map_hover(), graphic_padd_w: 7, graphic_padd_t: 5, x: recenter_bt.x + recenter_bt.width + TRANSIT_PADD, y: _base_padd+10, w: 41, h: 27, tip: { txt: 'World Map', pointer: WindowBorder.POINTER_BOTTOM_CENTER } }); world_map_out_bt.addEventListener(TSEvent.CHANGED, onWorldMapBtClick, false, 0, true); addChild(world_map_out_bt); //make sure the next button is in the right place next_transit_bt_x = world_map_out_bt.x + world_map_out_bt.width + TRANSIT_PADD; } private function buildTransitButtons():void { var i:int; var transit:Transit; for(i; i < model.worldModel.transits.length; i++){ transit = model.worldModel.transits[int(i)]; //do we have the button already? if(!getChildByName(transit.tsid+'_bt')){ transit_bt = new Button({ name: transit.tsid+'_bt', value: transit.tsid, size: Button.SIZE_TINY, type: Button.TYPE_MINOR, graphic: new AssetManager.instance.assets['transit_'+transit.tsid](), graphic_hover: new AssetManager.instance.assets['transit_'+transit.tsid+'_hover'](), graphic_padd_w: 11, x: next_transit_bt_x, y: recenter_bt.y, w: 36, h: 27, tip: { txt:transit.name, pointer:WindowBorder.POINTER_BOTTOM_CENTER } }); transit_bt.addEventListener(TSEvent.CHANGED, onTransitButtonClick, false, 0, true); addChild(transit_bt); next_transit_bt_x += transit_bt.width + TRANSIT_PADD; } } } private function onTransitButtonClick(event:TSEvent=null):void { if(transit_bt.disabled) return; //if we are already looking at this map, go ahead and hide it if (displayed_map_transit && displayed_map_transit.name == transit_bt.value && displayed_map_transit.visible){ TSTweener.removeTweens(displayed_map_transit); TSTweener.addTween(displayed_map_transit, {y:-MAP_H, time:.5, transition:'easeInQuad', onComplete:hideTransitMap}); showing_transit_map = false; if(!current_hub_id || model.worldModel.location.is_pol){ //toggle the buttons so it doesn't bung up the loading if someone clicks it showing_world_map = true; if(world_map_mc) { world_map_mc.visible = true; if(!world_map_mc.parent) all_maps_container.addChildAt(world_map_mc,0); if(displayed_map_hub && displayed_map_hub.parent) displayed_map_hub.parent.removeChild(displayed_map_hub); } } } else { cancel_transit_display = false; //showing_world_map = false; updateMapTransit(transit_bt.value, true); } //update the nav buttons refreshNavButtons(); } private function onTransitStatus(event:TSEvent = null):void { //looks like we have the map open and we are going for a little ride! if(current_transit_tsid){ var transit:Transit = model.worldModel.getTransitByTsid(current_transit_tsid); if(!transit){ CONFIG::debugging { Console.warn('No transit with TSID: '+current_transit_tsid); } return; } var transit_status:TransitStatus = TransitManager.instance.current_status; var transit_line:TransitLine = transit.getLineByCurrentAndNext(transit_status.current_tsid, transit_status.next_tsid); var loc:Location; //move the star to where it needs to go if(transit_line){ if(displayed_map_transit) displayed_map_transit.setPlayerLocation(transit_line, transit_status.current_tsid); if(!transit_status.is_moving || !displayed_map_transit){ loc = model.worldModel.getLocationByTsid(transit_line.getLocationByTsid(transit_status.current_tsid).station_tsid); if(loc){ hub_click_hub_id = loc.hub_id; hub_click_location_id = transit_line.getLocationByTsid(transit_status.current_tsid).station_tsid; hub_click_flash_loc = true; //load the proper hub map when we stop if(hub_click_hub_id){ //if we are showing the world map, then get the hub region so it can animate in if(world_map_mc && world_map_mc.visible){ world_map_clicked_region = world_map_mc.getRegion(hub_click_hub_id); } //fetch! is_map_loading = true; TSFrontController.instance.genericSend(new NetOutgoingMapGetVO(hub_click_hub_id), onMapData, onMapData); } } } } } } private function onWorldMapBtClick(event:TSEvent = null):void { if (!world_map_mc) { //try again real fast StageBeacon.waitForNextFrame(onWorldMapBtClick, event); return; } //if the button is disabled, don't do anything const bt:Button = event ? event.data as Button : null; if(bt) SoundMaster.instance.playSound(!bt.disabled ? 'CLICK_SUCCESS' : 'CLICK_FAILURE'); if(bt && bt.disabled) return; if (displayed_map_transit && displayed_map_transit.visible && showing_transit_map) { onTransitButtonClick(); } var region_mc:MovieClip; if(current_hub_id){ region_mc = world_map_mc.getRegion(current_hub_id); } if (world_map_mc.visible) { // then hide world map! if (region_mc) { // if there is a region for this hub, act like we clicked on the region on the map worldMapClickHandler(region_mc); } else if (displayed_map_transit && displayed_map_transit.visible){ //no region? maybe we are riding the subway or some other form of transit onTransitButtonClick(); } else { simpleHideWorldMap(); } } else { // then show world map! // some hubs do not have regions in the map, like uralia caverns stuff, I think, so check first if (region_mc && displayed_map_hub) { all_maps_container.addChild(world_map_mc); all_maps_container.addChild(displayed_map_hub); var pt:Point = region_mc.localToGlobal(new Point()); pt = displayed_map_hub.parent.globalToLocal(pt); displayed_map_hub.alpha = 1; displayed_map_hub.hideAllButGraphics(); // scale the displayed_map_hub down to the region TSTweener.addTween(displayed_map_hub, {alpha:0, time:.3, delay:.5, transition:'linear', onComplete:doneTransitionFromHubToWorld}); TSTweener.addTween(displayed_map_hub, {x:pt.x+30, y:pt.y+20, time:.6, delay:0, transition:'easeOutCubic'}); TSTweener.addTween(displayed_map_hub, {width:10, height:10, time:.6, delay:0, transition:'easeOutCubic'}); world_map_clicked_region = null; } else { // just show it all_maps_container.addChild(world_map_mc); } changeTitle('World Map'); showing_world_map = true; world_map_mc.visible = true; current_hub_id = model.worldModel.location.hub_id; } //toggle the buttons we can see refreshNavButtons(); } private function onMapData(nrm:NetResponseMessageVO):void { recenter_bt.disabled = model.worldModel.location.is_pol; is_map_loading = false; if (nrm.success) { if (nrm.payload.mapData) { //if we've got an ""all"" hash make sure to update the world if(nrm.payload.mapData.all){ Hub.updateFromMapDataAll(nrm.payload.mapData); } //if we've got a ""transit"" hash make sure to update the world if(nrm.payload.mapData.transit){ Transit.updateFromMapDataTransit(nrm.payload.mapData); } var hub:Hub = model.worldModel.hubs[NetOutgoingMapGetVO(nrm.request).hub_id]; if (!hub) { CONFIG::debugging { Console.error('IMPOSSIBLE!'); } return; } //add/update the map data if(!hub.map_data){ hub.map_data = MapData.fromAnonymous(nrm.payload.mapData); } else { hub.map_data = MapData.updateFromAnonymous(nrm.payload.mapData, hub.map_data); } updateMapHubIfWeClickedOnIt(hub.tsid, hub_click_flash_loc); loadWorldMapIfNeeded(hub.map_data.world_map); } else { SoundMaster.instance.playSound('CLICK_FAILURE'); CONFIG::debugging { Console.error('nrm.payload.mapData missing') } } } else { SoundMaster.instance.playSound('CLICK_FAILURE'); ; // satisfy compiler CONFIG::debugging { Console.error(nrm) } } } private function simpleHideWorldMap():void { if (!world_map_mc) return; world_map_mc.visible = false; showing_world_map = false; const hub_id:String = displayed_map_hub ? displayed_map_hub.name : current_hub_id; const hub:Hub = model.worldModel.getHubByTsid(hub_id); if(hub && !showing_transit_map){ changeTitle(hub.label); if(displayed_map_hub){ if(displayed_map_hub != map_hubsD[hub_id]){ //let's load it back up updateMapIfShowingHub(hub_id); } else if(!displayed_map_hub.visible){ displayed_map_hub.visible = true; } } } refreshNavButtons(); } private function doneTransitionFromHubToWorld():void { all_maps_container.addChild(world_map_mc); if (displayed_map_hub) { displayed_map_hub.x = 0; displayed_map_hub.y = 0; displayed_map_hub.width = MAP_ACTUAL_W; displayed_map_hub.height = MAP_ACTUAL_H; displayed_map_hub.alpha = 1; displayed_map_hub.unHideAllButGraphics(); displayed_map_hub.visible = false; } } private function onRecenterClick(event:TSEvent):void { SoundMaster.instance.playSound(!recenter_bt.disabled ? 'CLICK_SUCCESS' : 'CLICK_FAILURE'); if (recenter_bt.disabled) return; //reset any search flashing or search we may have done hub_click_hub_id = null; hub_click_location_id = null; hub_click_flash_loc = false; //hide the transit map if it's showing if(displayed_map_transit && displayed_map_transit.visible){ TSTweener.removeTweens(displayed_map_transit); TSTweener.addTween(displayed_map_transit, {y:-MAP_H, time:.5, transition:'easeInQuad', onComplete:hideTransitMap}); showing_transit_map = false; //return; } var region_mc:MovieClip; var loc:Location; //if we are riding the transit system, make sure the hub id is the right one if(TransitManager.instance.current_status){ var transit:Transit = model.worldModel.getTransitByTsid(current_transit_tsid); var transit_status:TransitStatus = TransitManager.instance.current_status; if(transit){ var transit_line:TransitLine = transit.getLineByCurrentAndNext(transit_status.current_tsid, transit_status.next_tsid); loc = model.worldModel.getLocationByTsid(transit_line.getLocationByTsid(transit_status.current_tsid).station_tsid); if(loc) region_mc = world_map_mc.getRegion(loc.hub_id); } } //set the location to where we are RIGHT NOW if(!loc) loc = model.worldModel.location; //if we are showing the world map, do pretty things if (showing_world_map) { region_mc = world_map_mc.getRegion(loc.hub_id); if (region_mc) { // if there is a region for this hub, act like we clicked on the region on the map worldMapClickHandler(region_mc) return; } } //otherwise go back to the hub we are at if (!displayed_map_hub || model.worldModel.location.hub_id != displayed_map_hub.name) { goToHubFromClick(loc.hub_id, loc.tsid); } } private function hideTransitMap():void { if(displayed_map_transit) displayed_map_transit.visible = false; showing_transit_map = false; if (showing_world_map) { changeTitle('World Map'); } else { var hub:Hub; //make sure to put back the title if(displayed_map_hub){ hub = model.worldModel.getHubByTsid(displayed_map_hub.name); } else if(current_hub_id){ hub = model.worldModel.getHubByTsid(current_hub_id); } if(hub){ changeTitle(hub.label); } } } private function tweenOpen(animate:Boolean = true):void { var self:HubMapDialog = this; TSTweener.removeTweens(self); if(animate){ transitioning = true; scaleX = scaleY = .02; x = model.layoutModel.loc_vp_w - 120 + model.layoutModel.gutter_w; y = model.layoutModel.header_h + 50; TSTweener.addTween(self, {y:dest_y, x:dest_x, scaleX:1, scaleY:1, time:.3, transition:'easeInCubic', onComplete:function():void{ self.transitioning = false; self._place(); }}); } else { scaleX = scaleY = 1; self.transitioning = false; self._place(); } } public function set open_map_chat_when_closed(value:Boolean):void { _open_map_chat_when_closed = value; } } } ",12542,True,2561.460053460984,median "/** * BigInteger * * An ActionScript 3 implementation of BigInteger (light version) * Copyright (c) 2007 Henri Torgemane * * Derived from: * The jsbn library, Copyright (c) 2003-2005 Tom Wu * * See LICENSE.txt for full license information. */ package hurlant.math { import hurlant.crypto.prng.Random; import hurlant.util.Hex; import hurlant.util.Memory; import flash.utils.ByteArray; use namespace bi_internal; public class BigInteger { public static const DB:int = 30; // number of significant bits per chunk public static const DV:int = (1<0) { if (p>p)>0) { m = true; r = d.toString(36); } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { r += d.toString(36); } } } return m?r:""0""; } public function toArray(array:ByteArray):uint { const k:int = 8; const km:int = (1<<8)-1; var d:int = 0; var i:int = t; var p:int = DB-(i*DB)%k; var m:Boolean = false; var c:int = 0; if (i-->0) { if (p>p)>0) { m = true; array.writeByte(d); c++; } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { array.writeByte(d); c++; } } } return c; } /** * best-effort attempt to fit into a Number. * precision can be lost if it just can't fit. */ public function valueOf():Number { var coef:Number = 1; var value:Number = 0; for (var i:uint=0;i v, - if this < v, 0 if equal */ public function compareTo(v:BigInteger):int { var r:int = s - v.s; if (r!=0) { return r; } var i:int = t; r = i-v.t; if (r!=0) { return r; } while (--i >=0) { r=a[i]-v.a[i]; if (r != 0) return r; } return 0; } /** * returns bit length of the integer x */ bi_internal function nbits(x:int):int { var r:int = 1; var t:int; if ((t=x>>>16) != 0) { x = t; r += 16; } if ((t=x>>8) != 0) { x = t; r += 8; } if ((t=x>>4) != 0) { x = t; r += 4; } if ((t=x>>2) != 0) { x = t; r += 2; } if ((t=x>>1) != 0) { x = t; r += 1; } return r; } /** * returns the number of bits in this */ public function bitLength():int { if (t<=0) return 0; return DB*(t-1)+nbits(a[t-1]^(s&DM)); } /** * * @param v * @return this % v * */ public function mod(v:BigInteger):BigInteger { var r:BigInteger = nbi(); abs().divRemTo(v,null,r); if (s<0 && r.compareTo(ZERO)>0) { v.subTo(r,r); } return r; } /** * this^e % m, 0 <= e < 2^32 */ public function modPowInt(e:int, m:BigInteger):BigInteger { var z:IReduction; if (e<256 || m.isEven()) { z = new ClassicReduction(m); } else { z = new MontgomeryReduction(m); } return exp(e, z); } /** * copy this to r */ bi_internal function copyTo(r:BigInteger):void { for (var i:int = t-1; i>=0; --i) { r.a[i] = a[i]; } r.t = t; r.s = s; } /** * set from integer value ""value"", -DV <= value < DV */ bi_internal function fromInt(value:int):void { t = 1; s = (value<0)?-1:0; if (value>0) { a[0] = value; } else if (value<-1) { a[0] = value+DV; } else { t = 0; } } /** * set from ByteArray and length, * starting a current position * If length goes beyond the array, pad with zeroes. */ bi_internal function fromArray(value:ByteArray, length:int):void { var p:int = value.position; var i:int = p+length; var sh:int = 0; const k:int = 8; t = 0; s = 0; while (--i >= p) { var x:int = i DB) { a[t-1] |= (x&((1<<(DB-sh))-1))<>(DB-sh); } else { a[t-1] |= x<= DB) sh -= DB; } clamp(); value.position = Math.min(p+length,value.length); } /** * clamp off excess high words */ bi_internal function clamp():void { var c:int = s&DM; while (t>0 && a[t-1]==c) { --t; } } /** * r = this << n*DB */ bi_internal function dlShiftTo(n:int, r:BigInteger):void { var i:int; for (i=t-1; i>=0; --i) { r.a[i+n] = a[i]; } for (i=n-1; i>=0; --i) { r.a[i] = 0; } r.t = t+n; r.s = s; } /** * r = this >> n*DB */ bi_internal function drShiftTo(n:int, r:BigInteger):void { var i:int; for (i=n; i=0; --i) { r.a[i+ds+1] = (a[i]>>cbs)|c; c = (a[i]&bm)<=0; --i) { r.a[i] = 0; } r.a[ds] = c; r.t = t+ds+1; r.s = s; r.clamp(); } /** * r = this >> n */ bi_internal function rShiftTo(n:int, r:BigInteger):void { r.s = s; var ds:int = n/DB; if (ds >= t) { r.t = 0; return; } var bs:int = n%DB; var cbs:int = DB-bs; var bm:int = (1<>bs; var i:int; for (i=ds+1; i>bs; } if (bs>0) { r.a[t-ds-1] |= (s&bm)<>= DB; } if (v.t < t) { c -= v.s; while (i< t) { c+= a[i]; r.a[i++] = c&DM; c >>= DB; } c += s; } else { c += s; while (i < v.t) { c -= v.a[i]; r.a[i++] = c&DM; c >>= DB; } c -= v.s; } r.s = (c<0)?-1:0; if (c<-1) { r.a[i++] = DV+c; } else if (c>0) { r.a[i++] = c; } r.t = i; r.clamp(); } /** * am: Compute w_j += (x*this_i), propagates carries, * c is initial carry, returns final carry. * c < 3*dvalue, x < 2*dvalue, this_i < dvalue */ bi_internal function am(i:int,x:int,w:BigInteger,j:int,c:int,n:int):int { var xl:int = x&0x7fff; var xh:int = x>>15; while(--n >= 0) { var l:int = a[i]&0x7fff; var h:int = a[i++]>>15; var m:int = xh*l + h*xl; l = xl*l + ((m&0x7fff)<<15)+w.a[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.a[j++] = l&0x3fffffff; } return c; } /** * r = this * v, r != this,a (HAC 14.12) * ""this"" should be the larger one if appropriate */ bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void { var x:BigInteger = abs(); var y:BigInteger = v.abs(); var i:int = x.t; r.t = i+y.t; while (--i >= 0) { r.a[i] = 0; } for (i=0; i=0) r.a[i] = 0; for (i=0; i= DV) { r.a[i+x.t] -= DV; r.a[i+x.t+1] = 1; } } if (r.t>0) { r.a[r.t-1] += x.am(i, x.a[i], r, 2*i, 0, 1); } r.s = 0; r.clamp(); } /** * divide this by m, quotient and remainder to q, r (HAC 14.20) * r != q, this != m. q or r may be null. */ bi_internal function divRemTo(m:BigInteger, q:BigInteger = null, r:BigInteger = null):void { var pm:BigInteger = m.abs(); if (pm.t <= 0) return; var pt:BigInteger = abs(); if (pt.t < pm.t) { if (q!=null) q.fromInt(0); if (r!=null) copyTo(r); return; } if (r==null) r = nbi(); var y:BigInteger = nbi(); var ts:int = s; var ms:int = m.s; var nsh:int = DB-nbits(pm.a[pm.t-1]); // normalize modulus if (nsh>0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys:int = y.t; var y0:int = y.a[ys-1]; if (y0==0) return; var yt:Number = y0*(1<1)?y.a[ys-2]>>F2:0); var d1:Number = FV/yt; var d2:Number = (1<=0) { r.a[r.t++] = 1; r.subTo(t,r); } ONE.dlShiftTo(ys,t); t.subTo(y,y); // ""negative"" y so we can replace sub with am later. while(y.t= 0) { // Estimate quotient digit var qd:int = (r.a[--i]==y0)?DM:Number(r.a[i])*d1+(Number(r.a[i-1])+e)*d2; if ((r.a[i]+= y.am(0, qd, r, j, 0, ys))0) { r.rShiftTo(nsh, r); // Denormalize remainder } if (ts<0) { ZERO.subTo(r,r); } } /** * return ""-1/this % 2^DB""; useful for Mont. reduction * justification: * xy == 1 (mod n) * xy = 1+km * xy(2-xy) = (1+km)(1-km) * x[y(2-xy)] = 1-k^2.m^2 * x[y(2-xy)] == 1 (mod m^2) * if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 * should reduce x and y(2-xy) by m^2 at each step to keep size bounded * [XXX unit test the living shit out of this.] */ bi_internal function invDigit():int { if (t<1) return 0; var x:int = a[0]; if ((x&1)==0) return 0; var y:int = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf )*y)) &0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y)) &0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints // XXX 48 bit ints? Whaaaa? is there an implicit float conversion in here? y = (y*(2-x*y%DV))%DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?DV-y:-y; } /** * true iff this is even */ bi_internal function isEven():Boolean { return ((t>0)?(a[0]&1):s) == 0; } /** * this^e, e < 2^32, doing sqr and mul with ""r"" (HAC 14.79) */ bi_internal function exp(e:int, z:IReduction):BigInteger { if (e > 0xffffffff || e < 1) return ONE; var r:BigInteger = nbi(); var r2:BigInteger = nbi(); var g:BigInteger = z.convert(this); var i:int = nbits(e)-1; g.copyTo(r); while(--i>=0) { z.sqrTo(r, r2); if ((e&(1<0) { z.mulTo(r2,g,r); } else { var t:BigInteger = r; r = r2; r2 = t; } } return z.revert(r); } bi_internal function intAt(str:String, index:int):int { return parseInt(str.charAt(index), 36); } protected function nbi():* { return new BigInteger; } /** * return bigint initialized to value */ public static function nbv(value:int):BigInteger { var bn:BigInteger = new BigInteger; bn.fromInt(value); return bn; } // Functions above are sufficient for RSA encryption. // The stuff below is useful for decryption and key generation public static const lowprimes:Array = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; public static const lplim:int = (1<<26)/lowprimes[lowprimes.length-1]; public function clone():BigInteger { var r:BigInteger = new BigInteger; this.copyTo(r); return r; } /** * * @return value as integer * */ public function intValue():int { if (s<0) { if (t==1) { return a[0]-DV; } else if (t==0) { return -1; } } else if (t==1) { return a[0]; } else if (t==0) { return 0; } // assumes 16 < DB < 32 return ((a[1]&((1<<(32-DB))-1))<>24; } /** * * @return value as short (assumes DB>=16) * */ public function shortValue():int { return (t==0)?s:(a[0]<<16)>>16; } /** * * @param r * @return x s.t. r^x < DV * */ protected function chunkSize(r:Number):int { return Math.floor(Math.LN2*DB/Math.log(r)); } /** * * @return 0 if this ==0, 1 if this >0 * */ public function sigNum():int { if (s<0) { return -1; } else if (t<=0 || (t==1 && a[0]<=0)) { return 0; } else{ return 1; } } /** * * @param b: radix to use * @return a string representing the integer converted to the radix. * */ protected function toRadix(b:uint=10):String { if (sigNum()==0 || b<2 || b>32) return ""0""; var cs:int = chunkSize(b); var a:Number = Math.pow(b, cs); var d:BigInteger = nbv(a); var y:BigInteger = nbi(); var z:BigInteger = nbi(); var r:String = """"; divRemTo(d, y, z); while (y.sigNum()>0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } /** * * @param s a string to convert from using radix. * @param b a radix * */ protected function fromRadix(s:String, b:int = 10):void { fromInt(0); var cs:int = chunkSize(b); var d:Number = Math.pow(b, cs); var mi:Boolean = false; var j:int = 0; var w:int = 0; for (var i:int=0;i= cs) { dMultiply(d); dAddOffset(w,0); j=0; w=0; } } if (j>0) { dMultiply(Math.pow(b,j)); dAddOffset(w,0); } if (mi) { BigInteger.ZERO.subTo(this, this); } } // XXX function fromNumber not written yet. /** * * @return a byte array. * */ public function toByteArray():ByteArray { var i:int = t; var r:ByteArray = new ByteArray; r[0] = s; var p:int = DB-(i*DB)%8; var d:int; var k:int=0; if (i-->0) { if (p>p)!=(s&DM)>>p) { r[k++] = d|(s<<(DB-p)); } while (i>=0) { if(p<8) { d = (a[i]&((1<>(p+=DB-8); } else { d = (a[i]>>(p-=8))&0xff; if (p<=0) { p += DB; --i; } } if ((d&0x80)!=0) d|=-256; if (k==0 && (s&0x80)!=(d&0x80)) ++k; if (k>0 || d!=s) r[k++] = d; } } return r; } public function equals(a:BigInteger):Boolean { return compareTo(a)==0; } public function min(a:BigInteger):BigInteger { return (compareTo(a)<0)?this:a; } public function max(a:BigInteger):BigInteger { return (compareTo(a)>0)?this:a; } /** * * @param a a BigInteger to perform the operation with * @param op a Function implementing the operation * @param r a BigInteger to store the result of the operation * */ protected function bitwiseTo(a:BigInteger, op:Function, r:BigInteger):void { var i:int; var f:int; var m:int = Math.min(a.t, t); for (i=0; i>= 16; r += 16; } if ((x&0xff) == 0) { x>>= 8; r += 8; } if ((x&0xf) == 0) { x>>= 4; r += 4; } if ((x&0x3) == 0) { x>>= 2; r += 2; } if ((x&0x1) == 0) ++r; return r; } /** * * @return index of lowest 1-bit (or -1 if none) * */ public function getLowestSetBit():int { for (var i:int=0;i=t) { return s!=0; } return ((a[j]&(1<<(n%DB)))!=0); } /** * * @param n * @param op * @return this op (1<>=DB; } if (a.t < t) { c += a.s; while (i>= DB; } c += s; } else { c += s; while (i>= DB; } c += a.s; } r.s = (c<0)?-1:0; if (c>0) { r.a[i++] = c; } else if (c<-1) { r.a[i++] = DV+c; } r.t = i; r.clamp(); } /** * * @param a * @return this + a * */ public function add(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; addTo(a,r); return r; } /** * * @param a * @return this - a * */ public function subtract(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; subTo(a,r); return r; } /** * * @param a * @return this * a * */ public function multiply(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; multiplyTo(a,r); return r; } /** * * @param a * @return this / a * */ public function divide(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, r, null); return r; } public function remainder(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, null, r); return r; } /** * * @param a * @return [this/a, this%a] * */ public function divideAndRemainder(a:BigInteger):Array { var q:BigInteger = new BigInteger; var r:BigInteger = new BigInteger; divRemTo(a, q, r); return [q,r]; } /** * * this *= n, this >=0, 1 < n < DV * * @param n * */ bi_internal function dMultiply(n:int):void { a[t] = am(0, n-1, this, 0, 0, t); ++t; clamp(); } /** * * this += n << w words, this >= 0 * * @param n * @param w * */ bi_internal function dAddOffset(n:int, w:int):void { while (t<=w) { a[t++] = 0; } a[w] += n; while (a[w] >= DV) { a[w] -= DV; if (++w >= t) { a[t++] = 0; } ++a[w]; } } /** * * @param e * @return this^e * */ public function pow(e:int):BigInteger { return exp(e, new NullReduction); } /** * * @param a * @param n * @param r = lower n words of ""this * a"", a.t <= n * */ bi_internal function multiplyLowerTo(a:BigInteger, n:int, r:BigInteger):void { var i:int = Math.min(t+a.t, n); r.s = 0; // assumes a, this >= 0 r.t = i; while (i>0) { r.a[--i]=0; } var j:int; for (j=r.t-t;i 0 * */ bi_internal function multiplyUpperTo(a:BigInteger, n:int, r:BigInteger):void { --n; var i:int = r.t = t+a.t-n; r.s = 0; // assumes a,this >= 0 while (--i>=0) { r.a[i] = 0; } for (i=Math.max(n-t,0);i 1) { var g2:BigInteger = new BigInteger; z.sqrTo(g[1], g2); while (n<=km) { g[n] = new BigInteger; z.mulTo(g2, g[n-2], g[n]); n += 2; } } var j:int = e.t-1; var w:int; var is1:Boolean = true; var r2:BigInteger = new BigInteger; var t:BigInteger; i = nbits(e.a[j])-1; while (j>=0) { if (i>=k1) { w = (e.a[j]>>(i-k1))&km; } else { w = (e.a[j]&((1<<(i+1))-1))<<(k1-i); if (j>0) { w |= e.a[j-1]>>(DB+i-k1); } } n = k; while ((w&1)==0) { w >>= 1; --n; } if ((i -= n) <0) { i += DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n>1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n>0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j>=0 && (e.a[j]&(1<0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.sigNum()>0) { if ((i = x.getLowestSetBit()) >0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) >0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g>0) { y.lShiftTo(g, y); } return y; } /** * * @param n * @return this % n, n < 2^DB * */ protected function modInt(n:int):int { if (n<=0) return 0; var d:int = DV%n; var r:int = (s<0)?n-1:0; if (t>0) { if (d==0) { r = a[0]%n; } else { for (var i:int=t-1;i>=0;--i) { r = (d*r+a[i])%n; } } } return r; } /** * * @param m * @return 1/this %m (HAC 14.61) * */ public function modInverse(m:BigInteger):BigInteger { var ac:Boolean = m.isEven(); if ((isEven()&&ac) || m.sigNum()==0) { return BigInteger.ZERO; } var u:BigInteger = m.clone(); var v:BigInteger = clone(); var a:BigInteger = nbv(1); var b:BigInteger = nbv(0); var c:BigInteger = nbv(0); var d:BigInteger = nbv(1); while (u.sigNum()!=0) { while (u.isEven()) { u.rShiftTo(1,u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if (!b.isEven()) { b.subTo(m,b); } b.rShiftTo(1,b); } while (v.isEven()) { v.rShiftTo(1,v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if (!d.isEven()) { d.subTo(m,d); } d.rShiftTo(1,d); } if (u.compareTo(v)>=0) { u.subTo(v,u); if (ac) { a.subTo(c,a); } b.subTo(d,b); } else { v.subTo(u,v); if (ac) { c.subTo(a,c); } d.subTo(b,d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.sigNum()<0) { d.addTo(m,d); } else { return d; } if (d.sigNum()<0) { return d.add(m); } else { return d; } } /** * * @param t * @return primality with certainty >= 1-.5^t * */ public function isProbablePrime(t:int):Boolean { var i:int; var x:BigInteger = abs(); if (x.t == 1 && x.a[0]<=lowprimes[lowprimes.length-1]) { for (i=0;i>1; if (t>lowprimes.length) { t = lowprimes.length; } var a:BigInteger = new BigInteger; for (var i:int=0;ibits) subTo(BigInteger.ONE.shiftLeft(bits-1),this); } } } } ",12117,True,2658.6241015473943,median "class ZSAPLINK_PROGRAM definition public inheriting from ZSAPLINK final create public . public section. methods CHECKEXISTS redefinition . methods CREATEIXMLDOCFROMOBJECT redefinition . methods CREATEOBJECTFROMIXMLDOC redefinition . methods CREATESTRINGFROMOBJECT redefinition . protected section. methods DELETEOBJECT redefinition . methods GETOBJECTTYPE redefinition . private section. methods GET_SOURCE returning value(PROGSOURCE) type RSWSOURCET . methods UPDATE_WB_TREE . methods CREATE_TEXTPOOL importing !TEXTPOOLNODE type ref to IF_IXML_ELEMENT . methods DEQUEUE_ABAP raising ZCX_SAPLINK . methods GET_TEXTPOOL returning value(TEXTNODE) type ref to IF_IXML_ELEMENT . methods CREATE_DOCUMENTATION importing !DOCNODE type ref to IF_IXML_ELEMENT . methods CREATE_SOURCE importing !SOURCE type TABLE_OF_STRINGS !ATTRIBS type TRDIR . methods ENQUEUE_ABAP raising ZCX_SAPLINK . methods GET_DOCUMENTATION returning value(DOCNODE) type ref to IF_IXML_ELEMENT . methods TRANSPORT_COPY importing !AUTHOR type SYUNAME !DEVCLASS type DEVCLASS raising ZCX_SAPLINK . methods GET_DYNPRO returning value(DYNP_NODE) type ref to IF_IXML_ELEMENT . methods CREATE_DYNPRO importing !DYNP_NODE type ref to IF_IXML_ELEMENT . methods GET_PFSTATUS returning value(PFSTAT_NODE) type ref to IF_IXML_ELEMENT . methods CREATE_PFSTATUS importing !PFSTAT_NODE type ref to IF_IXML_ELEMENT . endclass. ""ZSAPLINK_PROGRAM definition *----------------------------------------------------------------------* * class ZSAPLINK_PROGRAM implementation. *----------------------------------------------------------------------* * *----------------------------------------------------------------------* class ZSAPLINK_PROGRAM implementation. method CHECKEXISTS. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ select single name from trdir into objName where NAME = objName. if sy-subrc = 0. exists = 'X'. endif. endmethod. method CREATEIXMLDOCFROMOBJECT. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data rootNode type ref to if_ixml_element. data sourceNode type ref to if_ixml_element. data textPoolNode type ref to if_ixml_element. data docNode type ref to if_ixml_element. data dynproNode type ref to if_ixml_element. data statusNode type ref to if_ixml_element. data rc type sysubrc. data progAttribs type trdir. data progSource type RSWSOURCET. data sourceString type string. data _objType type string. _objType = getObjectType( ). rootNode = xmlDoc->create_element( _objType ). sourceNode = xmlDoc->create_element( 'source' ). select single * from trdir into progAttribs where NAME = objName. if sy-subrc = 0. setAttributesFromStructure( node = rootNode structure = progAttribs ). progSource = me->get_source( ). sourceString = buildSourceString( sourceTable = progSource ). rc = sourceNode->IF_IXML_NODE~SET_VALUE( sourceString ). textPoolNode = get_textPool( ). rc = rootNOde->append_child( textPoolNode ). docNode = get_documentation( ). rc = rootNOde->append_child( docNode ). dynproNode = get_dynpro( ). rc = rootNode->append_child( dynproNode ). statusNode = get_pfstatus( ). rc = rootNode->append_child( statusNode ). rc = rootNode->append_child( sourceNode ). rc = xmldoc->append_child( rootNode ). ixmlDocument = xmlDoc. else. clear ixmlDocument. raise exception type zcx_saplink exporting textid = zcx_saplink=>not_found object = objname. endif. endmethod. method CREATEOBJECTFROMIXMLDOC. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data rootnode type ref to if_ixml_element. data progattribs type trdir. data sourcenode type ref to if_ixml_element. data textnode type ref to if_ixml_element. data docnode type ref to if_ixml_element. data dynpnode type ref to if_ixml_element. data statnode type ref to if_ixml_element. data source type string. data sourcetable type table_of_strings. data _objname(30) type c. data aobjname type trobj_name. data _objtype type string. data checkexists type flag. *if sy-uname <> 'USDWM01'. * _objType = getObjectType( ). * xmlDoc = ixmlDocument. * rootNode = xmlDoc->find_from_name( _objType ). * call method GETSTRUCTUREFROMATTRIBUTES * exporting * node = rootNode * changing * structure = progAttribs. * objName = progAttribs-NAME. * ** check existing * select single name from trdir into objName where NAME = objName. * if sy-subrc = 0. * raise exception type zcx_saplink * exporting textid = zcx_saplink=>existing. * endif. * * sourceNode = rootNode->find_from_name( 'source' ). * source = sourceNode->get_value( ). * sourceTable = BUILDTABLEFROMSTRING( source ). * insert report progAttribs-NAME from sourceTable. * * commit work. * * call function 'RS_INSERT_INTO_WORKING_AREA' * EXPORTING * object = 'REPS' * obj_name = aobjName * EXCEPTIONS * wrong_object_name = 1. * if sy-subrc <> 0. * * endif. * *else. _objtype = getobjecttype( ). xmldoc = ixmldocument. rootnode = xmldoc->find_from_name( _objtype ). call method getstructurefromattributes exporting node = rootnode changing structure = progattribs. objname = progattribs-name. * check if object exists * select single name from trdir into objName where NAME = objName. * if sy-subrc = 0 and overwrite <> 'X'. * raise exception type zcx_saplink * exporting textid = zcx_saplink=>existing. * endif. checkexists = checkexists( ). if checkexists is not initial. if overwrite is initial. raise exception type zcx_saplink exporting textid = zcx_saplink=>existing. else. * delete object for new install deleteobject( ). endif. endif. enqueue_abap( ). transport_copy( author = progattribs-cnam devclass = devclass ). sourcenode = rootnode->find_from_name( 'source' ). source = sourcenode->get_value( ). sourcetable = buildtablefromstring( source ). create_source( source = sourcetable attribs = progattribs ). textnode = rootnode->find_from_name( 'textPool' ). create_textpool( textnode ). docnode = rootnode->find_from_name( 'programDocumentation' ). create_documentation( docnode ). dynpnode = rootnode->find_from_name( 'dynpros' ). create_dynpro( dynpnode ). statnode = rootnode->find_from_name( 'pfstatus' ). create_pfstatus( statnode ). dequeue_abap( ). update_wb_tree( ). *endif. * successful install name = objname. endmethod. method CREATESTRINGFROMOBJECT. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data progSource type RSWSOURCET. progsource = me->get_source( ). string = buildsourcestring( sourcetable = progsource ). endmethod. method CREATE_DOCUMENTATION. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ DATA txtline_node TYPE REF TO if_ixml_element. DATA txtline_filter TYPE REF TO if_ixml_node_filter. DATA txtline_iterator TYPE REF TO if_ixml_node_iterator. DATA lang_node TYPE REF TO if_ixml_element. DATA lang_filter TYPE REF TO if_ixml_node_filter. DATA lang_iterator TYPE REF TO if_ixml_node_iterator. data obj_name type DOKHL-OBJECT. data prog_name type string. data language type string. data obj_langu type DOKHL-LANGU. data lv_str type string. data rc type sy-subrc. DATA lt_lines TYPE TABLE OF tline. FIELD-SYMBOLS: LIKE LINE OF lt_lines. if docnode is not bound. return. endif. prog_name = docNode->get_attribute( name = 'OBJECT' ). obj_name = prog_name. * If no prog name, then there was no program documenation, just return. if prog_name is initial. return. endif. * Get languages from XML FREE: lang_filter, lang_iterator, lang_node. lang_filter = docNode->create_filter_name( `language` ). lang_iterator = docNode->create_iterator_filtered( lang_filter ). lang_node ?= lang_iterator->get_next( ). WHILE lang_node IS NOT INITIAL. refresh lt_lines. language = lang_node->get_attribute( name = 'SPRAS' ). obj_langu = language. * Get TextLines from XML FREE: txtline_filter, txtline_iterator, txtline_node. txtline_filter = lang_node->create_filter_name( `textLine` ). txtline_iterator = lang_node->create_iterator_filtered( txtline_filter ). txtline_node ?= txtline_iterator->get_next( ). WHILE txtline_node IS NOT INITIAL. APPEND INITIAL LINE TO lt_lines ASSIGNING . me->getstructurefromattributes( EXPORTING node = txtline_node CHANGING structure = ). txtline_node ?= txtline_iterator->get_next( ). ENDWHILE. * Delete any documentation that may currently exist. CALL FUNCTION 'DOCU_DEL' EXPORTING id = 'RE' ""<-- Report/program documentation langu = obj_langu object = obj_name typ = 'E' EXCEPTIONS ret_code = 1 OTHERS = 2. * Now update with new documentation text CALL FUNCTION 'DOCU_UPD' EXPORTING id = 'RE' langu = obj_langu object = obj_name typ = 'E' TABLES line = lt_lines EXCEPTIONS ret_code = 1 OTHERS = 2. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_saplink EXPORTING textid = zcx_saplink=>error_message msg = `Program Documentation object import failed`. ENDIF. lang_node ?= lang_iterator->get_next( ). ENDWHILE. endmethod. method CREATE_DYNPRO. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ types: begin of tdyn_head_temp. include type d020s. types: dtext type d020t-dtxt. types: end of tdyn_head_temp. data: idyn_fldl type table of d021s, idyn_flow type table of d022s, idyn_mcod type table of d023s. data: xdyn_head type d020s, xdyn_fldl type d021s, xdyn_flow type d022s, xdyn_mcod type d023s. data: xdyn_text_string type string. data: xdyn_text type d020t-dtxt . data: xdyn_head_temp type tdyn_head_temp. data _objname type trobj_name. data dynpros_node type ref to if_ixml_element. data dynpros_filter type ref to if_ixml_node_filter. data dynpros_iterator type ref to if_ixml_node_iterator. data dynpro_node type ref to if_ixml_element. data dynpro_filter type ref to if_ixml_node_filter. data dynpro_iterator type ref to if_ixml_node_iterator. data dynfldl_node type ref to if_ixml_element. data dynfldl_filter type ref to if_ixml_node_filter. data dynfldl_iterator type ref to if_ixml_node_iterator. data dynmcod_node type ref to if_ixml_element. data dynmcod_filter type ref to if_ixml_node_filter. data dynmcod_iterator type ref to if_ixml_node_iterator. data dynflow_node type ref to if_ixml_element. data xdynpro_flow_source type string. data idynpro_flow_source type table_of_strings. _objname = objname. dynpros_node = dynp_node. check dynpros_node is not initial. free: dynpro_filter, dynpro_iterator, dynpro_node. dynpro_filter = dynpros_node->create_filter_name( 'dynpro' ). dynpro_iterator = dynpros_node->create_iterator_filtered( dynpro_filter ). dynpro_node ?= dynpro_iterator->get_next( ). while dynpro_node is not initial. clear: xdyn_head, xdyn_fldl, xdyn_flow, xdyn_mcod. refresh: idyn_fldl, idyn_flow, idyn_mcod. * Get the header data for the screen. call method getstructurefromattributes exporting node = dynpro_node changing structure = xdyn_head_temp. xdyn_head = xdyn_head_temp. xdyn_text = xdyn_head_temp-dtext. * Retrieve field list free: dynfldl_filter, dynfldl_iterator, dynfldl_node. dynfldl_filter = dynpro_node->create_filter_name( 'dynprofield' ). dynfldl_iterator = dynpro_node->create_iterator_filtered( dynfldl_filter ). dynfldl_node ?= dynfldl_iterator->get_next( ). while dynfldl_node is not initial. call method getstructurefromattributes exporting node = dynfldl_node changing structure = xdyn_fldl. append xdyn_fldl to idyn_fldl. dynfldl_node ?= dynfldl_iterator->get_next( ). endwhile. * Retrieve matchcode data. free: dynmcod_filter, dynmcod_iterator, dynmcod_node. dynmcod_filter = dynpro_node->create_filter_name( 'dynprofield' ). dynmcod_iterator = dynpro_node->create_iterator_filtered( dynmcod_filter ). dynmcod_node ?= dynmcod_iterator->get_next( ). while dynmcod_node is not initial. call method getstructurefromattributes exporting node = dynmcod_node changing structure = xdyn_mcod. append xdyn_mcod to idyn_mcod. dynmcod_node ?= dynmcod_iterator->get_next( ). endwhile. * retieve flow logic source. clear xdynpro_flow_source. refresh idynpro_flow_source. clear xdyn_flow. refresh idyn_flow. free dynflow_node. dynflow_node = dynpro_node->find_from_name( 'dynproflowsource' ). xdynpro_flow_source = dynflow_node->get_value( ). idynpro_flow_source = buildtablefromstring( xdynpro_flow_source ). loop at idynpro_flow_source into xdyn_flow. append xdyn_flow to idyn_flow. endloop. * Build dynpro from data call function 'RPY_DYNPRO_INSERT_NATIVE' exporting * suppress_corr_checks = ' ' * CORRNUM = ' ' header = xdyn_head dynprotext = xdyn_text * SUPPRESS_EXIST_CHECKS = ' ' * USE_CORRNUM_IMMEDIATEDLY = ' ' * SUPPRESS_COMMIT_WORK = ' ' tables fieldlist = idyn_fldl flowlogic = idyn_flow params = idyn_mcod exceptions cancelled = 1 already_exists = 2 program_not_exists = 3 not_executed = 4 others = 5. if sy-subrc <> 0. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endif. dynpro_node ?= dynpro_iterator->get_next( ). endwhile. endmethod. method CREATE_PFSTATUS. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data: ista type table of rsmpe_stat, ifun type table of rsmpe_funt, imen type table of rsmpe_men, imtx type table of rsmpe_mnlt, iact type table of rsmpe_act, ibut type table of rsmpe_but, ipfk type table of rsmpe_pfk, iset type table of rsmpe_staf, idoc type table of rsmpe_atrt, itit type table of rsmpe_titt, ibiv type table of rsmpe_buts. data: xsta type rsmpe_stat, xfun type rsmpe_funt, xmen type rsmpe_men, xmtx type rsmpe_mnlt, xact type rsmpe_act, xbut type rsmpe_but, xpfk type rsmpe_pfk, xset type rsmpe_staf, xdoc type rsmpe_atrt, xtit type rsmpe_titt, xbiv type rsmpe_buts. data xtrkey type trkey. data xadm type rsmpe_adm. data _program type trdir-name. data _objname type trobj_name. data stat_node type ref to if_ixml_element. data node type ref to if_ixml_element. data filter type ref to if_ixml_node_filter. data iterator type ref to if_ixml_node_iterator. _objname = objname. stat_node = pfstat_node. check stat_node is not initial. * read pfstatus_sta node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_sta' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xsta. append xsta to ista. node ?= iterator->get_next( ). endwhile. * read pfstatus_fun node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_fun' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xfun. append xfun to ifun. node ?= iterator->get_next( ). endwhile. * read pfstatus_men node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_men' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xmen. append xmen to imen. node ?= iterator->get_next( ). endwhile. * read pfstatus_mtx node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_mtx' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xmtx. append xmtx to imtx. node ?= iterator->get_next( ). endwhile. * read pfstatus_act node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_act' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xact. append xact to iact. node ?= iterator->get_next( ). endwhile. * read pfstatus_but node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_but' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xbut. append xbut to ibut. node ?= iterator->get_next( ). endwhile. * read pfstatus_pfk node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_pfk' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xpfk. append xpfk to ipfk. node ?= iterator->get_next( ). endwhile. * read pfstatus_set node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_set' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xset. append xset to iset. node ?= iterator->get_next( ). endwhile. * read pfstatus_doc node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_doc' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xdoc. append xdoc to idoc. node ?= iterator->get_next( ). endwhile. * read pfstatus_tit node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_tit' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xtit. append xtit to itit. node ?= iterator->get_next( ). endwhile. * read pfstatus_biv node free: filter, iterator, node. filter = stat_node->create_filter_name( 'pfstatus_biv' ). iterator = stat_node->create_iterator_filtered( filter ). node ?= iterator->get_next( ). while node is not initial. call method getstructurefromattributes exporting node = node changing structure = xbiv. append xbiv to ibiv. node ?= iterator->get_next( ). endwhile. * Update the gui status _program = _objname. xtrkey-obj_type = 'PROG'. xtrkey-obj_name = _program. xtrkey-sub_type = 'CUAD'. xtrkey-sub_name = _program. call function 'RS_CUA_INTERNAL_WRITE' exporting program = _program language = sy-langu tr_key = xtrkey adm = xadm state = 'I' tables sta = ista fun = ifun men = imen mtx = imtx act = iact but = ibut pfk = ipfk set = iset doc = idoc tit = itit biv = ibiv exceptions not_found = 1 others = 2. if sy-subrc <> 0. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endif. endmethod. method CREATE_SOURCE. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data _objName type TROBJ_NAME. data progLine type PROGDIR. data titleInfo type trdirti. data reportLine type string. data miniReport type table_of_strings. _objName = objName. call function 'RS_INSERT_INTO_WORKING_AREA' exporting OBJECT = 'REPS' OBJ_NAME = _objName exceptions WRONG_OBJECT_NAME = 1. INSERT REPORT _objName FROM source STATE 'I' program type attribs-subc. ""added to handle includes, etc. MOVE 'I' TO progline-STATE. move-corresponding attribs to progline. progline-idate = sy-datum. progline-itime = sy-uzeit. progline-CDAT = sy-datum. progline-UDAT = sy-datum. progline-SDATE = sy-datum. modify progdir from progline. * Are you kidding me?!? No idea why you need to do this!! CONCATENATE 'REPORT' _objName '.' INTO reportLine SEPARATED BY SPACE. append reportline to miniReport. INSERT REPORT _objName FROM miniReport STATE 'A' program type attribs-subc. ""added to handle includes, etc. MOVE 'A' TO progline-STATE. modify progdir from progline. endmethod. method CREATE_TEXTPOOL. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data textPoolTable type standard table of textPool. data textPoolRow type textPool. data langIterator type ref to if_ixml_node_iterator. data filter type ref to if_ixml_node_filter. data textFilter type ref to if_ixml_node_filter. data textIterator type ref to if_ixml_node_iterator. data langNode type ref to if_ixml_element. data aTextNode type ref to if_ixml_element. data _objName type TROBJ_NAME. data lang type spras. data langNodeExists type flag. data logonLanguageExists type flag. data _state(1) type c. _objName = objName. CHECK textPoolNode IS NOT INITIAL. filter = textPoolNode->create_filter_name( 'language' ). langIterator = textPoolNode->create_iterator_filtered( filter ). langNode ?= langIterator->get_next( ). while langNode is not initial. langNodeExists = 'X'. CALL FUNCTION 'RS_INSERT_INTO_WORKING_AREA' EXPORTING OBJECT = 'REPT' OBJ_NAME = _objName EXCEPTIONS OTHERS = 0. refresh textPoolTable. textIterator = langNode->create_iterator( ). aTextNode ?= textIterator->get_next( ). *For some reason the 1st one is blank... not sure why. aTextNode ?= textIterator->get_next( ). while aTextNode is not initial. call method GETSTRUCTUREFROMATTRIBUTES exporting node = aTextNode changing structure = textPoolRow. append textPoolRow to textPoolTable. aTextNode ?= textIterator->get_next( ). endwhile. if textPoolTable is not initial. lang = langNode->get_attribute( 'SPRAS' ). if lang = sy-langu. logonLanguageExists = 'X'. _state = 'I'. else. * seems that if a textpool is inserted as inactive for language * other than the logon language, it is lost upon activation * not sure inserting as active is best solution,but seems to work _state = 'A'. endif. insert textpool _objName from textPooltable language lang state _state. endif. langNode ?= langIterator->get_next( ). endwhile. endmethod. method DELETEOBJECT. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data program type sy-repid. program = objName. CALL FUNCTION 'RS_DELETE_PROGRAM' EXPORTING * CORRNUMBER = program = program * SUPPRESS_CHECKS = ' ' * SUPPRESS_COMMIT = ' ' SUPPRESS_POPUP = 'X' * MASS_DELETE_CALL = ' ' * WITH_CUA = 'X' * WITH_DOCUMENTATION = 'X' * WITH_DYNPRO = 'X' * WITH_INCLUDES = ' ' * WITH_TEXTPOOL = 'X' * WITH_VARIANTS = 'X' * TADIR_DEVCLASS = * SKIP_PROGRESS_IND = ' ' * FORCE_DELETE_USED_INCLUDES = ' ' * IMPORTING * CORRNUMBER = * PROGRAM = * EXCEPTIONS * ENQUEUE_LOCK = 1 * OBJECT_NOT_FOUND = 2 * PERMISSION_FAILURE = 3 * REJECT_DELETION = 4 * OTHERS = 5 . IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. endmethod. method DEQUEUE_ABAP. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ call function 'RS_ACCESS_PERMISSION' exporting global_lock = 'X' mode = 'FREE' object = objName object_class = 'ABAP' exceptions canceled_in_corr = 1 enqueued_by_user = 3 enqueue_system_failure = 4 locked_by_author = 5 illegal_parameter_values = 6 no_modify_permission = 7 no_show_permission = 8 permission_failure = 9. if sy-subrc <> 0. case sy-subrc. when 7 or 8 or 9. raise exception type zcx_saplink exporting textid = zcx_saplink=>not_authorized. when 5. raise exception type zcx_saplink exporting textid = zcx_saplink=>error_message msg = 'object locked'. when others. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endcase. endif. endmethod. method ENQUEUE_ABAP. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ call function 'RS_ACCESS_PERMISSION' exporting * authority_check = authority_check global_lock = 'X' mode = 'INSERT' * master_language = trdir-rload object = objName object_class = 'ABAP' * importing * transport_key = trkey_global * new_master_language = trdir-rload * devclass = devclass_local exceptions canceled_in_corr = 1 enqueued_by_user = 3 enqueue_system_failure = 4 locked_by_author = 5 illegal_parameter_values = 6 no_modify_permission = 7 no_show_permission = 8 permission_failure = 9. if sy-subrc <> 0. case sy-subrc. when 7 or 8 or 9. raise exception type zcx_saplink exporting textid = zcx_saplink=>not_authorized. when 5. raise exception type zcx_saplink exporting textid = zcx_saplink=>error_message msg = 'object locked'. when others. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endcase. endif. endmethod. method GETOBJECTTYPE. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ objectType = 'PROG'. ""ABAP Program endmethod. method GET_DOCUMENTATION. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data languageNode type ref to if_ixml_element. DATA txtlines_node TYPE REF TO if_ixml_element. DATA rc TYPE sysubrc. DATA _objtype TYPE string. Types: BEGIN OF t_dokhl, id TYPE dokhl-id, object TYPE dokhl-object, langu type dokhl-langu, typ TYPE dokhl-typ, dokversion TYPE dokhl-dokversion, END OF t_dokhl. data lt_dokhl type table of t_dokhl. data ls_dokhl like line of lt_dokhl. DATA lt_lines TYPE TABLE OF tline. DATA ls_lines LIKE LINE OF lt_lines. data lv_str type string. DATA _objname TYPE e071-obj_name. _objname = objname. * Check against database SELECT id object langu typ dokversion INTO corresponding fields of table lt_dokhl FROM dokhl WHERE id = 'RE' AND object = _objname. * Use only most recent version. sort lt_dokhl by id object langu typ ascending dokversion descending. delete adjacent duplicates from lt_dokhl comparing id object typ langu. * Make sure there is at least one record here. clear ls_dokhl. read table lt_dokhl into ls_dokhl index 1. if sy-subrc <> 0. return. endif. docNode = xmlDoc->create_element( 'programDocumentation' ). * Set docNode object attribute lv_str = ls_dokhl-object. rc = docNode->set_attribute( name = 'OBJECT' value = lv_Str ). Loop at lt_dokhl into ls_dokhl. * Create language node, and set attribute languageNode = xmlDoc->create_element( 'language' ). lv_str = ls_dokhl-langu. rc = languageNode->set_attribute( name = 'SPRAS' value = lv_Str ). * Read the documentation text CALL FUNCTION 'DOCU_READ' EXPORTING id = ls_dokhl-id langu = ls_dokhl-langu object = ls_dokhl-object typ = ls_dokhl-typ version = ls_dokhl-dokversion TABLES line = lt_lines. * Write records to XML node LOOP AT lt_lines INTO ls_lines. txtlines_node = xmlDoc->create_element( `textLine` ). me->setattributesfromstructure( node = txtlines_node structure = ls_lines ). rc = languageNode->append_child( txtlines_node ). ENDLOOP. rc = docNode->append_child( languageNode ) . Endloop. endmethod. method GET_DYNPRO. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ types: begin of tdynp, prog type d020s-prog, dnum type d020s-dnum, end of tdynp. data: idyn_fldl type table of d021s, idyn_flow type table of d022s, idyn_mcod type table of d023s. data: xdyn_head type d020s, xdyn_fldl type d021s, xdyn_flow type d022s, xdyn_mcod type d023s. data idynp type table of tdynp. data xdynp type tdynp. data xdyn_text type d020t-dtxt. data xdyn_text_string type string. data _objname type trobj_name. data rc type sy-subrc . data iflowsource type rswsourcet. data xflowsource like line of iflowsource. data flowsourcestring type string. data dynnr_node type ref to if_ixml_element. data dynpromatchnode type ref to if_ixml_element. data dynprofieldsnode type ref to if_ixml_element. data dynproflownode type ref to if_ixml_element. _objname = objname. * Get all dynpros for program object clear xdynp. refresh idynp. select prog dnum into table idynp from d020s where prog = _objname and type <> 'S' "" No Selection Screens and type <> 'J'. "" No selection subscreens check sy-subrc = 0 . dynp_node = xmldoc->create_element( 'dynpros' ). loop at idynp into xdynp. * Retrieve dynpro imformation dynnr_node = xmldoc->create_element( 'dynpro' ). clear: xdyn_head, xdyn_fldl, xdyn_flow, xdyn_mcod. refresh: idyn_fldl, idyn_flow, idyn_mcod. call function 'RPY_DYNPRO_READ_NATIVE' exporting progname = xdynp-prog dynnr = xdynp-dnum * SUPPRESS_EXIST_CHECKS = ' ' * SUPPRESS_CORR_CHECKS = ' ' importing HEADER = xdyn_head dynprotext = xdyn_text tables fieldlist = idyn_fldl flowlogic = idyn_flow params = idyn_mcod * FIELDTEXTS = exceptions cancelled = 1 not_found = 2 permission_error = 3 others = 4. check sy-subrc = 0. * Add heading information for screen. setattributesfromstructure( node = dynnr_node structure = xdyn_head ). * Add the dynpro text also. xdyn_text_string = xdyn_text. rc = dynnr_node->set_attribute( name = 'DTEXT' value = xdyn_text_string ). rc = dynp_node->append_child( dynnr_node ). * Add fields information for screen. if not idyn_fldl[] is initial. loop at idyn_fldl into xdyn_fldl. dynprofieldsnode = xmldoc->create_element( 'dynprofield' ). setattributesfromstructure( node = dynprofieldsnode structure = xdyn_fldl ). rc = dynnr_node->append_child( dynprofieldsnode ). endloop. endif. * Add flow logic of screen if not idyn_flow[] is initial. clear xflowsource. refresh iflowsource. loop at idyn_flow into xdyn_flow. xflowsource = xdyn_flow. append xflowsource to iflowsource. endloop. dynproflownode = xmldoc->create_element( 'dynproflowsource' ). flowsourcestring = buildsourcestring( sourcetable = iflowsource ). rc = dynproflownode->if_ixml_node~set_value( flowsourcestring ). rc = dynnr_node->append_child( dynproflownode ). endif. * Add matchcode information for screen. if not idyn_mcod[] is initial. loop at idyn_mcod into xdyn_mcod. check not xdyn_mcod-type is initial and not xdyn_mcod-content is initial. dynpromatchnode = xmldoc->create_element( 'dynpromatchcode' ). setattributesfromstructure( node = dynpromatchnode structure = xdyn_mcod ). rc = dynnr_node->append_child( dynpromatchnode ). endloop. endif. endloop. endmethod. method GET_PFSTATUS. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data: ista type table of rsmpe_stat, ifun type table of rsmpe_funt, imen type table of rsmpe_men, imtx type table of rsmpe_mnlt, iact type table of rsmpe_act, ibut type table of rsmpe_but, ipfk type table of rsmpe_pfk, iset type table of rsmpe_staf, idoc type table of rsmpe_atrt, itit type table of rsmpe_titt, ibiv type table of rsmpe_buts. data: xsta type rsmpe_stat, xfun type rsmpe_funt, xmen type rsmpe_men, xmtx type rsmpe_mnlt, xact type rsmpe_act, xbut type rsmpe_but, xpfk type rsmpe_pfk, xset type rsmpe_staf, xdoc type rsmpe_atrt, xtit type rsmpe_titt, xbiv type rsmpe_buts. data sta_node type ref to if_ixml_element. data fun_node type ref to if_ixml_element. data men_node type ref to if_ixml_element. data mtx_node type ref to if_ixml_element. data act_node type ref to if_ixml_element. data but_node type ref to if_ixml_element. data pfk_node type ref to if_ixml_element. data set_node type ref to if_ixml_element. data doc_node type ref to if_ixml_element. data tit_node type ref to if_ixml_element. data biv_node type ref to if_ixml_element. data _objname type trobj_name. data _program type trdir-name. data rc type sy-subrc. _objname = objname. _program = objname. call function 'RS_CUA_INTERNAL_FETCH' exporting program = _program language = sy-langu tables sta = ista fun = ifun men = imen mtx = imtx act = iact but = ibut pfk = ipfk set = iset doc = idoc tit = itit biv = ibiv exceptions not_found = 1 unknown_version = 2 others = 3. check sy-subrc = 0. * if there is a gui status or gui title present, then * create pfstatus node. if ista[] is not initial or itit[] is not initial. pfstat_node = xmldoc->create_element( 'pfstatus' ). endif. * if ista is filled, assume there are one or more * gui statuses if ista[] is not initial. loop at ista into xsta. sta_node = xmldoc->create_element( 'pfstatus_sta' ). setattributesfromstructure( node = sta_node structure = xsta ). rc = pfstat_node->append_child( sta_node ). endloop. loop at ifun into xfun. fun_node = xmldoc->create_element( 'pfstatus_fun' ). setattributesfromstructure( node = fun_node structure = xfun ). rc = pfstat_node->append_child( fun_node ). endloop. loop at imen into xmen. men_node = xmldoc->create_element( 'pfstatus_men' ). setattributesfromstructure( node = men_node structure = xmen ). rc = pfstat_node->append_child( men_node ). endloop. loop at imtx into xmtx. mtx_node = xmldoc->create_element( 'pfstatus_mtx' ). setattributesfromstructure( node = mtx_node structure = xmtx ). rc = pfstat_node->append_child( mtx_node ). endloop. loop at iact into xact. act_node = xmldoc->create_element( 'pfstatus_act' ). setattributesfromstructure( node = act_node structure = xact ). rc = pfstat_node->append_child( act_node ). endloop. loop at ibut into xbut. but_node = xmldoc->create_element( 'pfstatus_but' ). setattributesfromstructure( node = but_node structure = xbut ). rc = pfstat_node->append_child( but_node ). endloop. loop at ipfk into xpfk. pfk_node = xmldoc->create_element( 'pfstatus_pfk' ). setattributesfromstructure( node = pfk_node structure = xpfk ). rc = pfstat_node->append_child( pfk_node ). endloop. loop at iset into xset. set_node = xmldoc->create_element( 'pfstatus_set' ). setattributesfromstructure( node = set_node structure = xset ). rc = pfstat_node->append_child( set_node ). endloop. loop at idoc into xdoc. doc_node = xmldoc->create_element( 'pfstatus_doc' ). setattributesfromstructure( node = doc_node structure = xdoc ). rc = pfstat_node->append_child( doc_node ). endloop. loop at ibiv into xbiv. biv_node = xmldoc->create_element( 'pfstatus_biv' ). setattributesfromstructure( node = biv_node structure = xbiv ). rc = pfstat_node->append_child( biv_node ). endloop. endif. * It itit is filled, assume one or more titles if itit[] is not initial. loop at itit into xtit. tit_node = xmldoc->create_element( 'pfstatus_tit' ). setattributesfromstructure( node = tit_node structure = xtit ). rc = pfstat_node->append_child( tit_node ). endloop. endif. endmethod. method GET_SOURCE. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data _objName(30) type c. _objName = me->objName. read report _objName into progSource. endmethod. method GET_TEXTPOOL. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ data aText type ref to if_ixml_element. data textPoolTable type standard table of TEXTPOOL. data textPoolRow type textPool. data languageList type instLang. data aLanguage type SPRAS. data _objName(30) type c. data rc type i. data sTemp type string. data languageNode type ref to if_ixml_element. data firstLoop type flag. _objName = objName. CALL FUNCTION 'RS_TEXTLOG_GET_PARAMETERS' changing INSTALLED_LANGUAGES = languageList. firstLoop = abap_true. loop at languageList into aLanguage. read textpool _objName into textPoolTable language aLanguage. if sy-subrc = 0. if firstLoop = abap_true. textNode = xmlDoc->create_element( 'textPool' ). firstLoop = abap_false. endif. languageNode = xmlDoc->create_Element( 'language' ). sTemp = aLanguage. rc = languageNode->set_attribute( name = 'SPRAS' value = sTemp ). loop at textPoolTable into textPoolRow. aText = xmlDoc->create_element( 'textElement' ). setAttributesFromStructure( node = aText structure = textPoolRow ). rc = languageNode->append_child( aText ). endloop. rc = textNode->append_child( languageNode ). endif. endloop. endmethod. method TRANSPORT_COPY. */---------------------------------------------------------------------\\ *| This file is part of SAPlink. | *| | *| The code of this project is provided to you under the current | *| version of the SAP Code Exchange Terms of Use. You can find the | *| text on the SAP Code Exchange webpage at http://www.sdn.sap.com | *| | *| SAPlink is provided to you AS IS with no guarantee, warranty or | *| support. | *\\---------------------------------------------------------------------/ CALL FUNCTION 'RS_CORR_INSERT' EXPORTING AUTHOR = author GLOBAL_LOCK = 'X' OBJECT = objName OBJECT_CLASS = 'ABAP' DEVCLASS = devClass * KORRNUM = CORRNUMBER_LOCAL MASTER_LANGUAGE = sy-langu * PROGRAM = PROGRAM_LOCAL MODE = 'INSERT' * IMPORTING * AUTHOR = UNAME * KORRNUM = CORRNUMBER_LOCAL * DEVCLASS = DEVCLASS_LOCAL EXCEPTIONS CANCELLED = 1 PERMISSION_FAILURE = 2 UNKNOWN_OBJECTCLASS = 3. if sy-subrc <> 0. case sy-subrc. when 2. raise exception type zcx_saplink exporting textid = zcx_saplink=>not_authorized. when others. raise exception type zcx_saplink exporting textid = zcx_saplink=>system_error. endcase. endif. endmethod. method UPDATE_WB_TREE. DATA: BEGIN OF pname, root(3) VALUE 'PG_', program(27), END OF pname. DATA: trdir TYPE trdir. pname-program = me->objname. CALL FUNCTION 'WB_TREE_ACTUALIZE' EXPORTING tree_name = pname. trdir-name = me->objname. CALL FUNCTION 'RS_TREE_OBJECT_PLACEMENT' EXPORTING object = trdir-name program = trdir-name operation = 'INSERT' type = 'CP'. endmethod. endclass. ""ZSAPLINK_PROGRAM implementation",13224,True,3025.8174176979205,median "/* FX-SaberOS V1.0 released on: 7 October 2017 author: Sebastien CAPOU (neskweek@gmail.com) and Andras Kun (kun.andras@yahoo.de) Source : https://github.com/Protonerd/FX-SaberOS Description: Operating System for Arduino based LightSaber This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. */ /***************************************************************************************************/ #include #include #include #include #include #include #include ""Buttons.h"" #include ""Config_HW.h"" #include ""Config_SW.h"" #include ""ConfigMenu.h"" #include ""Light.h"" #include ""SoundFont.h"" /* * DFPLAYER variables */ #ifdef OLD_DPFPLAYER_LIB #include ""DFPlayer_Mini_Mp3.h"" //SoftwareSerial mp3player(DFPLAYER_TX, DFPLAYER_RX); // TX, RX SoftwareSerial mp3player(7, 8); // TX, RX #else #include #include DFPlayer dfplayer; #endif SoundFont soundFont; unsigned long sndSuppress = millis(); unsigned long sndSuppress2 = millis(); unsigned long clashSndSuppress = millis(); #ifdef DEEP_SLEEP unsigned long sleepTimer = millis(); #endif bool hum_playing = false; // variable to store whether hum is being played #ifdef JUKEBOX bool jukebox_play = false; // indicate whether a song is being played in JukeBox mode uint8_t jb_track; // sound file track number in the directory designated for music playback #endif #ifdef CROSSGUARDSABER bool mainignition_done=false; #endif /*************************************************************************************************** * Saber Finite State Machine Custom Type and State Variable */ // global Saber state and Sub State variables extern SaberStateEnum SaberState; extern SaberStateEnum PrevSaberState; extern ActionModeSubStatesEnum ActionModeSubStates; extern ConfigModeSubStatesEnum ConfigModeSubStates; extern ActionModeSubStatesEnum PrevActionModeSubStates; extern ConfigModeSubStatesEnum PrevConfigModeSubStates; //extern SubStateEnum SubState; /*************************************************************************************************** * Motion detection Variables */ MPU6050 mpu; #ifdef CLASH_DET_MPU_INT I2Cdev i2ccomm; #endif // MPU control/status vars volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high bool dmpReady = false; // set true if DMP init was successful uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU uint8_t devStatus; // return status after each device operation (0 = success, !0 = error) uint16_t packetSize; // expected DMP packet size (default is 42 bytes) uint8_t fifoBuffer[64]; // FIFO storage buffer uint16_t mpuFifoCount; // count of all bytes currently in FIFO // orientation/motion vars Quaternion curRotation; // [w, x, y, z] quaternion container Quaternion prevRotation; // [w, x, y, z] quaternion container static Quaternion prevOrientation; // [w, x, y, z] quaternion container static Quaternion curOrientation; // [w, x, y, z] quaternion container VectorInt16 curAccel; VectorInt16 prevAccel; VectorInt16 curDeltAccel; VectorInt16 prevDeltAccel; /*************************************************************************************************** * LED String variables */ cRGB currentColor; #if defined LEDSTRINGS #ifdef DIYINO_PRIME uint8_t ledPins[] = {LS1, LS2, LS3, LS4, LS5, LS6}; #else if #ifdef DIYINO_STARDUST uint8_t ledPins[] = {LS1, LS2, LS3}; #endif uint8_t blasterPin; #endif #if defined STAR_LED uint8_t ledPins[] = {LED_RED, LED_GREEN, LED_BLUE}; #endif extern bool fireblade; #if defined PIXELBLADE or defined ADF_PIXIE_BLADE #ifdef DIYINO_PRIME uint8_t ledPins[] = {LS1, LS2, LS3, LS4, LS5, LS6}; #else if #ifdef DIYINO_STARDUST uint8_t ledPins[] = {LS1, LS2, LS3}; #endif WS2812 pixels(NUMPIXELS); cRGB color; uint8_t blasterPixel; #endif uint8_t clash = 0; bool lockuponclash = false; uint8_t randomBlink = 0; /*************************************************************************************************** * Buttons variables */ OneButton mainButton(MAIN_BUTTON, true); #ifndef SINGLEBUTTON OneButton lockupButton(AUX_BUTTON, true); #endif // replaced by Saber State Machine Variables //bool actionMode = false; // Play with your saber //bool configMode = false; // Configure your saber //static bool ignition = false; //static bool browsing = false; /*************************************************************************************************** * ConfigMode Variables */ int8_t modification = 0; int8_t prev_modification = 0; int16_t value = 0; uint8_t menu = 0; bool enterMenu = false; bool changeMenu = false; bool play = false; unsigned int configAdress = 0; volatile uint8_t portbhistory = 0xFF; // default is high because the pull-up struct StoreStruct { // This is for mere detection if they are our settings char version[5]; // The settings uint8_t volume;// 0 to 31 uint8_t soundFont;// as many as Sound font you have defined in Soundfont.h Max:253 struct Profile { cRGB mainColor; cRGB clashColor; cRGB blasterboltColor; uint16_t swingSensitivity; uint8_t flickerType; uint8_t poweronoffType; }sndProfile[SOUNDFONT_QUANTITY]; }storage; /*************************************************************************************************** * Function Prototypes * The following prototypes are not correctly generated by Arduino IDE 1.6.5-r5 or previous */ inline void printQuaternion(Quaternion quaternion, long multiplier); inline void printAcceleration(VectorInt16 aaWorld); // ==================================================================================== // === SETUP ROUTINE === // ==================================================================================== void setup() { // join I2C bus (I2Cdev library doesn't do this automatically) #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE Wire.begin(); TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR. #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE Fastwire::setup(400, true); #endif // Serial line for debug Serial.begin(115200); /***** LOAD CONFIG *****/ // Get config from EEPROM if there is one // or initialise value with default ones set in StoreStruct EEPROM.setMemPool(MEMORYBASE, EEPROMSizeATmega328); //Set memorypool base to 32, assume Arduino Uno board configAdress = EEPROM.getAddress(sizeof(StoreStruct)); // Size of config object Serial.print(""size of StoreStruct: "");Serial.println(sizeof(StoreStruct)); Serial.println(configAdress); if (!loadConfig()) { for (uint8_t i = 0; i <= 2; i++) { storage.version[i] = CONFIG_VERSION[i]; } storage.soundFont = SOUNDFONT; storage.volume = VOL; for (uint8_t i=0; i CS_LASTMEMBER) { for (uint8_t i=0; i CS_LASTMEMBER) { storage.volume=31; } /***** LOAD CONFIG *****/ /***** MP6050 MOTION DETECTOR INITIALISATION *****/ // initialize device #if defined LS_INFO Serial.println(F(""Initializing I2C devices..."")); #endif mpu.initialize(); // verify connection #if defined LS_INFO Serial.println(F(""Testing device connections..."")); Serial.println( mpu.testConnection() ? F(""MPU6050 connection successful"") : F(""MPU6050 connection failed"")); // load and configure the DMP Serial.println(F(""Initializing DMP..."")); #endif devStatus = mpu.dmpInitialize_light(); // this is a ligter version of the above /* Those offsets are specific to each MPU6050 device. they are found via calibration process. See this script http://www.i2cdevlib.com/forums/index.php?app=core&module=attach§ion=attach&attach_id=27 */ #ifdef MPUCALOFFSETEEPROM // retreive MPU6050 calibrated offset values from EEPROM EEPROM.setMemPool(MEMORYBASEMPUCALIBOFFSET, EEPROMSizeATmega328); int addressInt = MEMORYBASEMPUCALIBOFFSET; mpu.setXAccelOffset(EEPROM.readInt(addressInt)); #ifdef LS_INFO int16_t output; output = EEPROM.readInt(addressInt); Serial.print(""address: ""); Serial.println(addressInt); Serial.print(""output: ""); Serial.println(output); Serial.println(""""); #endif addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int)); mpu.setYAccelOffset(EEPROM.readInt(addressInt)); #ifdef LS_INFO output = EEPROM.readInt(addressInt); Serial.print(""address: ""); Serial.println(addressInt); Serial.print(""output: ""); Serial.println(output); Serial.println(""""); #endif addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int)); mpu.setZAccelOffset(EEPROM.readInt(addressInt)); #ifdef LS_INFO output = EEPROM.readInt(addressInt); Serial.print(""address: ""); Serial.println(addressInt); Serial.print(""output: ""); Serial.println(output); Serial.println(""""); #endif addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int)); mpu.setXGyroOffset(EEPROM.readInt(addressInt)); #ifdef LS_INFO output = EEPROM.readInt(addressInt); Serial.print(""address: ""); Serial.println(addressInt); Serial.print(""output: ""); Serial.println(output); Serial.println(""""); #endif addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int)); mpu.setYGyroOffset(EEPROM.readInt(addressInt)); #ifdef LS_INFO output = EEPROM.readInt(addressInt); Serial.print(""address: ""); Serial.println(addressInt); Serial.print(""output: ""); Serial.println(output); Serial.println(""""); #endif addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int)); mpu.setZGyroOffset(EEPROM.readInt(addressInt)); #ifdef LS_INFO output = EEPROM.readInt(addressInt); Serial.print(""address: ""); Serial.println(addressInt); Serial.print(""output: ""); Serial.println(output); Serial.println(""""); #endif #else // assign calibrated offset values here: /* UNIT1 */ mpu.setXAccelOffset(46); mpu.setYAccelOffset(-4942); mpu.setZAccelOffset(4721); mpu.setXGyroOffset(23); mpu.setYGyroOffset(-11); mpu.setZGyroOffset(44); #endif // make sure it worked (returns 0 if so) if (devStatus == 0) { // turn on the DMP, now that it's ready #if defined LS_INFO Serial.println(F(""Enabling DMP..."")); #endif mpu.setDMPEnabled(true); // enable Arduino interrupt detection #if defined LS_INFO Serial.println( F( ""Enabling interrupt detection (Arduino external interrupt 0)..."")); #endif // attachInterrupt(0, dmpDataReady, RISING); mpuIntStatus = mpu.getIntStatus(); // set our DMP Ready flag so the main loop() function knows it's okay to use it #if defined LS_INFO Serial.println(F(""DMP ready! Waiting for first interrupt..."")); #endif dmpReady = true; // get expected DMP packet size for later comparison packetSize = mpu.dmpGetFIFOPacketSize(); } else { // ERROR! // 1 = initial memory load failed // 2 = DMP configuration updates failed // (if it's going to break, usually the code will be 1) #if defined LS_INFO Serial.print(F(""DMP Initialization failed (code "")); Serial.print(devStatus); Serial.println(F("")"")); #endif } // configure the motion interrupt for clash recognition // INT_PIN_CFG register // in the working code of MPU6050_DMP all bits of the INT_PIN_CFG are false (0) mpu.setDLPFMode(3); mpu.setDHPFMode(0); //mpu.setFullScaleAccelRange(3); mpu.setIntMotionEnabled(true); // INT_ENABLE register enable interrupt source motion detection mpu.setIntZeroMotionEnabled(false); mpu.setIntFIFOBufferOverflowEnabled(false); mpu.setIntI2CMasterEnabled(false); mpu.setIntDataReadyEnabled(false); // mpu.setMotionDetectionThreshold(10); // 1mg/LSB mpu.setMotionDetectionThreshold(CLASH_THRESHOLD); // 1mg/LSB mpu.setMotionDetectionDuration(2); // number of consecutive samples above threshold to trigger int Serial.println(""checkpoint 0""); #ifdef CLASH_DET_MPU_INT // configure Interrupt with: // int level active low // int driver open drain // interrupt latched until read out (not 50us pulse) i2ccomm.writeByte(MPU6050_DEFAULT_ADDRESS, 0x37, 0xF0); // enable only Motion Interrut i2ccomm.writeByte(MPU6050_DEFAULT_ADDRESS, 0x38, 0x40); #endif mpuIntStatus = mpu.getIntStatus(); #ifdef CLASH_DET_MPU_INT // define D2 (interrupt0) as input pinMode(2, INPUT_PULLUP); // enable Arduino interrupt detection Serial.println(F(""Enabling interrupt detection (Arduino external interrupt 0)..."")); // define Interrupt Service for aux. switch attachInterrupt(0, ISR_MPUInterrupt, FALLING); // int.0 is the pin2 on the Atmega328P #endif /***** MP6050 MOTION DETECTOR INITIALISATION *****/ /***** LED SEGMENT INITIALISATION *****/ // initialize ledstrings segments DDRD |= B01101000; DDRB |= B00101110; //We shut off all pins that could wearing leds,just to be sure PORTD &= B10010111; PORTB &= B11010001; #if defined STAR_LED //initialise start color getColor(storage.sndProfile[storage.soundFont].mainColor); #endif #if defined PIXELBLADE pixels.setOutput(DATA_PIN); // This initializes the NeoPixel library. pixelblade_KillKey_Disable(); currentColor.r = 0; currentColor.g = 0; currentColor.b = 0; lightOn(ledPins, -1, currentColor); delay(300); lightOff(); getColor(storage.sndProfile[storage.soundFont].mainColor); pixelblade_KillKey_Enable(); #endif #if defined FoCSTRING pinMode(FoCSTRING, OUTPUT); FoCOff(FoCSTRING); #endif #if defined ACCENT_LED pinMode(ACCENT_LED, OUTPUT); #endif //Randomize randomness (no really that's what it does) randomSeed(analogRead(2)); /***** LED SEGMENT INITIALISATION *****/ /***** BUTTONS INITIALISATION *****/ // link the Main button functions. pinMode(MAIN_BUTTON, INPUT_PULLUP); mainButton.setClickTicks(CLICK); mainButton.setPressTicks(PRESS_CONFIG); mainButton.attachClick(mainClick); //mainButton.attachDoubleClick(mainDoubleClick); mainButton.attachLongPressStart(mainLongPressStart); mainButton.attachLongPressStop(mainLongPressStop); mainButton.attachDuringLongPress(mainLongPress); #ifndef SINGLEBUTTON // link the Lockup button functions. pinMode(AUX_BUTTON, INPUT_PULLUP); lockupButton.setClickTicks(CLICK); lockupButton.setPressTicks(PRESS_CONFIG); lockupButton.attachClick(lockupClick); //lockupButton.attachDoubleClick(lockupDoubleClick); lockupButton.attachLongPressStart(lockupLongPressStart); lockupButton.attachLongPressStop(lockupLongPressStop); lockupButton.attachDuringLongPress(lockupLongPress); #endif #ifdef DEEP_SLEEP /************ DEEP_SLEEP MODE SETTINGS **********/ pinMode(MP3_PSWITCH, OUTPUT); pinMode(FTDI_PSWITCH, OUTPUT); digitalWrite(MP3_PSWITCH, LOW); // enable MP3 player digitalWrite(FTDI_PSWITCH, LOW); // enable FTDI player // pin change interrupt masks (see below list) PCMSK2 |= bit (PCINT20); // pin 4 Aux button PCMSK0 |= bit (PCINT4); // pin 12 Main button delay(300); #endif // DEEP_SLEEP /***** DF PLAYER INITIALISATION *****/ InitDFPlayer(); delay(200); // according to debug on 3.11.2017, these 2 lines below cause the sporadic disable of sound. For audio tracker they are not strictly needed. //pinMode(SPK1, INPUT); //pinMode(SPK2, INPUT); SinglePlay_Sound(11); delay(20); #ifdef ADF_PIXIE_BLADE InitAdafruitPixie(ledPins); #endif /***** Quick Mute *****/ if (digitalRead(MAIN_BUTTON) == LOW) { Set_Volume(0); //Serial.println(""Muted""); } else { Set_Volume(storage.volume); //Serial.println(""Unmuted""); } /****** INIT SABER STATE VARIABLE *****/ SaberState = S_STANDBY; PrevSaberState = S_SLEEP; ActionModeSubStates = AS_HUM; #ifdef DEEP_SLEEP sleepTimer = millis(); #endif //Disable_MP3(true); // disable the MP3 in Stand-by mode to enable FTDI communication } // ==================================================================================== // === LOOP ROUTINE === // ==================================================================================== void loop() { // if MPU6050 DMP programming failed, don't try to do anything : EPIC FAIL ! if (!dmpReady) { return; } mainButton.tick(); #ifndef SINGLEBUTTON lockupButton.tick(); #endif /*////////////////////////////////////////////////////////////////////////////////////////////////////////// ACTION MODE HANDLER */ ///////////////////////////////////////////////////////////////////////////////////////////////////////// if (SaberState == S_SABERON) { /* // In case we want to time the loop Serial.print(F(""Action Mode"")); Serial.print(F("" time="")); Serial.println(millis()); */ if (ActionModeSubStates != AS_HUM) { // needed for hum relauch only in case it's not already being played hum_playing = false; } else { // AS_HUM if ((millis() - sndSuppress > HUM_RELAUNCH and not hum_playing)) { HumRelaunch(); } } if (ActionModeSubStates == AS_IGNITION) { /* This is the very first loop after Action Mode has been turned on */ #ifndef SINGLEBUTTON lockupButton.setPressTicks(PRESS_ACTION); #endif #if defined PIXELBLADE or defined ADF_PIXIE_BLADE pixelblade_KillKey_Disable(); #endif #if defined LS_INFO Serial.println(F(""START ACTION"")); #endif //Play powerons wavs SinglePlay_Sound(soundFont.getPowerOn((storage.soundFont)*NR_FILE_SF)); // Light up the blade pixelblade_KillKey_Disable(); #ifdef CROSSGUARDSABER lightIgnition(ledPins, soundFont.getPowerOnTime(), storage.sndProfile[storage.soundFont].poweronoffType, storage.sndProfile[storage.soundFont].mainColor, MAINBLADE_OFFSET, MAINBLADE_OFFSET+MAINBLADE_LENGTH); mainignition_done=true; #else // single blade or saber staff lightIgnition(ledPins, soundFont.getPowerOnTime(), storage.sndProfile[storage.soundFont].poweronoffType, storage.sndProfile[storage.soundFont].mainColor); #endif sndSuppress = millis()-soundFont.getPowerOnTime(); sndSuppress2 = millis(); #ifdef CROSSGUARDSABER // ignite the crossguard after the defined wat time or latest when a new hum shall be relaunched while (millis()-sndSuppress2 60 and mpuIntStatus < 70 and ActionModeSubStates != AS_BLADELOCKUP) { FX_Clash(); } #endif // CLASH_DET_MPU_POLL /* SIMPLE BLADE MOVEMENT DETECTION FOR MOTION TRIGGERED BLASTER FEDLECT We detect swings as hilt's orientation change since IMUs sucks at determining relative position in space */ // movement of the hilt while blaster move deflect is activated can trigger a blaster deflect #ifdef CLASH_DET_MPU_POLL else if ((ActionModeSubStates == AS_BLASTERDEFLECTPRESS or (ActionModeSubStates == AS_BLASTERDEFLECTMOTION and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis #endif #ifdef CLASH_DET_MPU_INT if ((ActionModeSubStates == AS_BLASTERDEFLECTPRESS or (ActionModeSubStates == AS_BLASTERDEFLECTMOTION and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis #endif or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity or abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity))) and (millis() - sndSuppress >= BLASTERBLOCK_SUPRESS)) { if (soundFont.getBlaster((storage.soundFont)*NR_FILE_SF)) { SinglePlay_Sound(soundFont.getBlaster((storage.soundFont)*NR_FILE_SF)); #if defined LEDSTRINGS lightBlasterEffect(ledPins, 0, 0); //blasterPin = random(1,5); //momentary shut off one led segment //analogWrite(ledPins[blasterPin], LOW); #endif #if defined STAR_LED getColor(storage.sndProfile[storage.soundFont].blasterboltColor); lightOn(ledPins, -1, currentColor); #endif //STAR_LED #if defined PIXELBLADE if (fireblade) { // #ifdef FIREBLADE blasterPixel = random(NUMPIXELS / 4, NUMPIXELS - 3); //momentary shut off one led segment lightBlasterEffect(ledPins, blasterPixel, map(NUMPIXELS, 10, NUMPIXELS-10, 1, 2), storage.sndProfile[storage.soundFont].blasterboltColor); } else { // #else lightOn(ledPins, -1, currentColor); blasterPixel = random(NUMPIXELS / 4, NUMPIXELS - 3); //momentary shut off one led segment getColor(storage.sndProfile[storage.soundFont].blasterboltColor); lightBlasterEffect(ledPins, blasterPixel, map(NUMPIXELS, 10, NUMPIXELS-10, 1, 2), storage.sndProfile[storage.soundFont].blasterboltColor); } // #endif #endif //delay(BLASTER_FX_DURATION); // blaster bolt deflect duration // Some Soundfont may not have Blaster sounds if (millis() - sndSuppress > 50) { //SinglePlay_Sound(soundFont.getBlaster((storage.soundFont)*NR_FILE_SF)); sndSuppress = millis(); } } } /* SWING DETECTION We detect swings as hilt's orientation change since IMUs sucks at determining relative position in space */ else if ( (not fireblade) and (ActionModeSubStates != AS_BLADELOCKUP #ifdef SWING_QUATERNION or lockuponclash// end lockuponclash event on a swing, but only if swings are calculated based on quaternions, otherwise swings will // interrut the lockup uncontrollably #endif ) #ifndef SWING_QUATERNION and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity or abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity) and (millis() - sndSuppress > SWING_SUPPRESS) #else // SWING_QUATERNION is defined and abs(curRotation.w * 1000) < 999 // some rotation movement have been initiated and ( #if defined BLADE_X ( (millis() - sndSuppress > SWING_SUPPRESS) // The movement doesn't follow another to closely and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity or abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity * 10) ) or (// A reverse movement follow a first one (millis() - sndSuppress2 > SWING_SUPPRESS) // The reverse movement doesn't follow another reverse movement to closely // and it must be a reverse movement on Vertical axis and ( abs(curDeltAccel.y) > abs(curDeltAccel.z) and abs(prevDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity and ( (prevDeltAccel.y > 0 and curDeltAccel.y < -storage.sndProfile[storage.soundFont].swingSensitivity) or ( prevDeltAccel.y < 0 and curDeltAccel.y > storage.sndProfile[storage.soundFont].swingSensitivity ) ) ) ) or (// A reverse movement follow a first one (millis() - sndSuppress2 > SWING_SUPPRESS) // The reverse movement doesn't follow another reverse movement to closely and ( // and it must be a reverse movement on Horizontal axis abs(curDeltAccel.z) > abs(curDeltAccel.y) and abs(prevDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity and ( (prevDeltAccel.z > 0 and curDeltAccel.z < -storage.sndProfile[storage.soundFont].swingSensitivity) or ( prevDeltAccel.z < 0 and curDeltAccel.z > storage.sndProfile[storage.soundFont].swingSensitivity ) ) ) ) // the movement must not be triggered by pure blade rotation (wrist rotation) and not ( abs(prevRotation.x * 1000 - curRotation.x * 1000) > abs(prevRotation.y * 1000 - curRotation.y * 1000) and abs(prevRotation.x * 1000 - curRotation.x * 1000) > abs(prevRotation.z * 1000 - curRotation.z * 1000) ) #endif // BLADE_X #if defined BLADE_Y ( (millis() - sndSuppress > SWING_SUPPRESS) // The movement doesn't follow another to closely and (abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity or abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity * 10) ) or (// A reverse movement follow a first one (millis() - sndSuppress2 > SWING_SUPPRESS) // The reverse movement doesn't follow another reverse movement to closely // and it must be a reverse movement on Vertical axis and ( abs(curDeltAccel.x) > abs(curDeltAccel.z) and abs(prevDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity and ( (prevDeltAccel.x > 0 and curDeltAccel.x < -storage.sndProfile[storage.soundFont].swingSensitivity) or ( prevDeltAccel.x < 0 and curDeltAccel.x > storage.sndProfile[storage.soundFont].swingSensitivity ) ) ) ) or (// A reverse movement follow a first one (millis() - sndSuppress2 > SWING_SUPPRESS) // The reverse movement doesn't follow another reverse movement to closely and ( // and it must be a reverse movement on Horizontal axis abs(curDeltAccel.z) > abs(curDeltAccel.x) and abs(prevDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity and ( (prevDeltAccel.z > 0 and curDeltAccel.z < -storage.sndProfile[storage.soundFont].swingSensitivity) or ( prevDeltAccel.z < 0 and curDeltAccel.z > storage.sndProfile[storage.soundFont].swingSensitivity ) ) ) ) // the movement must not be triggered by pure blade rotation (wrist rotation) and not ( abs(prevRotation.y * 1000 - curRotation.y * 1000) > abs(prevRotation.x * 1000 - curRotation.x * 1000) and abs(prevRotation.y * 1000 - curRotation.y * 1000) > abs(prevRotation.z * 1000 - curRotation.z * 1000) ) #endif // BLADE_Y #if defined BLADE_Z ( (millis() - sndSuppress > SWING_SUPPRESS) // The movement doesn't follow another to closely and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis or abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity * 10) ) or (// A reverse movement follow a first one (millis() - sndSuppress2 > SWING_SUPPRESS) // The reverse movement doesn't follow another reverse movement to closely // and it must be a reverse movement on Vertical axis and ( abs(curDeltAccel.y) > abs(curDeltAccel.x) and abs(prevDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity and ( (prevDeltAccel.y > 0 and curDeltAccel.y < -storage.sndProfile[storage.soundFont].swingSensitivity) or ( prevDeltAccel.y < 0 and curDeltAccel.y > storage.sndProfile[storage.soundFont].swingSensitivity ) ) ) ) or (// A reverse movement follow a first one (millis() - sndSuppress2 > SWING_SUPPRESS) // The reverse movement doesn't follow another reverse movement to closely and ( // and it must be a reverse movement on Horizontal axis abs(curDeltAccel.x) > abs(curDeltAccel.y) and abs(prevDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity and ( (prevDeltAccel.x > 0 and curDeltAccel.x < -storage.sndProfile[storage.soundFont].swingSensitivity) or ( prevDeltAccel.x < 0 and curDeltAccel.x > storage.sndProfile[storage.soundFont].swingSensitivity ) ) ) ) // the movement must not be triggered by pure blade rotation (wrist rotation) and not ( abs(prevRotation.z * 1000 - curRotation.z * 1000) > abs(prevRotation.y * 1000 - curRotation.y * 1000) and abs(prevRotation.z * 1000 - curRotation.z * 1000) > abs(prevRotation.x * 1000 - curRotation.x * 1000) ) #endif // BLADE_Z ) #endif // SWING_QUATERNION ) { // end of the condition definition for swings if ( ActionModeSubStates != AS_BLASTERDEFLECTMOTION and ActionModeSubStates != AS_BLASTERDEFLECTPRESS) { /* THIS IS A SWING ! */ prevDeltAccel = curDeltAccel; #if defined LS_SWING_DEBUG Serial.print(F(""SWING\\ttime="")); Serial.println(millis() - sndSuppress); Serial.print(F(""\\t\\tcurRotation\\tw="")); Serial.print(curRotation.w * 1000); Serial.print(F(""\\t\\tx="")); Serial.print(curRotation.x); Serial.print(F(""\\t\\ty="")); Serial.print(curRotation.y); Serial.print(F(""\\t\\tz="")); Serial.print(curRotation.z); Serial.print(F(""\\t\\tAcceleration\\tx="")); Serial.print(curDeltAccel.x); Serial.print(F(""\\ty="")); Serial.print(curDeltAccel.y); Serial.print(F(""\\tz="")); Serial.println(curDeltAccel.z); #endif #ifdef CLASH_DET_MPU_POLL motionEngine(); if (mpuIntStatus > 60 and mpuIntStatus < 70 and ActionModeSubStates != AS_BLADELOCKUP) { SinglePlay_Sound(soundFont.getClash((storage.soundFont)*NR_FILE_SF)); sndSuppress = millis(); sndSuppress2 = millis(); /* THIS IS A CLASH ! */ ActionModeSubStates = AS_CLASH; lightClashEffect(ledPins, storage.sndProfile[storage.soundFont].clashColor); if (!fireblade) { delay(CLASH_FX_DURATION); // clash duration } } else { #endif // CLASH_DET_MPU_POLL ActionModeSubStates = AS_SWING; SinglePlay_Sound(soundFont.getSwing((storage.soundFont)*NR_FILE_SF)); /* NORMAL SWING */ if (millis() - sndSuppress > SWING_SUPPRESS) { sndSuppress = millis(); } if (millis() - sndSuppress2 > SWING_SUPPRESS) { sndSuppress2 = millis(); } #ifdef CLASH_DET_MPU_POLL } #endif // CLASH_DET_MPU_POLL } } else { // simply flicker if (ActionModeSubStates != AS_BLASTERDEFLECTMOTION and ActionModeSubStates != AS_BLADELOCKUP) { // do not deactivate blaster move deflect mode in case the saber is idling ActionModeSubStates = AS_HUM; } else if (ActionModeSubStates == AS_BLASTERDEFLECTMOTION) { accentLEDControl(AL_PULSE); } // relaunch hum if more than HUM_RELAUNCH time elapsed since entering AS_HUM state if (millis() - sndSuppress > HUM_RELAUNCH and not hum_playing and ActionModeSubStates != AS_BLADELOCKUP) { HumRelaunch(); } getColor(storage.sndProfile[storage.soundFont].mainColor); lightFlicker(ledPins, storage.sndProfile[storage.soundFont].flickerType, 0, storage.sndProfile[storage.soundFont].mainColor, storage.sndProfile[storage.soundFont].clashColor, ActionModeSubStates); if (lockuponclash) { accentLEDControl(AL_PULSE); } } // ************************* blade movement detection ends*********************************** } ////END ACTION MODE HANDLER/////////////////////////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////////////////////////////////////////// CONFIG MODE HANDLER *////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (SaberState == S_CONFIG) { // read out the motion sensor in order to be able to detect clashes in Config Mode for the ""Hit-and-Run"" motionEngine(); if ((mpuIntStatus > 60 and mpuIntStatus < 70) and (millis() - sndSuppress >= CLASH_SUPRESS)) { sndSuppress = millis(); // define what shall happen in each Config Sub-State if the Escape Path is activated #if defined LS_INFO Serial.println(""Hit-and-Run is activated""); #endif #ifdef SINGLEBUTTON // In case a clash is detected, move to the next menu item in single button mode NextConfigState(); #else // in two button mode, activate different Hit-and-Run functions depending on the config state if (ConfigModeSubStates==CS_BATTERYLEVEL or ConfigModeSubStates==CS_MAINCOLOR or ConfigModeSubStates==CS_CLASHCOLOR or ConfigModeSubStates==CS_BLASTCOLOR or ConfigModeSubStates==CS_STORAGEACCESS or ConfigModeSubStates==CS_UARTMODE) { changeMenu = false; SaberState=S_STANDBY; PrevSaberState=S_CONFIG; #ifdef PIXELBLADE pixelblade_KillKey_Disable(); #endif } // for all other states: switch(ConfigModeSubStates) { case CS_VOLUME: // turn on the volume full storage.volume = 30; //MAX BladeMeter(ledPins, storage.volume*100/30); Set_Volume(storage.volume); // Too Slow: we'll change volume on exit delay(50); #if defined LS_INFO Serial.println(storage.volume); #endif break; case CS_SOUNDFONT: break; case CS_FLICKERTYPE: break; case CS_POWERONOFFTYPE: break; case CS_SWINGSENSITIVITY: // upon clash increase swing sensitivity by 1/10th of a g (1g=16384) if (storage.sndProfile[storage.soundFont].swingSensitivity <= 14400 ) { storage.sndProfile[storage.soundFont].swingSensitivity=storage.sndProfile[storage.soundFont].swingSensitivity+1600; } else { storage.sndProfile[storage.soundFont].swingSensitivity=0; } /* if (storage.sndProfile[storage.soundFont].swingSensitivity < 8000 ) { storage.sndProfile[storage.soundFont].swingSensitivity=8000; } else if ((storage.sndProfile[storage.soundFont].swingSensitivity >= 8000 ) and (storage.sndProfile[storage.soundFont].swingSensitivity < 16000 )) { storage.sndProfile[storage.soundFont].swingSensitivity=16000; } else { // storage.sndProfile[storage.soundFont].swingSensitivity=100; }*/ BladeMeter(ledPins, (storage.sndProfile[storage.soundFont].swingSensitivity)/100); Serial.println(storage.sndProfile[storage.soundFont].swingSensitivity); break; case CS_SLEEPINIT: break; } #endif // SINGLEBUTTON } if (PrevSaberState == S_STANDBY) { // entering config mode PrevSaberState = S_CONFIG; //if (storage.volume <= 10) { // Set_Volume(10); // delay(200); //} SinglePlay_Sound(3); delay(600); #if defined PIXELBLADE or defined ADF_PIXIE_BLADE pixelblade_KillKey_Disable(); #endif #if defined LS_INFO Serial.println(F(""START CONF"")); #endif enterMenu = true; ConfigModeSubStates=-1; NextConfigState(); //#ifdef BATTERY_CHECK // ConfigModeSubStates = CS_BATTERYLEVEL; // BatLevel_ConfigEnter(); //#else // ConfigModeSubStates = CS_SOUNDFONT; // SinglePlay_Sound(5); // delay(500); //#endif } #if defined PIXELBLADE or defined STAR_LED or defined ADF_PIXIE_BLADE if (ConfigModeSubStates == CS_MAINCOLOR or ConfigModeSubStates == CS_CLASHCOLOR or ConfigModeSubStates == CS_BLASTCOLOR) { #ifdef GRAVITY_COLOR modification = GravityVector(); switch (modification) { case (0): // red + currentColor.r = 100; currentColor.g = 0; currentColor.b = 0; break; case (1): // red - currentColor.r = 20; currentColor.g = 0; currentColor.b = 0; break; case (2): // green + currentColor.r = 0; currentColor.g = 100; currentColor.b = 0; break; case (3): // green - currentColor.r = 0; currentColor.g = 20; currentColor.b = 0; break; case (4): // blue + currentColor.r = 0; currentColor.g = 0; currentColor.b = 100; break; case (5): // blue - currentColor.r = 0; currentColor.g = 0; currentColor.b = 20; break; } // in case of a neopixel blade, show the gravity color on the last 5 pixel of the blade tip #ifdef PIXELBLADE lightOn(ledPins, -1, currentColor, NUMPIXELS - 5, NUMPIXELS); #else if STAR_LED #endif #ifdef ADF_PIXIE_BLADE if (ConfigModeSubStates == CS_MAINCOLOR) { lightOn(ledPins, -1, storage.sndProfile[storage.soundFont].mainColor); } else if (ConfigModeSubStates == CS_CLASHCOLOR) { lightOn(ledPins, -1, storage.sndProfile[storage.soundFont].clashColor); } else if (ConfigModeSubStates == CS_BLASTCOLOR) { lightOn(ledPins, -1, storage.sndProfile[storage.soundFont].blasterboltColor); } #endif #endif // GRAVITY_COLOR } #endif // color configuration for PIXELBLADE or STAR_LED or ADF_PIXIE_BLADE if (ConfigModeSubStates == CS_FLICKERTYPE) { lightFlicker(ledPins, storage.sndProfile[storage.soundFont].flickerType, 0, storage.sndProfile[storage.soundFont].mainColor, storage.sndProfile[storage.soundFont].clashColor, ActionModeSubStates); } else if (ConfigModeSubStates == CS_SWINGSENSITIVITY and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity or abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity)) { SinglePlay_Sound(soundFont.getSwing((storage.soundFont)*NR_FILE_SF)); } else if (ConfigModeSubStates == CS_BATTERYLEVEL) { MonitorBattery(); } } //END CONFIG MODE HANDLER /*////////////////////////////////////////////////////////////////////////////////////////////////////////// STANDBY MODE *////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (SaberState == S_STANDBY) { if (ActionModeSubStates == AS_RETRACTION) { // we just leaved Action Mode //detachInterrupt(0); #if defined DEEP_SLEEP sleepTimer=millis(); // reset sleep time counter #endif SinglePlay_Sound(soundFont.getPowerOff((storage.soundFont)*NR_FILE_SF)); ActionModeSubStates = AS_HUM; changeMenu = false; modification = 0; #ifdef CROSSGUARDSABER mainignition_done=false; #endif #if defined LS_INFO Serial.println(F(""END ACTION"")); #endif #ifndef SINGLEBUTTON lockupButton.setPressTicks(PRESS_CONFIG); #endif lightRetract(ledPins, soundFont.getPowerOffTime(), storage.sndProfile[storage.soundFont].poweronoffType,storage.sndProfile[storage.soundFont].mainColor); pixelblade_KillKey_Enable(); #if defined DEEP_SLEEP sleepTimer=millis(); // reset sleep time counter #endif } if (PrevSaberState == S_CONFIG) { // we just leaved Config Mode saveConfig(); PrevSaberState = S_STANDBY; #if defined DEEP_SLEEP sleepTimer=millis(); // reset sleep time counter #endif // these commands are not used at the moment and make exit from config mode too long //Disable_FTDI(false); //Disable_MP3(false); //delay(300); /* RESET CONFIG */ // for (unsigned int i = 0; i < EEPROMSizeATmega328; i++) { // // if (EEPROM.read(i) != 0) { // EEPROM.update(i, 0); // // } // } SinglePlay_Sound(3); //browsing = false; enterMenu = false; modification = 0; //dfplayer.setVolume(storage.volume); menu = 0; #if defined STAR_LED getColor(storage.sndProfile[storage.soundFont].mainColor); #endif #if defined PIXELBLADE getColor(storage.sndProfile[storage.soundFont].mainColor); #endif #if defined LS_INFO Serial.println(F(""END CONF"")); #endif } // switch of light in Stand-by mode #if defined STAR_LED lightOff(); #else lightOff(); #endif accentLEDControl(AL_ON); #if defined DEEP_SLEEP and (SLEEPYTIME>5000 and SLEEPYTIME<65000) if (millis() - sleepTimer > SLEEPYTIME) { // after the defined max idle time SLEEPYTIME automatically go to sleep mode SaberState=S_SLEEP; PrevSaberState=S_STANDBY; // play a beep 3 times SinglePlay_Sound(1); delay(500); SinglePlay_Sound(1); delay(500); SinglePlay_Sound(1); delay(500); } #endif } // END STANDBY MODE #ifdef JUKEBOX /*////////////////////////////////////////////////////////////////////////////////////////////////////////// JUKEBOX MODE (a.k.a. MP3 player mode *////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (SaberState == S_JUKEBOX) { if (PrevSaberState == S_STANDBY) { // just entered JukeBox mode PrevSaberState = S_JUKEBOX; SinglePlay_Sound(14); // play intro sound of JukeBox mode delay(2500); #if defined PIXELBLADE or defined ADF_PIXIE_BLADE pixelblade_KillKey_Disable(); #endif #if defined LS_INFO Serial.println(F(""START JUKEBOX"")); #endif // start playing the first song jb_track = NR_CONFIGFOLDERFILES + 1; SinglePlay_Sound(jb_track); // JukeBox dir/files must be directly adjecent to config sounds on the SD card } if (jukebox_play) { #ifdef LEDSTRINGS JukeBox_Stroboscope(ledPins); #endif #ifdef STAR_LED JukeBox_Stroboscope(); #endif #ifdef PIXELBLADE getColor(storage.sndProfile[storage.soundFont].mainColor); JukeBox_Stroboscope(currentColor); #endif } } #endif // JUKEBOX #ifdef DEEP_SLEEP else if (SaberState == S_SLEEP) { Serial.println(""LoL""); //if (PrevSaberState == S_CONFIG or ) { // just entered Sleep mode //byte old_ADCSRA = ADCSRA; // disable ADC to save power // disable ADC // repeat the interupt mask again here, it is already done in the setup() function // but for an unknown reason sometimes the device fails to wake up... // pin change interrupt masks (see below list) //PCMSK2 |= bit (PCINT20); // pin 4 Aux button //PCMSK0 |= bit (PCINT4); // pin 12 Main button //delay(300); //Serial.println(""LoL""); ADCSRA = 0; // reduces another ~100uA! // turns accent LED Off accentLEDControl(AL_OFF); SleepModeEntry(); // .. and the code will continue from here SleepModeExit(); SaberState = S_STANDBY; PrevSaberState = S_SLEEP; ADCSRA = 135; // old_ADCSRA; // re-enable ADC conversion // play boot sound SinglePlay_Sound(11); delay(20); //} } #endif // DEEP_SLEEP } //loop // ==================================================================================== // === MOTION DETECTION FUNCTIONS === // ==================================================================================== inline void motionEngine() { // if programming failed, don't try to do anything if (!dmpReady) return; // wait for MPU interrupt or extra packet(s) available // while (!mpuInterrupt && mpuFifoCount < packetSize) { // /* other program behavior stuff here // * // * If you are really paranoid you can frequently test in between other // * stuff to see if mpuInterrupt is true, and if so, ""break;"" from the // * while() loop to immediately process the MPU data // */ // } // reset interrupt flag and get INT_STATUS byte mpuInterrupt = false; mpuIntStatus = mpu.getIntStatus(); // get current FIFO count mpuFifoCount = mpu.getFIFOCount(); // check for overflow (this should never happen unless our code is too inefficient) if ((mpuIntStatus & 0x10) || mpuFifoCount == 1024) { // reset so we can continue cleanly mpu.resetFIFO(); // otherwise, check for DMP data ready interrupt (this should happen frequently) } else if (mpuIntStatus & 0x02) { // wait for correct available data length, should be a VERY short wait while (mpuFifoCount < packetSize) mpuFifoCount = mpu.getFIFOCount(); // read a packet from FIFO mpu.getFIFOBytes(fifoBuffer, packetSize); // track FIFO count here in case there is > 1 packet available // (this lets us immediately read more without waiting for an interrupt) mpuFifoCount -= packetSize; #ifdef SWING_QUATERNION //Making the last orientation the reference for next rotation prevOrientation = curOrientation.getConjugate(); #endif // SWING_QUATERNION prevAccel = curAccel; //retrieve current orientation value #ifdef SWING_QUATERNION mpu.dmpGetQuaternion(&curOrientation, fifoBuffer); #endif // SWING_QUATERNION mpu.dmpGetAccel(&curAccel, fifoBuffer); curDeltAccel.x = prevAccel.x - curAccel.x; curDeltAccel.y = prevAccel.y - curAccel.y; curDeltAccel.z = prevAccel.z - curAccel.z; #ifdef SWING_QUATERNION //We calculate the rotation quaternion since last orientation prevRotation = curRotation; curRotation = prevOrientation.getProduct( curOrientation.getNormalized()); #endif // SWING_QUATERNION #if defined LS_MOTION_HEAVY_DEBUG // display quaternion values in easy matrix form: w x y z printQuaternion(curRotation); #endif } } //motionEngine inline void dmpDataReady() { mpuInterrupt = true; } //dmpDataReady #if defined LS_MOTION_DEBUG inline void printQuaternion(Quaternion quaternion) { Serial.print(F(""\\t\\tQ\\t\\tw="")); Serial.print(quaternion.w * 1000); Serial.print(F(""\\t\\tx="")); Serial.print(quaternion.x); Serial.print(F(""\\t\\ty="")); Serial.print(quaternion.y); Serial.print(F(""\\t\\tz="")); Serial.println(quaternion.z); } //printQuaternion #endif uint8_t GravityVector() { uint8_t Orientation; // 0: +X, 1: -X, 2: +Y, 3: -Y, 4: +Z, 5: -Z int16_t ax, ay, az; //mpu.dmpGetAccel(&curAccel, fifoBuffer); mpu.getAcceleration(&ax, &ay, &az); //printAccel(ax, ay, az); if (ax < 0) { Orientation = 1; // -X } else { Orientation = 0; // +X } if (abs(abs(ax) - 16000) > abs(abs(ay) - 16000)) { if (ay < 0) { Orientation = 3; // -Y } else { Orientation = 2; // +Y } } if ( (abs(abs(ay) - 16000) > abs(abs(az) - 16000)) and (abs(abs(ax) - 16000) > abs(abs(az) - 16000)) ) { if (az < 0) { Orientation = 5; // -Z } else { Orientation = 4; // +Z } } //Serial.print(F(""\\t\\Orientation="")); //Serial.println(Orientation); return Orientation; } void FX_Clash() { #if defined LS_CLASH_DEBUG Serial.print(F(""CLASH\\tmpuIntStatus="")); Serial.println(mpuIntStatus); #endif if (lockuponclash) { //if (ActionModeSubStates==AS_PREBLADELOCKUP or lockuponclash) { //Lockup Start ActionModeSubStates = AS_BLADELOCKUP; if (soundFont.getLockup((storage.soundFont)*NR_FILE_SF)) { LoopPlay_Sound(soundFont.getLockup((storage.soundFont)*NR_FILE_SF)); } } else { // ordinary clash if (millis() - clashSndSuppress >= CLASH_SUPRESS) { SinglePlay_Sound(soundFont.getClash((storage.soundFont)*NR_FILE_SF)); /* THIS IS A CLASH ! */ ActionModeSubStates = AS_CLASH; lightClashEffect(ledPins, storage.sndProfile[storage.soundFont].clashColor); if (!fireblade) { //delay(CLASH_FX_DURATION); // clash duration delayMicroseconds(CLASH_FX_DURATION*1000); } sndSuppress = millis(); sndSuppress2 = millis(); clashSndSuppress=millis(); } } } #ifdef CLASH_DET_MPU_INT void ISR_MPUInterrupt() { if (SaberState==S_SABERON) { FX_Clash(); } } #endif //#if defined LS_MOTION_DEBUG //inline void printAccel(int16_t ax, int16_t ay, int16_t az) { // Serial.print(F(""\\t\\tx="")); // Serial.print(ax); // Serial.print(F(""\\t\\ty="")); // Serial.print(ay); // Serial.print(F(""\\t\\tz="")); // Serial.println(az); //} //printQuaternion //#endif // ==================================================================================== // === EEPROM MANIPULATION FUNCTIONS === // ==================================================================================== inline bool loadConfig() { bool equals = true; EEPROM.readBlock(configAdress, storage); for (uint8_t i = 0; i <= 2; i++) { if (storage.version[i] != CONFIG_VERSION[i]) { equals = false; Serial.println(""Wrong config!""); } } Serial.println(storage.version); //Serial.print(""ADC status:""); Serial.println(ADCSRA); return equals; } //loadConfig inline void saveConfig() { EEPROM.updateBlock(configAdress, storage); //#ifdef LS_DEBUG // dump values stored in EEPROM //for (uint8_t i = 0; i < 255; i++) { // Serial.print(i); Serial.print(""\\t""); Serial.println(EEPROM.readByte(i)); //} //#endif } //saveConfig // ==================================================================================== // === SOUND FUNCTIONS === // ==================================================================================== void HumRelaunch() { LoopPlay_Sound(soundFont.getHum((storage.soundFont)*NR_FILE_SF)); sndSuppress = millis(); hum_playing = true; } void SinglePlay_Sound(uint8_t track) { #ifdef OLD_DPFPLAYER_LIB mp3_play_physical(track); #else // DFPlayer_LSOS dfplayer.playPhysicalTrack(track); #endif } void LoopPlay_Sound(uint8_t track) { #ifdef OLD_DPFPLAYER_LIB mp3_loop_play(track); #else // DFPlayer_LSOS dfplayer.playSingleLoop(track); #endif } void Set_Volume(int8_t volumeSet) { #ifdef OLD_DPFPLAYER_LIB mp3_set_volume (volumeSet); #else dfplayer.setVolume(volumeSet); // Too Slow: we'll change volume on exit #endif delay(50); } void Set_Loop_Playback() { #ifdef OLD_DPFPLAYER_LIB mp3_single_loop(true); #else dfplayer.setSingleLoop(true);; #endif } void InitDFPlayer() { #ifdef OLD_DPFPLAYER_LIB mp3_set_serial (mp3player); //set softwareSerial for DFPlayer-mini mp3 module mp3player.begin(9600); delay(50); mp3_set_device(1); //playback from SD card //delay(50); //mp3_set_volume (storage.volume); #else dfplayer.setSerial(DFPLAYER_TX, DFPLAYER_RX); // AK 7.9.2016: if the storage.volume has no or invalid value, it will cause the // sketch to repeat setup (reset itself) - up till now no idea why? // this can happen if the EEPROM is erased (i.e. reflash of bootloader) //if (CS_LASTMEMBER < CS_VOLUME) { // if the volume cannot be set from the config menu, set it to the loudest // storage.volume=31; //} //dfplayer.setVolume(storage.volume); //setup finished. Boot ready. We notify ! #endif } void Pause_Sound() { #ifdef OLD_DPFPLAYER_LIB mp3_pause(); #else dfplayer.pause(); #endif } void Resume_Sound() { #ifdef OLD_DPFPLAYER_LIB mp3_play(); #else dfplayer.play(); #endif } #ifdef DEEP_SLEEP // ==================================================================================== // === SLEEP MODE FUNCTIONS === // ==================================================================================== void sleepNow() // here we put the arduino to sleep { power_all_disable (); // turn off all modules -> no measurable effect set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here sleep_enable(); // enables the sleep bit in the mcucr register // so sleep is possible. just a safety pin // turn off brown-out enable in software -> no measurable effect MCUCR = bit (BODS) | bit (BODSE); MCUCR = bit (BODS); PCIFR |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2); // clear any outstanding interrupts PCICR |= bit (PCIE0) | bit (PCIE1) | bit (PCIE2); // enable pin change interrupts //PCMSK0 |= bit (PCINT4); // enable pin change interrupt pin 12 Main button //delay(300); //enableInterrupt(12, SleepModeExit, CHANGE); sleep_mode(); // here the device is actually put to sleep!! // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP sleep_disable(); // first thing after waking from sleep: // disable sleep... detachInterrupt(0); // disables interrupt 0 on pin 2 so the // wakeUpNow code will not be executed // during normal running time. } void SleepModeEntry() { // switch off all LS channels for (uint8_t i = 0; i < sizeof(ledPins); i++) { digitalWrite(ledPins[i], LOW); } // pin change interrupt masks (see below list) //PCMSK2 |= bit (PCINT20); // pin 4 Aux button PCMSK0 |= bit (PCINT4); // pin 12 Main button // contrain the communication signals to the MP3 player to low, otherwise they will back-supply the module pinMode(DFPLAYER_RX, OUTPUT); digitalWrite(DFPLAYER_RX, LOW); pinMode(DFPLAYER_TX, OUTPUT); digitalWrite(DFPLAYER_TX, LOW); mpu.setSleepEnabled(true); Disable_MP3(true); //mpu.setSleepEnabled(true); // included as dummy, for an unknown reason if it's not here and the dfplayer.sleep() is commented out, sound is disabled //dfplayer.sleep(); delay (300); Disable_FTDI(true); sleepNow(); // sleep function called here } void SleepModeExit() { // cancel sleep as a precaution sleep_disable(); power_all_enable (); // enable modules again //digitalWrite(11,HIGH); Disable_FTDI(false); //mpu.setSleepEnabled(false); //delay (300); Disable_MP3(false); //digitalWrite(11,LOW); pinMode(DFPLAYER_RX, OUTPUT); pinMode(DFPLAYER_TX, INPUT); //delay (300); //digitalWrite(11,HIGH); setup(); // redo all initializations } #endif // DEEP_SLEEP void Disable_FTDI(bool ftdi_off) { if (ftdi_off) { // disable FTDI digitalWrite(FTDI_PSWITCH, HIGH); // disable the FTDI chip //delay (800); // cut power to FTDI, this delay is needed, the sleep //function will provoke a Serial error otherwise!! } else { // enable ftdi digitalWrite(FTDI_PSWITCH, LOW); // enable the FTDI chip //delay (800); } } void Disable_MP3(bool mp3_off) { if (mp3_off) { // disable MP3 digitalWrite(MP3_PSWITCH, HIGH); // disable the MP3 chip and the audio amp //delay (300); } else { // enable MP3 digitalWrite(MP3_PSWITCH, LOW); // enable the MP3 chip and the audio amp //delay (300); } } // ==================================================================================== // === BATTERY CHECKING FUNCTIONS === // ==================================================================================== float batCheck() { float sum = 0; // take a number of analog samples and add them up analogReference(INTERNAL); for (int i = 0; i < 10; i++) { analogRead(BATTERY_READPIN); // clear the reads after reference switch delay(1); } for (int i = 0; i < 10; i++) { sum += analogRead(BATTERY_READPIN); //Serial.println(analogRead(BATTERY_READPIN)); delay(10); } // 5.0V is the calibrated reference voltage float voltage = ((float)sum / 10 * BATTERY_FACTOR) / 1023.0; analogReference(DEFAULT); for (int i = 0; i < 10; i++) { analogRead(BATTERY_READPIN); // clear the reads after reference switch delay(1); } Serial.print(F(""Battery Level: "")); Serial.println(voltage); return voltage; // return 3.2; //temporary value for testing } void BatLevel_ConfigEnter() { #ifdef DIYINO_PRIME // int batLevel = 100 * (1 / batCheck() - 1 / LOW_BATTERY) / (1 / FULL_BATTERY - 1 / LOW_BATTERY); int batLevel = 100 * ((batCheck() - LOW_BATTERY) / (FULL_BATTERY - LOW_BATTERY)); #endif #ifdef DIYINO_STARDUST // flush out the ADC getBandgap(); getBandgap(); getBandgap(); int batLevel=((getBandgap()/37)*10); Serial.println(batLevel); #endif if (batLevel > 95) { //full SinglePlay_Sound(19); } else if (batLevel > 60) { //nominal SinglePlay_Sound(15); } else if (batLevel > 30) { //diminished SinglePlay_Sound(16); } else if (batLevel > 0) { //low SinglePlay_Sound(17); } else { //critical SinglePlay_Sound(18); } BladeMeter(ledPins, batLevel); delay(1000); } void MonitorBattery() { #ifdef DIYINO_PRIME //BatteryStatus=analogRead(BATTERY_READPIN); #endif #ifdef DIYINO_STARDUST BladeMeter(ledPins,(getBandgap()/37)*10); Serial.println(getBandgap()); #endif } // Code courtesy of ""Coding Badly"" and ""Retrolefty"" from the Arduino forum // results are Vcc * 100 // So for example, 5V would be 500. int getBandgap () { // REFS0 : Selects AVcc external reference // MUX3 MUX2 MUX1 : Selects 1.1V (VBG) ADMUX = bit (REFS0) | bit (MUX3) | bit (MUX2) | bit (MUX1); ADCSRA |= bit( ADSC ); // start conversion while (ADCSRA & bit (ADSC)) { } // wait for conversion to complete int results = (((InternalReferenceVoltage * 1024) / ADC) + 5) / 10; return results; } // end of getBandgap ",16309,True,3162.416290268935,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.controls { COMPILE::JS { import goog.events; import org.apache.royale.core.WrappedHTMLElement; import org.apache.royale.html.util.addElementToWrapper; } import mx.controls.listClasses.BaseListData; import mx.core.ITextInput; import mx.core.UIComponent; import mx.events.FlexEvent; import org.apache.royale.core.ITextModel; import org.apache.royale.events.Event; import org.apache.royale.html.accessories.PasswordInputBead; import org.apache.royale.html.beads.DisableBead; COMPILE::SWF { import org.apache.royale.html.beads.TextInputView; } /* import mx.managers.IFocusManager; import mx.managers.IFocusManagerComponent; import mx.managers.ISystemManager; import mx.managers.SystemManager; import mx.styles.ISimpleStyleClient; use namespace mx_internal; */ //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when text in the TextInput control changes * through user input. * This event does not occur if you use data binding or * ActionScript code to change the text. * *

Even though the default value of the Event.bubbles property * is true, this control dispatches the event with * the Event.bubbles property set to false.

* * @eventType flash.events.Event.CHANGE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""change"", type=""flash.events.Event"")] /** * Dispatched when the data property changes. * *

When you use a component as an item renderer, * the data property contains the data to display. * You can listen for this event and update the component * when the data property changes.

* * @eventType mx.events.FlexEvent.DATA_CHANGE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dataChange"", type=""mx.events.FlexEvent"")] /** * Dispatched when the user presses the Enter key. * * @eventType mx.events.FlexEvent.ENTER * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""enter"", type=""mx.events.FlexEvent"")] /** * Dispatched when the user types, deletes, or pastes text into the control. * No event is dispatched when the user presses the Delete key, or Backspace key. * *

Even though the default value of the TextEvent.bubbles property * is true, this control dispatches the event with * the TextEvent.bubbles property set to false.

* * @eventType flash.events.TextEvent.TEXT_INPUT * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""textInput"", type=""flash.events.TextEvent"")] //-------------------------------------- // Other metadata //-------------------------------------- [DefaultBindingProperty(source=""text"", destination=""text"")] [DefaultTriggerEvent(""change"")] /** * The TextInput control is a single-line text field * that is optionally editable. * All text in this control must use the same styling * unless it is HTML text. * The TextInput control supports the HTML rendering * capabilities of Flash Player and AIR. * *

TextInput controls do not include a label, although you * can add one by using a Label control or by nesting the * TextInput control in a FormItem control in a Form container. * When used in a FormItem control, a TextInput control * indicates whether a value is required. * TextInput controls have a number of states, including filled, * selected, disabled, and error. * TextInput controls support formatting, validation, and keyboard * equivalents; they also dispatch change and enter events.

* *

If you disable a TextInput control, it displays its contents * in the color specified by the disabledColor * style. * To disallow editing the text, you set the editable * property to false. * To conceal the input text by displaying asterisks instead of the * characters entered, you set the displayAsPassword property * to true.

* *

The TextInput control is used as a subcomponent in several other controls, * such as the RichTextEditor, NumericStepper, and ComboBox controls. As a result, * if you assign style properties to a TextInput control by using a CSS type selector, * Flex applies those styles to the TextInput when it appears in the other controls * unless you explicitly override them.

* *

The TextInput control has the following default sizing characteristics:

* * * * * * * * * * * * * * * * * *
CharacteristicDescription
Default sizeThe size of the text with a default minimum size of 22 pixels high and 160 pixels wide
Minimum size0 pixels
Maximum size10000 by 10000 pixels
* * @mxml * *

The <mx:TextInput> tag inherits the attributes * of its superclass and adds the following attributes:

* *
 *  <mx:TextInput
 *    Properties
 *    condenseWhite=""false|true""
 *    data=""undefined""
 *    displayAsPassword=""false|true""
 *    editable=""true|false""
 *    horizontalScrollPosition=""0""
 *    htmlText=""""
 *    imeMode=""null""
 *    length=""0""
 *    listData=""null""
 *    maxChars=""0""
 *    parentDrawsFocus=""false""
 *    restrict=""null""
 *    selectionBeginIndex=""0""
 *    selectionEndIndex=""0""
 *    text=""""
 *    textHeight=""0""
 *    textWidth=""0""
 *     
 *    Styles
 *    backgroundAlpha=""1.0""
 *    backgroundColor=""undefined""
 *    backgroundImage=""undefined""
 *    backgroundSize=""auto""
 *    borderColor=""0xAAB3B3""
 *    borderSides=""left top right bottom""
 *    borderSkin=""mx.skins.halo.HaloBorder""
 *    borderStyle=""inset""
 *    borderThickness=""1""
 *    color=""0x0B333C""
 *    cornerRadius=""0""
 *    disabledColor=""0xAAB3B3""
 *    dropShadowColor=""0x000000""
 *    dropShadowEnabled=""false""
 *    focusAlpha=""0.5""
 *    focusRoundedCorners""tl tr bl br""
 *    fontAntiAliasType=""advanced|normal""
 *    fontFamily=""Verdana""
 *    fontGridFitType=""pixel|none|subpixel""
 *    fontSharpness=""0""
 *    fontSize=""10""
 *    fontStyle=""normal|italic""
 *    fontThickness=""0""
 *    fontWeight=""normal|bold""
 *    paddingLeft=""0""
 *    paddingRight=""0""
 *    shadowDirection=""center""
 *    shadowDistance=""2""
 *    textAlign=""left|right|center""
 *    textDecoration=""none|underline""
 *    textIndent=""0""
 *     
 *    Events
 *    change=""No default""
 *    dataChange=""No default""
 *    enter=""No default""
 *    textInput=""No default""
 *  />
 *  
* * @includeExample examples/TextInputExample.mxml * * @see mx.controls.Label * @see mx.controls.Text * @see mx.controls.TextArea * @see mx.controls.RichTextEditor * @see mx.controls.textClasses.TextRange * * @helpid 3188 * @tiptext TextInput is a single-line, editable text field. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class TextInput extends UIComponent implements ITextInput { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function TextInput() { super(); typeNames = ""TextInput""; COMPILE::SWF { model.addEventListener(""textChange"", textChangeHandler); } } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Flag that will block default data/listData behavior. */ private var textSet:Boolean; /** * @private */ private var selectionChanged:Boolean = false; /** * @private */ private var errorCaught:Boolean = false; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // enabled //---------------------------------- /** * @private */ private var enabledChanged:Boolean = false; private var _disableBead:DisableBead; [Inspectable(category=""General"", enumeration=""true,false"", defaultValue=""true"")] /** * @private * Disable TextField when we're disabled. */ override public function set enabled(value:Boolean):void { if (value == enabled) return; super.enabled = value; // enabledChanged = true; // // invalidateProperties(); // // if (border && border is IInvalidating) // IInvalidating(border).invalidateDisplayList(); if (_disableBead == null) { _disableBead = new DisableBead(); addBead(_disableBead); } _disableBead.disabled = !value; COMPILE::SWF { var textView:TextInputView = view as TextInputView; textView.textField.mouseEnabled = super.enabled; } } //---------------------------------- // tabIndex //---------------------------------- /** * @private * Storage for the tabIndex property. */ private var _tabIndex:int = -1; /** * @private */ private var tabIndexChanged:Boolean = false; /** * @private * Tab order in which the control receives the focus when navigating * with the Tab key. * * @default -1 * @tiptext tabIndex of the component * @helpid 3198 */ // override public function get tabIndex():int // { // return _tabIndex; // } /** * @private */ // override public function set tabIndex(value:int):void // { // if (value == _tabIndex) // return; // // _tabIndex = value; // tabIndexChanged = true; // // invalidateProperties(); // } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // borderVisible //---------------------------------- public function get borderVisible():Boolean { return true; } public function set borderVisible(value:Boolean) :void { } //---------------------------------- // data //---------------------------------- /** * @private * Storage for the data property. */ private var _data:Object; [Bindable(""dataChange"")] [Inspectable(environment=""none"")] /** * Lets you pass a value to the component * when you use it in an item renderer or item editor. * You typically use data binding to bind a field of the data * property to a property of this component. * *

When you use the control as a drop-in item renderer or drop-in * item editor, Flex automatically writes the current value of the item * to the text property of this control.

* *

You do not set this property in MXML.

* * @default null * @see mx.core.IDataRenderer * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get data():Object { return _data; } /** * @private */ public function set data(value:Object):void { var newText:*; _data = value; if (_listData) { newText = _listData.label; } else if (_data != null) { if (_data is String) newText = String(_data); else newText = _data.toString(); } if (newText !== undefined && !textSet) { text = newText; textSet = false; // changing text should trigger the TextInput's view bead to change the display. //textField.setSelection(0, 0); } dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE)); } //---------------------------------- // displayAsPassword //---------------------------------- /** * @private * Storage for the displayAsPassword property. */ private var _displayAsPassword:Boolean = false; /** * @private */ private var _passwordBead:PasswordInputBead; private var displayAsPasswordChanged:Boolean = false; [Bindable(""displayAsPasswordChanged"")] [Inspectable(category=""General"", defaultValue=""false"")] /** * Indicates whether this control is used for entering passwords. * If true, the field does not display entered text, * instead, each text character entered into the control * appears as the character ""*"". * * @default false * @tiptext Specifies whether to display '*' * instead of the actual characters * @helpid 3197 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get displayAsPassword():Boolean { return _displayAsPassword; } /** * @private */ public function set displayAsPassword(value:Boolean):void { if (value == _displayAsPassword) return; _displayAsPassword = value; // displayAsPasswordChanged = true; // // invalidateProperties(); // invalidateSize(); // invalidateDisplayList();; if (_displayAsPassword && _passwordBead == null) { _passwordBead = new PasswordInputBead(); addBead(_passwordBead); } else if (!_displayAsPassword && _passwordBead != null) { removeBead(_passwordBead); _passwordBead = null; } dispatchEvent(new Event(""displayAsPasswordChanged"")); } //---------------------------------- // editable //---------------------------------- /** * @private * Storage for the editable property. */ private var _editable:Boolean = true; /** * @private */ private var editableChanged:Boolean = false; [Bindable(""editableChanged"")] [Inspectable(category=""General"", defaultValue=""true"")] /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get editable():Boolean { return _editable; } /** * @private */ public function set editable(value:Boolean):void { if (value == _editable) return; _editable = value; editableChanged = true; invalidateProperties(); dispatchEvent(new Event(""editableChanged"")); } //---------------------------------- // horizontalScrollPosition //---------------------------------- /** * @private * Used to store the init time value if any. */ private var _horizontalScrollPosition:Number = 0; /** * @private */ private var horizontalScrollPositionChanged:Boolean = false; [Bindable(""horizontalScrollPositionChanged"")] [Inspectable(defaultValue=""0"")] /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get horizontalScrollPosition():Number { return _horizontalScrollPosition; } /** * @private */ public function set horizontalScrollPosition(value:Number):void { if (value == _horizontalScrollPosition) return; _horizontalScrollPosition = value; horizontalScrollPositionChanged = true; invalidateProperties(); dispatchEvent(new Event(""horizontalScrollPositionChanged"")); } //---------------------------------- // htmlText //---------------------------------- /** * @private * Storage for the htmlText property. * In addition to being set in the htmlText setter, * it is automatically updated at two other times. * 1. When the 'text' or 'htmlText' is pushed down into * the textField in commitProperties(), this causes * the textField to update its own 'htmlText'. * Therefore in commitProperties() we reset this storage var * to be in sync with the textField. * 2. When the TextFormat of the textField changes * because a CSS style has changed (see validateNow() * in UITextField), the textField also updates its own 'htmlText'. * Therefore in textField_textFieldStyleChangeHandler() */ private var _htmlText:String = """"; /** * @private */ private var htmlTextChanged:Boolean = false; /** * @private * The last value of htmlText that was set. * We have to keep track of this because when you set the htmlText * of a TextField and read it back, you don't get what you set. * In general it will have additional HTML markup corresponding * to the defaultTextFormat set from the CSS styles. * If this var is null, it means that 'text' rather than 'htmlText' * was last set. */ private var explicitHTMLText:String = null; [Bindable(""htmlTextChanged"")] [CollapseWhiteSpace] [Inspectable(category=""General"", defaultValue="""")] [NonCommittingChangeEvent(""change"")] /** * Specifies the text displayed by the TextInput control, including HTML markup that * expresses the styles of that text. * When you specify HTML text in this property, you can use the subset of HTML * tags that is supported by the Flash TextField control. * *

When you set this property, the HTML markup is applied * after the CSS styles for the TextInput instance are applied. * When you get this property, the HTML markup includes * the CSS styles.

* *

For example, if you set this to be a string such as, * ""This is an example of <b>bold</b> markup"", * the text ""This is an example of bold markup"" appears * in the TextInput with whatever CSS styles normally apply. * Also, the word ""bold"" appears in boldface font because of the * <b> markup.

* *

HTML markup uses characters such as < and >, * which have special meaning in XML (and therefore in MXML). So, * code such as the following does not compile:

* *
     *  <mx:TextInput htmlText=""This is an example of <b>bold</b> markup""/>
     *  
* *

There are three ways around this problem.

* *
    * *
  • * *

    Set the htmlText property in an ActionScript method called as * an initialize handler:

    * *
         *  <mx:TextInput id=""myTextInput"" initialize=""myTextInput_initialize()""/>
         *  
    * *

    where the myTextInput_initialize method is in a script CDATA section:

    * *
         *  <fx:Script>
         *  <![CDATA[
         *  private function myTextInput_initialize():void {
         *      myTextInput.htmlText = ""This is an example of <b>bold</b> markup"";
         *  }
         *  ]]>
         *  </fx:Script>
         *
         *  
    * *

    This is the simplest approach because the HTML markup * remains easily readable. * Notice that you must assign an id to the TextInput * so you can refer to it in the initialize * handler.

    * *
  • * *
  • * *

    Specify the htmlText property by using a child tag * with a CDATA section. A CDATA section in XML contains character data * where characters like < and > aren't given a special meaning.

    * *
         *  <mx:TextInput>
         *      <mx:htmlText><![CDATA[This is an example of <b>bold</b> markup]]></mx:htmlText>
         *  <mx:TextInput/>
         *  
    * *

    You must write the htmlText property as a child tag * rather than as an attribute on the <mx:TextInput> tag * because XML doesn't allow CDATA for the value of an attribute. * Notice that the markup is readable, but the CDATA section makes * this approach more complicated.

    * *
  • * *
  • * *

    Use an hmtlText attribute where any occurences * of the HTML markup characters < and > in the attribute value * are written instead as the XML ""entities"" &lt; * and &gt;:

    * *
         *  <mx:TextInput htmlText=""This is an example of &lt;b&gt;bold&lt;/b&gt; markup""/&gt;
         *  
    * * Adobe does not recommend this approach because the HTML markup becomes * nearly impossible to read. * *
  • * *
* *

If the condenseWhite property is true * when you set the htmlText property, multiple * white-space characters are condensed, as in HTML-based browsers; * for example, three consecutive spaces are displayed * as a single space. * The default value for condenseWhite is * false, so you must set condenseWhite * to true to collapse the white space.

* *

If you read back the htmlText property quickly * after setting it, you get the same string that you set. * However, after the LayoutManager runs, the value changes * to include additional markup that includes the CSS styles.

* *

Setting the htmlText property affects the text * property in several ways. * If you read the text property quickly after setting * the htmlText property, you get null, * which indicates that the text corresponding to the new * htmlText has not yet been determined. * However, after the LayoutManager runs, the text property * value changes to the htmlText string with all the * HTML markup removed; that is, * the value is the characters that the TextInput actually displays.

* *

Conversely, if you set the text property, * any previously set htmlText is irrelevant. * If you read the htmlText property quickly after setting * the text property, you get null, * which indicates that the htmlText that corresponds to the new * text has not yet been determined. * However, after the LayoutManager runs, the htmlText property * value changes to the new text plus the HTML markup for the CSS styles.

* *

To make the LayoutManager run immediately, you can call the * validateNow() method on the TextInput. * For example, you could set some htmlText, * call the validateNow() method, and immediately * obtain the corresponding text that doesn't have * the HTML markup.

* *

If you set both text and htmlText properties * in ActionScript, whichever is set last takes effect. * Do not set both in MXML, because MXML does not guarantee that * the properties of an instance get set in any particular order.

* *

Setting either text or htmlText property * inside a loop is a fast operation, because the underlying TextField * that actually renders the text is not updated until * the LayoutManager runs.

* *

If you try to set this property to null, * it is set, instead, to the empty string. * If the property temporarily has the value null, * it indicates that the text has been recently set * and the corresponding htmlText * has not yet been determined.

* * @default """" * * @see flash.text.TextField#htmlText * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get htmlText():String { COMPILE::SWF { return ITextModel(model).html; } COMPILE::JS { return (element as HTMLInputElement).value; } } /** * @private */ public function set htmlText(value:String):void { COMPILE::SWF { ITextModel(model).html = value; } COMPILE::JS { (element as HTMLInputElement).value = value; dispatchEvent(new Event('textChange')); } } //---------------------------------- // isHTML //---------------------------------- /** * @private */ private function get isHTML():Boolean { return explicitHTMLText != null; } //---------------------------------- // length //---------------------------------- /** * The number of characters of text displayed in the TextArea. * * @default 0 * @tiptext The number of characters in the TextInput. * @helpid 3192 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get length():int { return text != null ? text.length : -1; } //---------------------------------- // listData //---------------------------------- private var _listData:BaseListData; [Bindable(""dataChange"")] [Inspectable(environment=""none"")] /** * When a component is used as a drop-in item renderer or drop-in * item editor, Flex initializes the listData property * of the component with the appropriate data from the list control. * The component can then use the listData property * to initialize the data property of the drop-in * item renderer or drop-in item editor. * *

You do not set this property in MXML or ActionScript; * Flex sets it when the component is used as a drop-in item renderer * or drop-in item editor.

* * @default null * @see mx.controls.listClasses.IDropInListItemRenderer * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get listData():BaseListData { return _listData; } /** * @private */ public function set listData(value:BaseListData):void { _listData = value; } //---------------------------------- // maxChars //---------------------------------- /** * @private * Storage for the maxChars property. */ private var _maxChars:int = 0; /** * @private */ private var maxCharsChanged:Boolean = false; [Bindable(""maxCharsChanged"")] [Inspectable(category=""General"", defaultValue=""0"")] /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get maxChars():int { return _maxChars; } /** * @private */ public function set maxChars(value:int):void { if (value == _maxChars) return; _maxChars = value; maxCharsChanged = true; invalidateProperties(); dispatchEvent(new Event(""maxCharsChanged"")); } //---------------------------------- // maxHorizontalScrollPosition //---------------------------------- /** * @private * Maximum value of horizontalScrollPosition. * *

The default value is 0, which means that horizontal scrolling is not * required.

* *

The value of the maxHorizontalScrollPosition property is * computed from the data and size of component, and must not be set by * the application code.

*/ public function get maxHorizontalScrollPosition():Number { return 0;//textField ? textField.maxScrollH : 0; } //---------------------------------- // parentDrawsFocus //---------------------------------- /** * @private * Storage for the parentDrawsFocus property. */ private var _parentDrawsFocus:Boolean = false; [Inspectable(category=""General"", enumeration=""true,false"", defaultValue=""false"")] /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get parentDrawsFocus():Boolean { return _parentDrawsFocus; } /** * @private */ public function set parentDrawsFocus(value:Boolean):void { _parentDrawsFocus = value; } //---------------------------------- // restrict //---------------------------------- /** * @private * Storage for the restrict property. */ private var _restrict:String; /** * @private */ private var restrictChanged:Boolean = false; [Bindable(""restrictChanged"")] [Inspectable(category=""General"")] /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get restrict():String { return _restrict; } /** * @private */ public function set restrict(value:String):void { if (value == _restrict) return; _restrict = value; restrictChanged = true; invalidateProperties(); dispatchEvent(new Event(""restrictChanged"")); } //---------------------------------- // selectable //---------------------------------- /** * @private * Used to make TextInput function correctly in the components that use it * as a subcomponent. ComboBox, at this point. */ private var _selectable:Boolean = true; /** * @private */ private var selectableChanged:Boolean = false; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectable():Boolean { return _selectable; } /** * @private */ public function set selectable(value:Boolean):void { if (_selectable == value) return; _selectable = value; selectableChanged = true; invalidateProperties(); } //---------------------------------- // selectionBeginIndex //---------------------------------- /** * @private * Storage for the selectionBeginIndex property. */ private var _selectionBeginIndex:int = 0; [Inspectable(defaultValue=""0"")] /** * The zero-based character index value of the first character * in the current selection. * For example, the first character is 0, the second character is 1, * and so on. * When the control gets the focus, the selection is visible if the * selectionBeginIndex and selectionEndIndex * properties are both set. * * @default 0 * * @tiptext The zero-based index value of the first character * in the selection. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectionBeginIndex():int { return _selectionBeginIndex; } /** * @private */ public function set selectionBeginIndex(value:int):void { _selectionBeginIndex = value; } //---------------------------------- // selectionEndIndex //---------------------------------- /** * @private * Storage for the selectionEndIndex property. */ private var _selectionEndIndex:int = 0; [Inspectable(defaultValue=""0"")] /** * The zero-based index of the position after the last character * in the current selection (equivalent to the one-based index of the last * character). * If the last character in the selection, for example, is the fifth * character, this property has the value 5. * When the control gets the focus, the selection is visible if the * selectionBeginIndex and selectionEndIndex * properties are both set. * * @default 0 * * @tiptext The zero-based index value of the last character * in the selection. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectionEndIndex():int { return _selectionEndIndex; } /** * @private */ public function set selectionEndIndex(value:int):void { _selectionEndIndex = value; selectionChanged = true; invalidateProperties(); } //---------------------------------- // text //---------------------------------- /** * @private */ private var textChanged:Boolean = false; [Bindable(""textChanged"")] [CollapseWhiteSpace] [Inspectable(category=""General"", defaultValue="""")] [NonCommittingChangeEvent(""change"")] /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 * @royaleignorecoercion HTMLInputElement */ public function get text():String { COMPILE::SWF { return ITextModel(model).text; } COMPILE::JS { return (element as HTMLInputElement).value; } } /** * @private */ public function set text(value:String):void { COMPILE::SWF { inSetter = true; ITextModel(model).text = value; inSetter = false; } COMPILE::JS { (element as HTMLInputElement).value = value; dispatchEvent(new Event('textChange')); } dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private * Create child objects. */ override protected function createChildren():void { super.createChildren(); } /** * @private */ override protected function commitProperties():void { super.commitProperties(); // if (hasFontContextChanged() && textField != null) // { // var childIndex:int = getChildIndex(DisplayObject(textField)); // removeTextField(); // createTextField(childIndex); // // accessibilityPropertiesChanged = true; // condenseWhiteChanged = true; // displayAsPasswordChanged = true; // enabledChanged = true; // maxCharsChanged = true; // restrictChanged = true; // tabIndexChanged = true; // textChanged = true; // selectionChanged = true; // horizontalScrollPositionChanged = true; // } // // if (accessibilityPropertiesChanged) // { // textField.accessibilityProperties = _accessibilityProperties; // // accessibilityPropertiesChanged = false; // } // // if (condenseWhiteChanged) // { // textField.condenseWhite = _condenseWhite; // // condenseWhiteChanged = false; // } // // if (displayAsPasswordChanged) // { // textField.displayAsPassword = _displayAsPassword; // // displayAsPasswordChanged = false; // } // // if (enabledChanged || editableChanged) // { // textField.type = enabled && _editable ? // TextFieldType.INPUT : // TextFieldType.DYNAMIC; // // if (enabledChanged) // { // if (textField.enabled != enabled) // textField.enabled = enabled; // // enabledChanged = false; // } // selectableChanged = true; // editableChanged = false; // } // // if (selectableChanged) // { // if (_editable) // textField.selectable = enabled; // else // textField.selectable = enabled && _selectable; // selectableChanged = false; // } // // if (maxCharsChanged) // { // textField.maxChars = _maxChars; // // maxCharsChanged = false; // } // // if (restrictChanged) // { // textField.restrict = _restrict; // // restrictChanged = false; // } // // if (tabIndexChanged) // { // textField.tabIndex = _tabIndex; // // tabIndexChanged = false; // } // // if (textChanged || htmlTextChanged) // { // // If the 'text' and 'htmlText' properties have both changed, // // the last one set wins. // if (isHTML) // textField.htmlText = explicitHTMLText; // else // textField.text = _text; // // textFieldChanged(false, true); // // textChanged = false; // htmlTextChanged = false; // } // // if (selectionChanged) // { // textField.setSelection(_selectionBeginIndex, _selectionEndIndex); // // selectionChanged = false; // } // // if (horizontalScrollPositionChanged) // { // textField.scrollH = _horizontalScrollPosition; // // horizontalScrollPositionChanged = false; // } } /** * @private */ override protected function measure():void { super.measure(); trace(""TextInput.measure not implemented""); // var bm:EdgeMetrics = border && border is IRectangularBorder ? // IRectangularBorder(border).borderMetrics : // EdgeMetrics.EMPTY; // // var w:Number; // var h:Number; // // // Start with a width of 160. This may change. // measuredWidth = DEFAULT_MEASURED_WIDTH; // // if (maxChars) // { // // Use the width of ""W"" and multiply by the maxChars // measuredWidth = Math.min(measuredWidth, // measureText(""W"").width * maxChars + bm.left + bm.right + 8); // } // // if (!text || text == """") // { // w = DEFAULT_MEASURED_MIN_WIDTH; // h = measureText("" "").height + // bm.top + bm.bottom + UITextField.TEXT_HEIGHT_PADDING; // h += getStyle(""paddingTop"") + getStyle(""paddingBottom""); // } // else // { // var lineMetrics:TextLineMetrics; // lineMetrics = measureText(text); // // w = lineMetrics.width + bm.left + bm.right + 8; // h = lineMetrics.height + bm.top + bm.bottom + UITextField.TEXT_HEIGHT_PADDING; // // w += getStyle(""paddingLeft"") + getStyle(""paddingRight""); // h += getStyle(""paddingTop"") + getStyle(""paddingBottom""); // } // // measuredWidth = Math.max(w, measuredWidth); // measuredHeight = Math.max(h, DEFAULT_MEASURED_HEIGHT); // // measuredMinWidth = DEFAULT_MEASURED_MIN_WIDTH; // measuredMinHeight = DEFAULT_MEASURED_MIN_HEIGHT; } /** * @private * Stretch the border and fit the TextField inside it. */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); trace(""TextInput.updateDisplayList not implemented""); // var bm:EdgeMetrics; // // if (border) // { // border.setActualSize(unscaledWidth, unscaledHeight); // bm = border is IRectangularBorder ? // IRectangularBorder(border).borderMetrics : EdgeMetrics.EMPTY; // } // else // { // bm = EdgeMetrics.EMPTY; // } // // var paddingLeft:Number = getStyle(""paddingLeft""); // var paddingRight:Number = getStyle(""paddingRight""); // var paddingTop:Number = getStyle(""paddingTop""); // var paddingBottom:Number = getStyle(""paddingBottom""); // var widthPad:Number = bm.left + bm.right; // var heightPad:Number = bm.top + bm.bottom + 1; // // textField.x = bm.left; // textField.y = bm.top; // // textField.x += paddingLeft; // textField.y += paddingTop; // widthPad += paddingLeft + paddingRight; // heightPad += paddingTop + paddingBottom; // // textField.width = Math.max(0, unscaledWidth - widthPad); // textField.height = Math.max(0, unscaledHeight - heightPad); } /** * @private * Focus should always be on the internal TextField. */ COMPILE::SWF override public function setFocus():void { var textView:TextInputView = view as TextInputView; textView.textField.stage.focus = textView.textField } /** * @private */ override public function styleChanged(styleProp:String):void { trace(""TextInput.styleChanged not implemented""); // var allStyles:Boolean = (styleProp == null || styleProp == ""styleName""); // // super.styleChanged(styleProp); // // // Replace the borderSkin // if (allStyles || styleProp == ""borderSkin"") // { // if (border) // { // removeChild(DisplayObject(border)); // border = null; // createBorder(); // } // } } //-------------------------------------------------------------------------- // // createElement // //-------------------------------------------------------------------------- /** * @royaleignorecoercion org.apache.royale.core.WrappedHTMLElement */ COMPILE::JS override protected function createElement():WrappedHTMLElement { addElementToWrapper(this,'input'); element.setAttribute('type', 'text'); //attach input handler to dispatch royale change event when user write in textinput //goog.events.listen(element, 'change', killChangeHandler); goog.events.listen(element, 'input', textChangeHandler); return element; } private var inSetter:Boolean; /** * dispatch change event in response to a textChange event * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function textChangeHandler(event:Event):void { if (!inSetter) dispatchEvent(new Event(Event.CHANGE)); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Creates the border for this component. * Normally the border is determined by the * borderStyle and borderSkin styles. * It must set the border property to the instance * of the border. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function createBorder():void { trace(""TextInput.createBorder not implemented""); // if (!border) // { // var borderClass:Class = getStyle(""borderSkin""); // // if (borderClass != null) // { // border = new borderClass(); // // if (border is ISimpleStyleClient) // ISimpleStyleClient(border).styleName = this; // // // Add the border behind all the children. // addChildAt(DisplayObject(border), 0); // // invalidateDisplayList(); // } // } } /** * Selects the text in the range specified by the parameters. * If the control is not in focus, the selection highlight will not show * until the control gains focus. Also, if the focus is gained by clicking * on the control, any previous selection would be lost. * If the two parameter values are the same, * the new selection is an insertion point. * * @param beginIndex The zero-based index of the first character in the * selection; that is, the first character is 0, the second character * is 1, and so on. * * @param endIndex The zero-based index of the position after * the last character in the selection (equivalent to the one-based * index of the last character). * If the parameter is 5, the last character in the selection, for * example, is the fifth character. * When the TextInput control gets the focus, the selection is visible * if the selectionBeginIndex and selectionEndIndex * properties are both set. * * @tiptext Sets a new text selection. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function setSelection(beginIndex:int, endIndex:int):void { _selectionBeginIndex = beginIndex; _selectionEndIndex = endIndex; selectionChanged = true; invalidateProperties(); } /** * @private * Setting the 'htmlText' of textField changes its 'text', * and vice versa, so afterwards doing so we call this method * to update the storage vars for various properties. * Afterwards, the TextInput's 'text', 'htmlText', 'textWidth', * and 'textHeight' are all in sync with each other * and are identical to the TextField's. */ private function textFieldChanged(styleChangeOnly:Boolean, dispatchValueCommitEvent:Boolean):void { trace(""TextInput.textFieldChanged not implemented""); // var changed1:Boolean; // var changed2:Boolean; // // if (!styleChangeOnly) // { // changed1 = _text != textField.text; // _text = textField.text; // } // // changed2 = _htmlText != textField.htmlText; // _htmlText = textField.htmlText; // // // If the 'text' property changes, trigger bindings to it // // and conditionally dispatch a 'valueCommit' event. // if (changed1) // { // dispatchEvent(new Event(""textChanged"")); // // if (dispatchValueCommitEvent) // dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); // } // // If the 'htmlText' property changes, trigger bindings to it. // if (changed2) // dispatchEvent(new Event(""htmlTextChanged"")); // // _textWidth = textField.textWidth; // _textHeight = textField.textHeight; } //-------------------------------------------------------------------------- // // ITextInput Interface // //-------------------------------------------------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectionActivePosition():int { return selectionEndIndex; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectionAnchorPosition():int { return selectionBeginIndex; } /** * Selects the text in the range specified by the parameters. Unlike * setSelection this is done immediately. * * @param anchorIndex The zero-based character index specifying the beginning * of the selection that stays fixed when the selection is extended. * * @param activeIndex The zero-based character index specifying * the end of the selection that moves when the selection is extended. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function selectRange(anchorIndex:int, activeIndex:int):void { trace(""TextInput.selectRange not implemented""); // Do it immediately. // textField.setSelection(anchorIndex, activeIndex); } //-------------------------------------------------------------------------- // // Overridden event handlers: UIComponent // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- } } ",12438,True,2580.138381792577,median "/* MPU9250 Basic Example Code by: Kris Winer date: April 1, 2014 license: Beerware - Use this code however you'd like. If you find it useful you can buy me a beer some time. Demonstrate basic MPU-9250 functionality including parameterizing the register addresses, initializing the sensor, getting properly scaled accelerometer, gyroscope, and magnetometer data out. Added display functions to allow display to on breadboard monitor. Addition of 9 DoF sensor fusion using open source Madgwick and Mahony filter algorithms. Sketch runs on the 3.3 V 8 MHz Pro Mini and the Teensy 3.1. SDA and SCL should have external pull-up resistors (to 3.3V). 10k resistors are on the EMSENSR-9250 breakout board. Hardware setup: MPU9250 Breakout --------- Arduino VDD ---------------------- 3.3V VDDI --------------------- 3.3V SDA ----------------------- A4 SCL ----------------------- A5 GND ---------------------- GND Note: The MPU9250 is an I2C sensor and uses the Arduino Wire library. Because the sensor is not 5V tolerant, we are using a 3.3 V 8 MHz Pro Mini or a 3.3 V Teensy 3.1. We have disabled the internal pull-ups used by the Wire library in the Wire.h/twi.c utility file. We are also using the 400 kHz fast I2C mode by setting the TWI_FREQ to 400000L /twi.h utility file. */ #include #include // See also MPU-9250 Register Map and Descriptions, Revision 4.0, RM-MPU-9250A-00, Rev. 1.4, 9/9/2013 for registers not listed in // above document; the MPU9250 and MPU9150 are virtually identical but the latter has a different register map // //Magnetometer Registers #define AK8963_ADDRESS 0x0C #define AK8963_WHO_AM_I 0x00 // should return 0x48 #define AK8963_INFO 0x01 #define AK8963_ST1 0x02 // data ready status bit 0 #define AK8963_XOUT_L 0x03 // data #define AK8963_XOUT_H 0x04 #define AK8963_YOUT_L 0x05 #define AK8963_YOUT_H 0x06 #define AK8963_ZOUT_L 0x07 #define AK8963_ZOUT_H 0x08 #define AK8963_ST2 0x09 // Data overflow bit 3 and data read error status bit 2 #define AK8963_CNTL 0x0A // Power down (0000), single-measurement (0001), self-test (1000) and Fuse ROM (1111) modes on bits 3:0 #define AK8963_ASTC 0x0C // Self test control #define AK8963_I2CDIS 0x0F // I2C disable #define AK8963_ASAX 0x10 // Fuse ROM x-axis sensitivity adjustment value #define AK8963_ASAY 0x11 // Fuse ROM y-axis sensitivity adjustment value #define AK8963_ASAZ 0x12 // Fuse ROM z-axis sensitivity adjustment value #define SELF_TEST_X_GYRO 0x00 #define SELF_TEST_Y_GYRO 0x01 #define SELF_TEST_Z_GYRO 0x02 #define SELF_TEST_X_ACCEL 0x0D #define SELF_TEST_Y_ACCEL 0x0E #define SELF_TEST_Z_ACCEL 0x0F #define SELF_TEST_A 0x10 #define XG_OFFSET_H 0x13 // User-defined trim values for gyroscope #define XG_OFFSET_L 0x14 #define YG_OFFSET_H 0x15 #define YG_OFFSET_L 0x16 #define ZG_OFFSET_H 0x17 #define ZG_OFFSET_L 0x18 #define SMPLRT_DIV 0x19 #define CONFIG 0x1A #define GYRO_CONFIG 0x1B #define ACCEL_CONFIG 0x1C #define ACCEL_CONFIG2 0x1D #define LP_ACCEL_ODR 0x1E #define WOM_THR 0x1F #define MOT_DUR 0x20 // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms #define ZMOT_THR 0x21 // Zero-motion detection threshold bits [7:0] #define ZRMOT_DUR 0x22 // Duration counter threshold for zero motion interrupt generation, 16 Hz rate, LSB = 64 ms #define FIFO_EN 0x23 #define I2C_MST_CTRL 0x24 #define I2C_SLV0_ADDR 0x25 #define I2C_SLV0_REG 0x26 #define I2C_SLV0_CTRL 0x27 #define I2C_SLV1_ADDR 0x28 #define I2C_SLV1_REG 0x29 #define I2C_SLV1_CTRL 0x2A #define I2C_SLV2_ADDR 0x2B #define I2C_SLV2_REG 0x2C #define I2C_SLV2_CTRL 0x2D #define I2C_SLV3_ADDR 0x2E #define I2C_SLV3_REG 0x2F #define I2C_SLV3_CTRL 0x30 #define I2C_SLV4_ADDR 0x31 #define I2C_SLV4_REG 0x32 #define I2C_SLV4_DO 0x33 #define I2C_SLV4_CTRL 0x34 #define I2C_SLV4_DI 0x35 #define I2C_MST_STATUS 0x36 #define INT_PIN_CFG 0x37 #define INT_ENABLE 0x38 #define DMP_INT_STATUS 0x39 // Check DMP interrupt #define INT_STATUS 0x3A #define ACCEL_XOUT_H 0x3B #define ACCEL_XOUT_L 0x3C #define ACCEL_YOUT_H 0x3D #define ACCEL_YOUT_L 0x3E #define ACCEL_ZOUT_H 0x3F #define ACCEL_ZOUT_L 0x40 #define TEMP_OUT_H 0x41 #define TEMP_OUT_L 0x42 #define GYRO_XOUT_H 0x43 #define GYRO_XOUT_L 0x44 #define GYRO_YOUT_H 0x45 #define GYRO_YOUT_L 0x46 #define GYRO_ZOUT_H 0x47 #define GYRO_ZOUT_L 0x48 #define EXT_SENS_DATA_00 0x49 #define EXT_SENS_DATA_01 0x4A #define EXT_SENS_DATA_02 0x4B #define EXT_SENS_DATA_03 0x4C #define EXT_SENS_DATA_04 0x4D #define EXT_SENS_DATA_05 0x4E #define EXT_SENS_DATA_06 0x4F #define EXT_SENS_DATA_07 0x50 #define EXT_SENS_DATA_08 0x51 #define EXT_SENS_DATA_09 0x52 #define EXT_SENS_DATA_10 0x53 #define EXT_SENS_DATA_11 0x54 #define EXT_SENS_DATA_12 0x55 #define EXT_SENS_DATA_13 0x56 #define EXT_SENS_DATA_14 0x57 #define EXT_SENS_DATA_15 0x58 #define EXT_SENS_DATA_16 0x59 #define EXT_SENS_DATA_17 0x5A #define EXT_SENS_DATA_18 0x5B #define EXT_SENS_DATA_19 0x5C #define EXT_SENS_DATA_20 0x5D #define EXT_SENS_DATA_21 0x5E #define EXT_SENS_DATA_22 0x5F #define EXT_SENS_DATA_23 0x60 #define MOT_DETECT_STATUS 0x61 #define I2C_SLV0_DO 0x63 #define I2C_SLV1_DO 0x64 #define I2C_SLV2_DO 0x65 #define I2C_SLV3_DO 0x66 #define I2C_MST_DELAY_CTRL 0x67 #define SIGNAL_PATH_RESET 0x68 #define MOT_DETECT_CTRL 0x69 #define USER_CTRL 0x6A // Bit 7 enable DMP, bit 3 reset DMP #define PWR_MGMT_1 0x6B // Device defaults to the SLEEP mode #define PWR_MGMT_2 0x6C #define DMP_BANK 0x6D // Activates a specific bank in the DMP #define DMP_RW_PNT 0x6E // Set read/write pointer to a specific start address in specified DMP bank #define DMP_REG 0x6F // Register in DMP from which to read or to which to write #define DMP_REG_1 0x70 #define DMP_REG_2 0x71 #define FIFO_COUNTH 0x72 #define FIFO_COUNTL 0x73 #define FIFO_R_W 0x74 #define WHO_AM_I_MPU9250 0x75 // Should return 0x71 #define XA_OFFSET_H 0x77 #define XA_OFFSET_L 0x78 #define YA_OFFSET_H 0x7A #define YA_OFFSET_L 0x7B #define ZA_OFFSET_H 0x7D #define ZA_OFFSET_L 0x7E // Using the MSENSR-9250 breakout board, ADO is set to 0 // Seven-bit device address is 110100 for ADO = 0 and 110101 for ADO = 1 #define ADO 0 #if ADO #define MPU9250_ADDRESS 0x69 // Device address when ADO = 1 #else #define MPU9250_ADDRESS 0x68 // Device address when ADO = 0 #define AK8963_ADDRESS 0x0C // Address of magnetometer #endif #define AHRS true // set to false for basic data read #define SerialDebug true // set to true to get Serial output for debugging // Set initial input parameters enum Ascale { AFS_2G = 0, AFS_4G, AFS_8G, AFS_16G }; enum Gscale { GFS_250DPS = 0, GFS_500DPS, GFS_1000DPS, GFS_2000DPS }; enum Mscale { MFS_14BITS = 0, // 0.6 mG per LSB MFS_16BITS // 0.15 mG per LSB }; // Specify sensor full scale uint8_t Gscale = GFS_500DPS; uint8_t Ascale = AFS_4G; uint8_t Mscale = MFS_16BITS; // Choose either 14-bit or 16-bit magnetometer resolution uint8_t Mmode = 0x06; // 2 for 8 Hz, 6 for 100 Hz continuous magnetometer data read float aRes, gRes, mRes; // scale resolutions per LSB for the sensors // Pin definitions int intPin = 12; // These can be changed, 2 and 3 are the Arduinos ext int pins int myLed = 13; // Set up pin 13 led for toggling int16_t accelCount[3]; // Stores the 16-bit signed accelerometer sensor output int16_t gyroCount[3]; // Stores the 16-bit signed gyro sensor output int16_t magCount[3]; // Stores the 16-bit signed magnetometer sensor output float magCalibration[3] = {0, 0, 0}, magbias[3] = {0, 0, 0}; // Factory mag calibration and mag bias float gyroBias[3] = {0, 0, 0}, accelBias[3] = {0, 0, 0}; // Bias corrections for gyro and accelerometer int16_t tempCount; // temperature raw count output float temperature; // Stores the real internal chip temperature in degrees Celsius float SelfTest[6]; // holds results of gyro and accelerometer self test // global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System) //float GyroMeasError = PI * (40.0f / 180.0f); // gyroscope measurement error in rads/s (start at 40 deg/s) //float GyroMeasDrift = PI * (0.0f / 180.0f); // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s) // There is a tradeoff in the beta parameter between accuracy and response speed. // In the original Madgwick study, beta of 0.041 (corresponding to GyroMeasError of 2.7 degrees/s) was found to give optimal accuracy. // However, with this value, the LSM9SD0 response time is about 10 seconds to a stable initial quaternion. // Subsequent changes also require a longish lag time to a stable output, not fast enough for a quadcopter or robot car! // By increasing beta (GyroMeasError) by about a factor of fifteen, the response time constant is reduced to ~2 sec // I haven't noticed any reduction in solution accuracy. This is essentially the I coefficient in a PID control sense; // the bigger the feedback coefficient, the faster the solution converges, usually at the expense of accuracy. // In any case, this is the free parameter in the Madgwick filtering and fusion scheme. //float beta = sqrt(3.0f / 4.0f) * GyroMeasError; // compute beta //float zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift; // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value //#define Kp 2.0f * 4.0f // these are the free parameters in the Mahony filter and fusion scheme, Kp for proportional feedback, Ki for integral //#define Ki 2.0f #define Kp (2.0f * 0.02f) // these are the free parameters in the Mahony filter and fusion scheme, Kp for proportional feedback, Ki for integral #define Ki (2.0f * 0.0f) uint32_t delt_t = 0; // used to control //display output rate uint32_t count = 0, sumCount = 0; // used to control //display output rate float pitch, yaw, roll; float a12, a22, a31, a32, a33; // rotation matrix coefficients for Euler angles and gravity components float deltat = 0.0f, sum = 0.0f; // integration interval for both filter schemes uint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval uint32_t Now = 0; // used to calculate integration interval float ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor data values float lin_ax, lin_ay, lin_az; // linear acceleration (acceleration with gravity component subtracted) float q[4] = {1.0f, 0.0f, 0.0f, 0.0f}; // vector to hold quaternion float eInt[3] = {0.0f, 0.0f, 0.0f}; // vector to hold integral error for Mahony method void setup() { Wire.begin(); TWBR = 12; // 400 kbit/sec I2C speed should be cahnge if use other CPU. Serial.begin(38400); // Set up the interrupt pin, its set as active high, push-pull pinMode(intPin, INPUT); digitalWrite(intPin, LOW); pinMode(myLed, OUTPUT); digitalWrite(myLed, HIGH); // Read the WHO_AM_I register, this is a good test of communication byte c = readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250); // Read WHO_AM_I register for MPU-9250 Serial.print(""MPU9250 ""); Serial.print(""I AM ""); Serial.print(c, HEX); Serial.print("" I should be ""); Serial.println(0x71, HEX); if (c == 0x73) // WHO_AM_I should always be 0x68 { Serial.println(""MPU9250 is online...""); MPU9250SelfTest(SelfTest); // Start by performing self test and reporting values Serial.print(""x-axis self test: acceleration trim within : ""); Serial.print(SelfTest[0],1); Serial.println(""% of factory value""); Serial.print(""y-axis self test: acceleration trim within : ""); Serial.print(SelfTest[1],1); Serial.println(""% of factory value""); Serial.print(""z-axis self test: acceleration trim within : ""); Serial.print(SelfTest[2],1); Serial.println(""% of factory value""); Serial.print(""x-axis self test: gyration trim within : ""); Serial.print(SelfTest[3],1); Serial.println(""% of factory value""); Serial.print(""y-axis self test: gyration trim within : ""); Serial.print(SelfTest[4],1); Serial.println(""% of factory value""); Serial.print(""z-axis self test: gyration trim within : ""); Serial.print(SelfTest[5],1); Serial.println(""% of factory value""); calibrateMPU9250(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers initMPU9250(); Serial.println(""MPU9250 initialized for active data mode....""); // Initialize device for active mode read of acclerometer, gyroscope, and temperature // Read the WHO_AM_I register of the magnetometer, this is a good test of communication byte d = readByte(AK8963_ADDRESS, AK8963_WHO_AM_I); // Read WHO_AM_I register for AK8963 Serial.print(""AK8963 ""); Serial.print(""I AM ""); Serial.print(d, HEX); Serial.print("" I should be ""); Serial.println(0x48, HEX); // Get magnetometer calibration from AK8963 ROM initAK8963(magCalibration); Serial.println(""AK8963 initialized for active data mode....""); // Initialize device for active mode read of magnetometer magcalMPU9250(magbias); Serial.println(""AK8963 mag biases (mG)""); Serial.println(magbias[0]); Serial.println(magbias[1]); Serial.println(magbias[2]); //delay(2000); // add delay to see results before serial spew of data if(SerialDebug) { // Serial.println(""Calibration values: ""); Serial.print(""X-Axis sensitivity adjustment value ""); Serial.println(magCalibration[0], 2); Serial.print(""Y-Axis sensitivity adjustment value ""); Serial.println(magCalibration[1], 2); Serial.print(""Z-Axis sensitivity adjustment value ""); Serial.println(magCalibration[2], 2); } } else { Serial.print(""Could not connect to MPU9250: 0x""); Serial.println(c, HEX); while(1) ; // Loop forever if communication doesn't happen } } void loop() { // If intPin goes high, all data registers have new data if (readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01) { // On interrupt, check if data ready interrupt readAccelData(accelCount); // Read the x/y/z adc values getAres(); // Now we'll calculate the accleration value into actual g's ax = (float)accelCount[0]*aRes;// - accelBias[0]; // get actual g value, this depends on scale being set ay = (float)accelCount[1]*aRes;// - accelBias[1]; az = (float)accelCount[2]*aRes;// - accelBias[2]; //Serial.print(""accBias: ""); Serial.print(accelBias[0]); //Serial.print(""accBias: ""); Serial.print(accelBias[1]); //Serial.print(""accBias: ""); Serial.print(accelBias[2]); readGyroData(gyroCount); // Read the x/y/z adc values getGres(); // Calculate the gyro value into actual degrees per second gx = (float)gyroCount[0]*gRes;// - gyroBias[0]; // get actual gyro value, this depends on scale being set gy = (float)gyroCount[1]*gRes;// - gyroBias[1]; gz = (float)gyroCount[2]*gRes;// - gyroBias[2]; //Serial.print(""gyroBias: ""); Serial.print(gyroBias[0]); //Serial.print(""gyroBias: ""); Serial.print(gyroBias[1]); //Serial.print(""gyroBias: ""); Serial.print(gyroBias[2]); readMagData(magCount); // Read the x/y/z adc values getMres(); //magbias[0] = +390.; // User environmental x-axis correction in milliGauss, should be automatically calculated //magbias[1] = +200.; // User environmental y-axis correction in milliGauss //magbias[2] = +100.; // User environmental z-axis correction in milliGauss // Calculate the magnetometer values in milliGauss // Include factory calibration per data sheet and user environmental corrections mx = (float)magCount[0]*mRes*magCalibration[0] - magbias[0];//*mRes*magCalibration[0]; // get actual magnetometer value, this depends on scale being set my = (float)magCount[1]*mRes*magCalibration[1] - magbias[1];//*mRes*magCalibration[1]; mz = (float)magCount[2]*mRes*magCalibration[2] - magbias[2];//*mRes*magCalibration[2]; } Now = micros(); deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update lastUpdate = Now; sum += deltat; // sum for averaging filter update rate sumCount++; // Sensors x (y)-axis of the accelerometer is aligned with the y (x)-axis of the magnetometer; // the magnetometer z-axis (+ down) is opposite to z-axis (+ up) of accelerometer and gyro! // We have to make some allowance for this orientationmismatch in feeding the output to the quaternion filter. // For the MPU-9250, we have chosen a magnetic rotation that keeps the sensor forward along the x-axis just like // in the LSM9DS0 sensor. This rotation can be modified to allow any convenient orientation convention. // This is ok by aircraft orientation standards! // Pass gyro rate as rad/s // MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, my, mx, mz); MahonyQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, my, mx, mz); if (!AHRS) { delt_t = millis() - count; if(delt_t > 500) { if(SerialDebug) { // Print acceleration values in milligs! Serial.print(""X-acceleration: ""); Serial.print(1000*ax); Serial.print("" mg ""); Serial.print(""Y-acceleration: ""); Serial.print(1000*ay); Serial.print("" mg ""); Serial.print(""Z-acceleration: ""); Serial.print(1000*az); Serial.println("" mg ""); // Print gyro values in degree/sec Serial.print(""X-gyro rate: ""); Serial.print(gx, 3); Serial.print("" degrees/sec ""); Serial.print(""Y-gyro rate: ""); Serial.print(gy, 3); Serial.print("" degrees/sec ""); Serial.print(""Z-gyro rate: ""); Serial.print(gz, 3); Serial.println("" degrees/sec""); // Print mag values in degree/sec Serial.print(""X-mag field: ""); Serial.print(mx); Serial.print("" mG ""); Serial.print(""Y-mag field: ""); Serial.print(my); Serial.print("" mG ""); Serial.print(""Z-mag field: ""); Serial.print(mz); Serial.println("" mG""); tempCount = readTempData(); // Read the adc values temperature = ((float) tempCount) / 333.87 + 21.0; // Temperature in degrees Centigrade // Print temperature in degrees Centigrade Serial.print(""Temperature is ""); Serial.print(temperature, 1); Serial.println("" degrees C""); // Print T values to tenths of s degree C } count = millis(); digitalWrite(myLed, !digitalRead(myLed)); // toggle led } } else { // Serial print and/or display at 0.5 s rate independent of data rates delt_t = millis() - count; if (delt_t > 200) { // update LCD once per half-second independent of read rate if(SerialDebug) { //Serial.print(""ax = ""); Serial.print((int)1000*ax); //Serial.print("" ay = ""); Serial.print((int)1000*ay); //Serial.print("" az = ""); Serial.print((int)1000*az); Serial.println("" mg""); //Serial.print(""gx = ""); Serial.print( gx, 2); //Serial.print("" gy = ""); Serial.print( gy, 2); //Serial.print("" gz = ""); Serial.print( gz, 2); Serial.println("" deg/s""); //Serial.print(""mx = ""); Serial.print( (int)mx ); //Serial.print("" my = ""); Serial.print( (int)my ); //Serial.print("" mz = ""); Serial.print( (int)mz ); Serial.println("" mG""); // //Serial.print(""q0 = ""); Serial.print(q[0]); //Serial.print("" qx = ""); Serial.print(q[1]); //Serial.print("" qy = ""); Serial.print(q[2]); //Serial.print("" qz = ""); Serial.println(q[3]); } // Define output variables from updated quaternion---these are Tait-Bryan angles, commonly used in aircraft orientation. // In this coordinate system, the positive z-axis is down toward Earth. // Yaw is the angle between Sensor x-axis and Earth magnetic North (or true North if corrected for local declination, looking down on the sensor positive yaw is counterclockwise. // Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative. // Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll. // These arise from the definition of the homogeneous rotation matrix constructed from quaternions. // Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be // applied in the correct order which for this configuration is yaw, pitch, and then roll. // For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links. a12 = 2.0f * (q[1] * q[2] + q[0] * q[3]); a22 = q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]; //a22 = 1-2*(q[1]*q[1]+q[2]*q[2]); a31 = 2.0f * (q[0] * q[1] + q[2] * q[3]); a32 = 2.0f * (q[0] * q[2] - q[3] * q[1]); a33 = q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]; //a33 = 1-2*(q[2]*q[2]+q[3]*q[3]); roll = atan2f(a31, a33); pitch = asinf(a32); yaw = atan2f(a12, a22); roll *= 180.0f / PI; pitch *= 180.0f / PI; yaw *= 180.0f / PI; yaw -= 8.2f; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04 -> SEOUL if(yaw < 0) yaw += 360.0f; // Ensure yaw stays between 0 and 360 lin_ax = ax + a31; lin_ay = ay + a32; lin_az = az - a33; if(SerialDebug) { //Serial.println(""Yaw, Pitch, Roll: ""); Serial.print(yaw, 2); Serial.print(""\\t""); Serial.print(pitch, 2); Serial.print(""\\t""); Serial.println(roll, 2); //Serial.print(""Grav_x, Grav_y, Grav_z: ""); //Serial.print(-a31*1000, 2); //Serial.print("", ""); //Serial.print(-a32*1000, 2); //Serial.print("", ""); //Serial.print(a33*1000, 2); Serial.println("" mg""); //Serial.print(""Lin_ax, Lin_ay, Lin_az: ""); //Serial.print(lin_ax*1000, 2); //Serial.print("", ""); //Serial.print(lin_ay*1000, 2); //Serial.print("", ""); //Serial.print(lin_az*1000, 2); Serial.println("" mg""); //Serial.print(""rate = ""); Serial.print((float)sumCount/sum, 2); Serial.println("" Hz""); } // With these settings the filter is updating at a ~145 Hz rate using the Madgwick scheme and // >200 Hz using the Mahony scheme even though the display refreshes at only 2 Hz. // The filter update rate is determined mostly by the mathematical steps in the respective algorithms, // the processor speed (8 MHz for the 3.3V Pro Mini), and the magnetometer ODR: // an ODR of 10 Hz for the magnetometer produce the above rates, maximum magnetometer ODR of 100 Hz produces // filter update rates of 36 - 145 and ~38 Hz for the Madgwick and Mahony schemes, respectively. // This is presumably because the magnetometer read takes longer than the gyro or accelerometer reads. // This filter update rate should be fast enough to maintain accurate platform orientation for // stabilization control of a fast-moving robot or quadcopter. Compare to the update rate of 200 Hz // produced by the on-board Digital Motion Processor of Invensense's MPU6050 6 DoF and MPU9150 9DoF sensors. // The 3.3 V 8 MHz Pro Mini is doing pretty well! //displaysetCursor(0, 40); //displayprint(""rt: ""); //displayprint((float) sumCount / sum, 2); //displayprint("" Hz""); //displaydisplay(); count = millis(); sumCount = 0; sum = 0; } } } //=================================================================================================================== //====== Set of useful function to access acceleration. gyroscope, magnetometer, and temperature data //=================================================================================================================== void getMres() { switch (Mscale) { // Possible magnetometer scales (and their register bit settings) are: // 14 bit resolution (0) and 16 bit resolution (1) case MFS_14BITS: mRes = 10.*4912./8190.; // Proper scale to return milliGauss break; case MFS_16BITS: mRes = 10.*4912./32760.0; // Proper scale to return milliGauss break; } } void getGres() { switch (Gscale) { // Possible gyro scales (and their register bit settings) are: // 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS (11). // Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value: case GFS_250DPS: gRes = 250.0/32768.0; break; case GFS_500DPS: gRes = 500.0/32768.0; break; case GFS_1000DPS: gRes = 1000.0/32768.0; break; case GFS_2000DPS: gRes = 2000.0/32768.0; break; } } void getAres() { switch (Ascale) { // Possible accelerometer scales (and their register bit settings) are: // 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11). // Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value: case AFS_2G: aRes = 2.0/32768.0; break; case AFS_4G: aRes = 4.0/32768.0; break; case AFS_8G: aRes = 8.0/32768.0; break; case AFS_16G: aRes = 16.0/32768.0; break; } } void readAccelData(int16_t * destination) { uint8_t rawData[6]; // x/y/z accel register data stored here readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ; destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ; } void readGyroData(int16_t * destination) { uint8_t rawData[6]; // x/y/z gyro register data stored here readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ; destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ; } void readMagData(int16_t * destination) { uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition if(readByte(AK8963_ADDRESS, AK8963_ST1) & 0x01) { // wait for magnetometer data ready bit to be set readBytes(AK8963_ADDRESS, AK8963_XOUT_L, 7, &rawData[0]); // Read the six raw data and ST2 registers sequentially into data array uint8_t c = rawData[6]; // End data read by reading ST2 register if(!(c & 0x08)) { // Check if magnetic sensor overflow set, if not then report data destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ; // Turn the MSB and LSB into a signed 16-bit value destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ; // Data stored as little Endian destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; } } } int16_t readTempData() { uint8_t rawData[2]; // x/y/z gyro register data stored here readBytes(MPU9250_ADDRESS, TEMP_OUT_H, 2, &rawData[0]); // Read the two raw data registers sequentially into data array return ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a 16-bit value } void initAK8963(float * destination) { // First extract the factory calibration for each magnetometer axis uint8_t rawData[3]; // x/y/z gyro calibration data stored here writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer delay(10); writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x0F); // Enter Fuse ROM access mode delay(10); readBytes(AK8963_ADDRESS, AK8963_ASAX, 3, &rawData[0]); // Read the x-, y-, and z-axis calibration values destination[0] = (float)(rawData[0] - 128)/256. + 1.; // Return x-axis sensitivity adjustment values, etc. destination[1] = (float)(rawData[1] - 128)/256. + 1.; destination[2] = (float)(rawData[2] - 128)/256. + 1.; writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer delay(10); // Configure the magnetometer for continuous read and highest resolution // set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register, // and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates writeByte(AK8963_ADDRESS, AK8963_CNTL, Mscale << 4 | Mmode); // Set magnetometer data resolution and sample ODR delay(10); } void initMPU9250() { // wake up device writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Clear sleep mode bit (6), enable all sensors delay(100); // Wait for all registers to reset // get stable time source writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01); // Auto select clock source to be PLL gyroscope reference if ready else delay(200); // Configure Gyro and Thermometer // Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz, respectively; // minimum delay time for this setting is 5.9 ms, which means sensor fusion update rates cannot // be higher than 1 / 0.0059 = 170 Hz // DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for both // With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!), 8 kHz, or 1 kHz writeByte(MPU9250_ADDRESS, CONFIG, 0x03); // Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV) writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04); // Use a 200 Hz rate; a rate consistent with the filter update rate // determined inset in CONFIG above // Set gyroscope full scale range // Range selects FS_SEL and GFS_SEL are 0 - 3, so 2-bit values are left-shifted into positions 4:3 uint8_t c = readByte(MPU9250_ADDRESS, GYRO_CONFIG); // get current GYRO_CONFIG register value // c = c & ~0xE0; // Clear self-test bits [7:5] c = c & ~0x03; // Clear Fchoice bits [1:0] c = c & ~0x18; // Clear GFS bits [4:3] c = c | Gscale << 3; // Set full scale range for the gyro // c =| 0x00; // Set Fchoice for the gyro to 11 by writing its inverse to bits 1:0 of GYRO_CONFIG writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c ); // Write new GYRO_CONFIG value to register // Set accelerometer full-scale range configuration c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG); // get current ACCEL_CONFIG register value // c = c & ~0xE0; // Clear self-test bits [7:5] c = c & ~0x18; // Clear AFS bits [4:3] c = c | Ascale << 3; // Set full scale range for the accelerometer writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, c); // Write new ACCEL_CONFIG register value // Set accelerometer sample rate configuration // It is possible to get a 4 kHz sample rate from the accelerometer by choosing 1 for // accel_fchoice_b bit [3]; in this case the bandwidth is 1.13 kHz c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG2); // get current ACCEL_CONFIG2 register value c = c & ~0x0F; // Clear accel_fchoice_b (bit 3) and A_DLPFG (bits [2:0]) c = c | 0x03; // Set accelerometer rate to 1 kHz and bandwidth to 41 Hz writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c); // Write new ACCEL_CONFIG2 register value // The accelerometer, gyro, and thermometer are set to 1 kHz sample rates, // but all these rates are further reduced by a factor of 5 to 200 Hz because of the SMPLRT_DIV setting // Configure Interrupts and Bypass Enable // Set interrupt pin active high, push-pull, hold interrupt pin level HIGH until interrupt cleared, // clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips // can join the I2C bus and all can be controlled by the Arduino as master writeByte(MPU9250_ADDRESS, INT_PIN_CFG, 0x22); writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x01); // Enable data ready (bit 0) interrupt delay(100); } // Function which accumulates gyro and accelerometer data after device initialization. It calculates the average // of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers. void calibrateMPU9250(float * dest1, float * dest2) { uint8_t data[12]; // data array to hold accelerometer and gyro x, y, z, data uint16_t ii, packet_count, fifo_count; int32_t gyro_bias[3] = {0, 0, 0}, accel_bias[3] = {0, 0, 0}; // reset device writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset bit; toggle reset device delay(100); // get stable time source; Auto select clock source to be PLL gyroscope reference if ready // else use the internal oscillator, bits 2:0 = 001 writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01); writeByte(MPU9250_ADDRESS, PWR_MGMT_2, 0x00); delay(200); // Configure device for bias calculation writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x00); // Disable all interrupts writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable FIFO writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Turn on internal clock source writeByte(MPU9250_ADDRESS, I2C_MST_CTRL, 0x00); // Disable I2C master writeByte(MPU9250_ADDRESS, USER_CTRL, 0x00); // Disable FIFO and I2C master modes writeByte(MPU9250_ADDRESS, USER_CTRL, 0x0C); // Reset FIFO and DMP delay(15); // Configure MPU6050 gyro and accelerometer for bias calculation writeByte(MPU9250_ADDRESS, CONFIG, 0x01); // Set low-pass filter to 188 Hz writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set sample rate to 1 kHz writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00); // Set gyro full-scale to 250 degrees per second, maximum sensitivity writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00); // Set accelerometer full-scale to 2 g, maximum sensitivity uint16_t gyrosensitivity = 131; // = 131 LSB/degrees/sec uint16_t accelsensitivity = 16384; // = 16384 LSB/g // Configure FIFO to capture accelerometer and gyro data for bias calculation writeByte(MPU9250_ADDRESS, USER_CTRL, 0x40); // Enable FIFO writeByte(MPU9250_ADDRESS, FIFO_EN, 0x78); // Enable gyro and accelerometer sensors for FIFO (max size 512 bytes in MPU-9150) delay(40); // accumulate 40 samples in 40 milliseconds = 480 bytes // At end of sample accumulation, turn off FIFO sensor read writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable gyro and accelerometer sensors for FIFO readBytes(MPU9250_ADDRESS, FIFO_COUNTH, 2, &data[0]); // read FIFO sample count fifo_count = ((uint16_t)data[0] << 8) | data[1]; packet_count = fifo_count/12;// How many sets of full gyro and accelerometer data for averaging for (ii = 0; ii < packet_count; ii++) { int16_t accel_temp[3] = {0, 0, 0}, gyro_temp[3] = {0, 0, 0}; readBytes(MPU9250_ADDRESS, FIFO_R_W, 12, &data[0]); // read data for averaging accel_temp[0] = (int16_t) (((int16_t)data[0] << 8) | data[1] ) ; // Form signed 16-bit integer for each sample in FIFO accel_temp[1] = (int16_t) (((int16_t)data[2] << 8) | data[3] ) ; accel_temp[2] = (int16_t) (((int16_t)data[4] << 8) | data[5] ) ; gyro_temp[0] = (int16_t) (((int16_t)data[6] << 8) | data[7] ) ; gyro_temp[1] = (int16_t) (((int16_t)data[8] << 8) | data[9] ) ; gyro_temp[2] = (int16_t) (((int16_t)data[10] << 8) | data[11]) ; accel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases accel_bias[1] += (int32_t) accel_temp[1]; accel_bias[2] += (int32_t) accel_temp[2]; gyro_bias[0] += (int32_t) gyro_temp[0]; gyro_bias[1] += (int32_t) gyro_temp[1]; gyro_bias[2] += (int32_t) gyro_temp[2]; } accel_bias[0] /= (int32_t) packet_count; // Normalize sums to get average count biases accel_bias[1] /= (int32_t) packet_count; accel_bias[2] /= (int32_t) packet_count; gyro_bias[0] /= (int32_t) packet_count; gyro_bias[1] /= (int32_t) packet_count; gyro_bias[2] /= (int32_t) packet_count; if(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) accelsensitivity;} // Remove gravity from the z-axis accelerometer bias calculation else {accel_bias[2] += (int32_t) accelsensitivity;} // Construct the gyro biases for push to the hardware gyro bias registers, which are reset to zero upon device startup data[0] = (-gyro_bias[0]/4 >> 8) & 0xFF; // Divide by 4 to get 32.9 LSB per deg/s to conform to expected bias input format data[1] = (-gyro_bias[0]/4) & 0xFF; // Biases are additive, so change sign on calculated average gyro biases data[2] = (-gyro_bias[1]/4 >> 8) & 0xFF; data[3] = (-gyro_bias[1]/4) & 0xFF; data[4] = (-gyro_bias[2]/4 >> 8) & 0xFF; data[5] = (-gyro_bias[2]/4) & 0xFF; // Push gyro biases to hardware registers writeByte(MPU9250_ADDRESS, XG_OFFSET_H, data[0]); writeByte(MPU9250_ADDRESS, XG_OFFSET_L, data[1]); writeByte(MPU9250_ADDRESS, YG_OFFSET_H, data[2]); writeByte(MPU9250_ADDRESS, YG_OFFSET_L, data[3]); writeByte(MPU9250_ADDRESS, ZG_OFFSET_H, data[4]); writeByte(MPU9250_ADDRESS, ZG_OFFSET_L, data[5]); // Output scaled gyro biases for display in the main program dest1[0] = (float) gyro_bias[0]/(float) gyrosensitivity; dest1[1] = (float) gyro_bias[1]/(float) gyrosensitivity; dest1[2] = (float) gyro_bias[2]/(float) gyrosensitivity; // Construct the accelerometer biases for push to the hardware accelerometer bias registers. These registers contain // factory trim values which must be added to the calculated accelerometer biases; on boot up these registers will hold // non-zero values. In addition, bit 0 of the lower byte must be preserved since it is used for temperature // compensation calculations. Accelerometer bias registers expect bias input as 2048 LSB per g, so that // the accelerometer biases calculated above must be divided by 8. int32_t accel_bias_reg[3] = {0, 0, 0}; // A place to hold the factory accelerometer trim biases readBytes(MPU9250_ADDRESS, XA_OFFSET_H, 2, &data[0]); // Read factory accelerometer trim values accel_bias_reg[0] = (int32_t) (((int16_t)data[0] << 8) | data[1]); readBytes(MPU9250_ADDRESS, YA_OFFSET_H, 2, &data[0]); accel_bias_reg[1] = (int32_t) (((int16_t)data[0] << 8) | data[1]); readBytes(MPU9250_ADDRESS, ZA_OFFSET_H, 2, &data[0]); accel_bias_reg[2] = (int32_t) (((int16_t)data[0] << 8) | data[1]); uint32_t mask = 1uL; // Define mask for temperature compensation bit 0 of lower byte of accelerometer bias registers uint8_t mask_bit[3] = {0, 0, 0}; // Define array to hold mask bit for each accelerometer bias axis for(ii = 0; ii < 3; ii++) { if((accel_bias_reg[ii] & mask)) mask_bit[ii] = 0x01; // If temperature compensation bit is set, record that fact in mask_bit } // Construct total accelerometer bias, including calculated average accelerometer bias from above accel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale) accel_bias_reg[1] -= (accel_bias[1]/8); accel_bias_reg[2] -= (accel_bias[2]/8); data[0] = (accel_bias_reg[0] >> 8) & 0xFF; data[1] = (accel_bias_reg[0]) & 0xFF; data[1] = data[1] | mask_bit[0]; // preserve temperature compensation bit when writing back to accelerometer bias registers data[2] = (accel_bias_reg[1] >> 8) & 0xFF; data[3] = (accel_bias_reg[1]) & 0xFF; data[3] = data[3] | mask_bit[1]; // preserve temperature compensation bit when writing back to accelerometer bias registers data[4] = (accel_bias_reg[2] >> 8) & 0xFF; data[5] = (accel_bias_reg[2]) & 0xFF; data[5] = data[5] | mask_bit[2]; // preserve temperature compensation bit when writing back to accelerometer bias registers // Apparently this is not working for the acceleration biases in the MPU-9250 // Are we handling the temperature correction bit properly? // Push accelerometer biases to hardware registers writeByte(MPU9250_ADDRESS, XA_OFFSET_H, data[0]); writeByte(MPU9250_ADDRESS, XA_OFFSET_L, data[1]); writeByte(MPU9250_ADDRESS, YA_OFFSET_H, data[2]); writeByte(MPU9250_ADDRESS, YA_OFFSET_L, data[3]); writeByte(MPU9250_ADDRESS, ZA_OFFSET_H, data[4]); writeByte(MPU9250_ADDRESS, ZA_OFFSET_L, data[5]); // Output scaled accelerometer biases for display in the main program dest2[0] = (float)accel_bias[0]/(float)accelsensitivity; dest2[1] = (float)accel_bias[1]/(float)accelsensitivity; dest2[2] = (float)accel_bias[2]/(float)accelsensitivity; } // Accelerometer and gyroscope self test; check calibration wrt factory settings void MPU9250SelfTest(float * destination) // Should return percent deviation from factory trim values, +/- 14 or less deviation is a pass { uint8_t rawData[6] = {0, 0, 0, 0, 0, 0}; uint8_t selfTest[6]; int32_t gAvg[3] = {0}, aAvg[3] = {0}, aSTAvg[3] = {0}, gSTAvg[3] = {0}; float factoryTrim[6]; uint8_t FS = 0; writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set gyro sample rate to 1 kHz writeByte(MPU9250_ADDRESS, CONFIG, 0x02); // Set gyro sample rate to 1 kHz and DLPF to 92 Hz writeByte(MPU9250_ADDRESS, GYRO_CONFIG, FS<<3); // Set full scale range for the gyro to 250 dps writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, 0x02); // Set accelerometer rate to 1 kHz and bandwidth to 92 Hz writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, FS<<3); // Set full scale range for the accelerometer to 2 g for( int ii = 0; ii < 200; ii++) { // get average current values of gyro and acclerometer readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array aAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value aAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ; aAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array gAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value gAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ; gAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; } for (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as average current readings aAvg[ii] /= 200; gAvg[ii] /= 200; } // Configure the accelerometer for self-test writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0xE0); // Enable self test on all three axes and set accelerometer range to +/- 2 g writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0xE0); // Enable self test on all three axes and set gyro range to +/- 250 degrees/s delay(25); // Delay a while to let the device stabilize for( int ii = 0; ii < 200; ii++) { // get average self-test values of gyro and acclerometer readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array aSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value aSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ; aSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array gSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value gSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ; gSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; } for (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as average self-test readings aSTAvg[ii] /= 200; gSTAvg[ii] /= 200; } // Configure the gyro and accelerometer for normal operation writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00); writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00); delay(25); // Delay a while to let the device stabilize // Retrieve accelerometer and gyro factory Self-Test Code from USR_Reg selfTest[0] = readByte(MPU9250_ADDRESS, SELF_TEST_X_ACCEL); // X-axis accel self-test results selfTest[1] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_ACCEL); // Y-axis accel self-test results selfTest[2] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_ACCEL); // Z-axis accel self-test results selfTest[3] = readByte(MPU9250_ADDRESS, SELF_TEST_X_GYRO); // X-axis gyro self-test results selfTest[4] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_GYRO); // Y-axis gyro self-test results selfTest[5] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_GYRO); // Z-axis gyro self-test results // Retrieve factory self-test value from self-test code reads factoryTrim[0] = (float)(2620/1< mag_max[jj]) mag_max[jj] = mag_temp[jj]; if(mag_temp[jj] < mag_min[jj]) mag_min[jj] = mag_temp[jj]; } delay(135); // at 8 Hz ODR, new mag data is available every 125 ms } //Serial.println(""mag x min/max:""); Serial.println(mag_max[0]); Serial.println(mag_min[0]); //Serial.println(""mag y min/max:""); Serial.println(mag_max[1]); Serial.println(mag_min[1]); //Serial.println(""mag z min/max:""); Serial.println(mag_max[2]); Serial.println(mag_min[2]); mag_bias[0] = (mag_max[0] + mag_min[0])/2; // get average x mag bias in counts mag_bias[1] = (mag_max[1] + mag_min[1])/2; // get average y mag bias in counts mag_bias[2] = (mag_max[2] + mag_min[2])/2; // get average z mag bias in counts dest1[0] = mag_bias[0]; dest1[1] = mag_bias[1]; dest1[2] = mag_bias[2]; //Serial.println(""dest1[0]""); Serial.println(dest1[0]); //Serial.println(""dest1[1]""); Serial.println(dest1[1]); //Serial.println(""dest1[2]""); Serial.println(dest1[2]); Serial.println(""Mag Calibration done!""); } ",16263,True,2531.187652607293,median "//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2010 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package spark.transitions { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Stage; import flash.events.Event; import flash.events.EventDispatcher; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import mx.core.FlexGlobals; import mx.core.IVisualElementContainer; import mx.core.UIComponent; import mx.core.mx_internal; import mx.effects.IEffect; import mx.effects.Parallel; import mx.events.EffectEvent; import mx.events.FlexEvent; import mx.geom.TransformOffsets; import mx.managers.SystemManager; import spark.components.ActionBar; import spark.components.Group; import spark.components.TabbedViewNavigator; import spark.components.View; import spark.components.ViewNavigator; import spark.components.supportClasses.ButtonBarBase; import spark.components.supportClasses.ViewNavigatorBase; import spark.effects.Animate; import spark.effects.Fade; import spark.effects.animation.MotionPath; import spark.effects.animation.SimpleMotionPath; import spark.effects.easing.IEaser; import spark.effects.easing.Sine; import spark.primitives.BitmapImage; import spark.utils.BitmapUtil; use namespace mx_internal; /** * Dispatched when the transition starts. * * @eventType mx.events.FlexEvent.TRANSITION_START * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""transitionStart"", type=""mx.events.FlexEvent"")] /** * Dispatched when the transition completes. * * @eventType mx.events.FlexEvent.TRANSITION_START * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""transitionEnd"", type=""mx.events.FlexEvent"")] /** * The ViewTransitionBase class is the base class for all view transitions. * It is not intended to be used as a transition on its own. * In addition to providing common convenience and helper methods used by * view transitions, this class provides a default action bar transition * sequence. * *

When a view transition is initialized, the owning view navigator * sets the startView and endView properties * to the views the transition animates. * The navigator property is * set to the view navigator.

* *

The lifecycle of a transition is as follows:

*
    *
  • The transition starts with * the captureStartValues() method. * When this method is called, the navigator is currently in the * start state. * At this time, the transition should capture any start values * or bitmaps that it requires.
  • *
  • A validation pass is performed on the pending * view, and the captureEndValues() method is called. * At this time, the transition captures any properties or * bitmaps representations from the pending view.
  • *
  • The prepareForPlay() method is then called, * which allows the transition to perform any further preparations, * such as preparing a Spark effects sequence, * or positioning transient elements on the display list.
  • *
  • After a final validation pass, if necessary, * the play() method is called by the navigator * to perform the actual transition.
  • *
  • Prior to any animation starting, the start * event is dispatched.
  • *
  • When a transition completes, it dispatches an * end event.
  • *
* *

Note:Create and configure view transitions in ActionScript; * you cannot create them in MXML.

* * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class ViewTransitionBase extends EventDispatcher { //-------------------------------------------------------------------------- // // Constants // //-------------------------------------------------------------------------- /** * Constant used in tandem with the actionBarTransitionMode property to * hint the default action bar transition behavior. */ mx_internal static const ACTION_BAR_MODE_FADE:String = ""fade""; /** * Constant used in tandem with the actionBarTransitionMode property to * hint the default action bar transition behavior. */ mx_internal static const ACTION_BAR_MODE_FADE_AND_SLIDE:String = ""fadeAndSlide""; /** * Constant used in tandem with the actionBarTransitionMode property to * hint the default action bar transition behavior. */ mx_internal static const ACTION_BAR_MODE_NONE:String = ""none""; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function ViewTransitionBase() { super(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Flag set when we've determined that we need to transition the navigator * in its entirety and cannot transition the control bars independently. */ protected var consolidatedTransition:Boolean = false; /** * @private * startView's action bar height. */ private var cachedActionBarHeight:Number; /** * @private * startView's action bar width. */ private var cachedActionBarWidth:Number; /** * @private * Transient display object used to hold temporary bitmap snapshots * during transition. */ private var transitionGroup:Group; /** * @private * Flag to assist with cleanup of any constructs used only for vertical * transitions (e.g. clipping masks). */ private var verticalTransition:Boolean; /** * @private * Flag used to determine whether the transition should wait a frame when * it receives the EFFECT_END event. This is true by default. It is only * set to false when the endTransitions() method is called. */ private static var renderLastFrame:Boolean = true; /** * @private * Private vector that stores all the active transitions. */ private static var activeTransitions:Vector. = new Vector.(); /** * @private * Ends all currently active view transitions. */ mx_internal static function endTransitions():void { // Prevent the transitions from waiting a frame when they receive the // EFFECT_END event. See effectComplete(). renderLastFrame = false; // End all active transitions. They will be removed from the vector // in transitionComplete(). for (var i:int = 0; i < activeTransitions.length; i++) activeTransitions[i].effect.end(); // Restore render flag renderLastFrame = true; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // duration //---------------------------------- private var _duration:Number = 250; /** * Duration of the transition, in milliseconds. * The default may vary depending on the transition * but is defined in ViewTransitionBase as 250 ms. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get duration():Number { return _duration; } /** * @private */ public function set duration(value:Number):void { _duration = value; } //---------------------------------- // easer //---------------------------------- private var _easer:IEaser = new Sine(.5); /** * The easing behavior for this transition. The IEaser object is * generally propagated to the IEffect instance managing the actual * transition animation. * * @default Sine(.5); * * @see spark.effects.easing * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get easer():IEaser { return _easer; } /** * @private */ public function set easer(value:IEaser):void { _easer = value; } //---------------------------------- // effect //---------------------------------- private var _effect:IEffect; /** * Provides access to the underlying IEffect instance which the * transition is using to perform the transition (if any). This property * is only valid after the FlexEvent.TRANSITION_START event even has been * dispatched. * * If a transition does not make use of IEffect to perform the transition * this can be null. * * @default null * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function get effect():IEffect { return _effect; } mx_internal function set effect(value:IEffect):void { _effect = value; } //---------------------------------- // endView //---------------------------------- private var _endView:View; /** * The view that the navigator is transitioning * to, as set by the owning ViewNavigator object. * This property can be null. * * @default null * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get endView():View { return _endView; } /** * @private */ public function set endView(value:View):void { _endView = value; } //---------------------------------- // navigator //---------------------------------- private var _navigator:ViewNavigator; /** * Reference to the owning ViewNavigator instance set by the owning * ViewNavigator. * * @default null * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get navigator():ViewNavigator { return _navigator; } /** * @private */ public function set navigator(value:ViewNavigator):void { _navigator = value; } //---------------------------------- // startView //---------------------------------- private var _startView:View; /** * The currently active view of the view navigator, * as set by the owning view navigator. * This property can be null. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get startView():View { return _startView; } /** * @private */ public function set startView(value:View):void { _startView = value; } //---------------------------------- // suspendBackgroundProcessing //---------------------------------- private var _suspendBackgroundProcessing:Boolean = true; /** * When set to true, the UIComponent.suspendBackgroundProcessing() * method is invoked prior to the transition playing. * This disables Flex's layout manager and improving performance. * Upon completion of the transition, * the layout manager function is restored by a call to the * UIComponent.resumeBackgroundProcessing() method. * * @default false * * @see mx.core.UIComponent#suspendBackgroundProcessing() * @see mx.core.UIComponent#resumeBackgroundProcessing() * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get suspendBackgroundProcessing():Boolean { return _suspendBackgroundProcessing; } /** * @private */ public function set suspendBackgroundProcessing(value:Boolean):void { _suspendBackgroundProcessing = value; } //---------------------------------- // transitionControlsWithContent //---------------------------------- private var _transitionControlsWithContent:Boolean; /** * When set to true, the primary view transition * is used to transition the view navigator in its entirety, * including the action bar. * Specific transitions for the action bar are not performed. * Because the tab bar is associated with the entire application, * and not a view, view transitions do not affect it. * *

Note that even when set to false, there are cases * where its not feasible to transition the action bar. * For example, when the action bar does not exist in one of * the two views, or if the action bar changes size.

* * @default false * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get transitionControlsWithContent():Boolean { return _transitionControlsWithContent; } /** * @private */ public function set transitionControlsWithContent(value:Boolean):void { _transitionControlsWithContent = value; } //-------------------------------------------------------------------------- // // Private Properties // //-------------------------------------------------------------------------- //---------------------------------- // actionBarTransitionMode //---------------------------------- /** * @private * Convenience property used by ViewTransitionBase overrides to hint the behavior of * the default action bar transition as appropriate for the type and nature * of the specific view transition. Can be one either ViewTransitionBase.ACTION_BAR_MODE_FADE, * ViewTransitionBase.ACTION_BAR_MODE_FADE_AND_SLIDE, or null. If set to fade * and slide, the actionBarTransitionDirection property is considered by the * default createActionBarEffect() implementation. * * @default ACTION_BAR_MODE_FADE_AND_SLIDE */ mx_internal var actionBarTransitionMode:String = ACTION_BAR_MODE_FADE_AND_SLIDE; //---------------------------------- // actionBarTransitionDirection //---------------------------------- /** * @private * Convenience property used by ViewTransitionBase overrides to hint the direction * of the default action bar transition when the actionBarTransitionMode is set to * ""fadeAndSlide"". Can be or null or set to one of the ViewTransitionDirection * constants. This property is considered by the default createActionBarEffect() * implementation. * * @default ViewTransitionDirection.LEFT */ mx_internal var actionBarTransitionDirection:String = ViewTransitionDirection.LEFT; //---------------------------------- // cachedNavigatorSnapshot //---------------------------------- /** * @private * Cached image of the cumulative view of the owning navigator * captured by the default captureStartValues() implementation. * This snapshot is generally leveraged by transitions that need to * performing a full screen transition. */ mx_internal var cachedNavigator:BitmapImage; /** * @private * Stores the location of the cached navigator in the global coordinate space * so that the transition can properly position it when added to the display list. */ mx_internal var cachedNavigatorGlobalPosition:Point = new Point(); //---------------------------------- // cachedActionGroupSnapshot //---------------------------------- /** * @private * Cached image of the action bar's action group. This image is * only captured by default if action group content exists in the * previous view. */ mx_internal var cachedActionGroup:BitmapImage; /** * @private * Stores the location of the cached navigator in the global coordinate space * so that the transition can properly position it when added to the display list. */ mx_internal var cachedActionGroupGlobalPosition:Point = new Point(); //---------------------------------- // cachedTitleGroupSnapshot //---------------------------------- /** * @private * Cached image of the action bar's title group. This image is * only captured by default if title group content exists in the * previous view. */ mx_internal var cachedTitleGroup:BitmapImage; /** * @private * Stores the location of the cached navigator in the global coordinate space * so that the transition can properly position it when added to the display list. */ mx_internal var cachedTitleGroupGlobalPosition:Point = new Point(); //---------------------------------- // cachedNavigationGroupSnapshot //---------------------------------- /** * @private * Cached image of the action bar's navigation group. This image is * only captured by default if navigation group content exists in the * previous view. */ mx_internal var cachedNavigationGroup:BitmapImage; /** * @private * Stores the location of the cached navigator in the global coordinate space * so that the transition can properly position it when added to the display list. */ mx_internal var cachedNavigationGroupGlobalPosition:Point = new Point(); //---------------------------------- // targetNavigator //---------------------------------- /** * @private * Convenience property which caches our primary containing navigator, * this is usually our owning ViewNavigator but may be an outer TabNavigator */ protected var targetNavigator:ViewNavigatorBase; //---------------------------------- // parentNavigator //---------------------------------- /** * @private * Convenience property which caches our primary containing navigator, * this is usually our owning ViewNavigator but may be an outer TabNavigator */ protected var parentNavigator:ViewNavigatorBase; //---------------------------------- // actionBar //---------------------------------- /** * @private * Convenience property which caches our associated action bar. */ protected var actionBar:ActionBar; /** * @private * Convenience property which caches our associated tab bar. */ protected var tabBar:ButtonBarBase; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- mx_internal function preInit():void { // Override } /** * Called by the ViewNavigator during the preparation phase of a transition. * It is invoked when the new view has been fully realized and validated and the * action bar and tab bar content reflect the state of the new view. * The transition can use this method capture any values it requires from the * pending view. * Any bitmaps reflecting the state of the new view, tab bar, * or action bar should be captured if required for animation. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function captureStartValues():void { // Remember some common references. parentNavigator = navigator.parentNavigator; if (parentNavigator is TabbedViewNavigator) { targetNavigator = parentNavigator; tabBar = TabbedViewNavigator(parentNavigator).tabBar; } else { targetNavigator = navigator; } if (navigator) actionBar = navigator.actionBar; // Determine first if we're able to transition our control bars independently // of our view content. If we are, then capture the necessary action bar // bitmap snapshots for use later by our default action bar transition. if (!consolidatedTransition) consolidatedTransition = !canTransitionControlBarContent(); // Snapshot component parts of action bar in preparation for our // default action bar transition, (if appropriate). if (!consolidatedTransition) { if (componentIsVisible(actionBar)) { // Save bounds of action bar. cachedActionBarWidth = actionBar.width; cachedActionBarHeight = actionBar.height; // Snapshot title content of our startView. if (actionBar.titleGroup && actionBar.titleGroup.visible) cachedTitleGroup = getSnapshot(actionBar.titleGroup, 4, cachedTitleGroupGlobalPosition); else if (actionBar.titleDisplay && (actionBar.titleDisplay is UIComponent) && UIComponent(actionBar.titleDisplay).visible) cachedTitleGroup = getSnapshot(UIComponent(actionBar.titleDisplay), 4, cachedTitleGroupGlobalPosition); // Snapshot actionContent if it's changing between our start and end views. if (startView.actionContent != endView.actionContent) cachedActionGroup = getSnapshot(actionBar.actionGroup, 4, cachedActionGroupGlobalPosition); // Snapshot navigationContent if it's changing between our start and end views. if (startView.navigationContent != endView.navigationContent) cachedNavigationGroup = getSnapshot(actionBar.navigationGroup, 4, cachedNavigationGroupGlobalPosition); } } } /** * Called by the ViewNavigator during the preparation phase of a transition. * It is invoked when the new view has been fully realized and validated and the * action bar and tab bar content reflect the state of the new view. * It is at this point that the transition can capture any values it requires from the * pending view. * In addition any bitmaps reflecting the state of the new view, tab bar, * or action bar should be captured, if required for animation. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function captureEndValues():void { // One final check to determine if we will be required to perform a full // (consolidated) transition. if (!consolidatedTransition) { consolidatedTransition = ((actionBar.height != cachedActionBarHeight) || (actionBar.width != cachedActionBarWidth)); } } /** * Called by the ViewNavigator when the transition * should begin animating. * At this time, the transition should dispatch a * start event. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function play():void { if (effect) { activeTransitions.push(this); effect.addEventListener(EffectEvent.EFFECT_END, effectComplete); // Dispatch TRANSITION_START. if (hasEventListener(FlexEvent.TRANSITION_START)) dispatchEvent(new FlexEvent(FlexEvent.TRANSITION_START)); if (navigator && navigator.stage && navigator.stage.hasEventListener(FlexEvent.TRANSITION_START)) navigator.stage.dispatchEvent(new FlexEvent(FlexEvent.TRANSITION_START)); effect.play(); } else transitionComplete(); } /** * Called by the ViewNavigator during the preparation phase * of a transition. * This method gives the transition the chance to create and * configure the underlying IEffect instance, or to add any transient * elements to the display list. * Example transient elements include bitmap placeholders, temporary * containers required during the transition, and other elements. * If required, a final validation pass occurs prior to the invocation * of the play() method. * *

If it is determined that a standard transition can be initiated, * meaning one that transitions the control bars separately from the views, * the default implementation of this method constructs * a single Parallel effect which wraps the individual effect sequences * for the view transition, the action bar transition, and the tab bar transition. * This method uses the methods, createActionBarEffect(), * createTabBarEffect(), and createViewEffect().

* *

If transitionControlsWithContent is set to true, * or if it is determined that the control bars cannot be transitioned independently, * a single effect is created to transition the navigator in its entirety. * In this case, only createConsolidatedEffect() is invoked.

* * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function prepareForPlay():void { if (!consolidatedTransition) { effect = new Parallel(); // Prepare action bar effect if (actionBar) { var actionBarEffect:IEffect = createActionBarEffect(); if (actionBarEffect) Parallel(effect).addChild(actionBarEffect); } // Prepare tab bar effect if (targetNavigator is TabbedViewNavigator) { if (TabbedViewNavigator(targetNavigator).tabBar) { var tabBarEffect:IEffect = createTabBarEffect(); if (tabBarEffect) Parallel(effect).addChild(tabBarEffect); } } // Prepare view effect var viewEffect:IEffect = createViewEffect(); if (viewEffect) Parallel(effect).addChild(viewEffect); } else { // Prepare full transition of navigator in its entirety. effect = createConsolidatedEffect(); } // Disable layout manager if requested. if (suspendBackgroundProcessing) UIComponent.suspendBackgroundProcessing(); } /** * Called by the default prepareForPlay() implementation, * this method is responsible for creating the Spark effect * played on the action bar when the transition starts. * This method should be overridden by subclasses if a custom action bar * effect is required. * By default, this method returns a basic action bar effect. * * @return An IEffect instance serving as the action bar effect. * This effect is played by the default play() method implementation. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createActionBarEffect():IEffect { var transformOffsets:TransformOffsets; var slideDistance:Number; var animatedProperty:String; var actionBarSkin:UIComponent = actionBar.skin; var slideTargets:Array = new Array(); var fadeOutTargets:Array = new Array(); var fadeInTargets:Array = new Array(); // Return if we have a noop action bar transition mode. if (!actionBar || actionBarTransitionMode == ACTION_BAR_MODE_NONE || !actionBarTransitionMode) return null; transitionGroup = new Group(); transitionGroup.autoLayout = false; transitionGroup.includeInLayout = false; transitionGroup.width = actionBar.width; transitionGroup.height = actionBar.height; addComponentToContainer(transitionGroup, actionBarSkin); // Construct our parallel effect. var actionBarEffect:Parallel = new Parallel(); // Calculate the slide distance based on direction. switch (actionBarTransitionDirection) { case ViewTransitionDirection.RIGHT: animatedProperty = ""x""; slideDistance = -actionBar.width / 2.5; break; case ViewTransitionDirection.DOWN: animatedProperty = ""y""; slideDistance = -actionBar.height / 2.5; verticalTransition = true; break; case ViewTransitionDirection.UP: animatedProperty = ""y""; slideDistance = actionBar.height / 2.5; verticalTransition = true; break; case ViewTransitionDirection.LEFT: default: animatedProperty = ""x""; slideDistance = actionBar.width / 2.5; break; } transitionGroup.clipAndEnableScrolling = true; // Suppress slide if our action bar transition behavior is fade-only. if (actionBarTransitionMode == ACTION_BAR_MODE_FADE) slideDistance = 0; // If the skin has title content queue new title content for fade in. if (actionBar.titleGroup || actionBar.titleDisplay) { var titleComponent:UIComponent = actionBar.titleGroup; if (!titleComponent || !titleComponent.visible) titleComponent = actionBar.titleDisplay as UIComponent; if (titleComponent) { // Initialize the transformation offests transformOffsets = new TransformOffsets(); transformOffsets[animatedProperty] = slideDistance; slideTargets.push(transformOffsets); // Initialize titleGroup titleComponent.cacheAsBitmap = true; titleComponent.alpha = 0; titleComponent.postLayoutTransformOffsets = transformOffsets; fadeInTargets.push(titleComponent); // We reparent the titleComponent into the transition group so // that the items are properly clipped when animating vertically if (verticalTransition) transitionGroup.addElementAt(titleComponent, 0); } if (cachedTitleGroup) addCachedElementToGroup(transitionGroup, cachedTitleGroup, cachedTitleGroupGlobalPosition); } // If a cache of the navigation group exists, that means the content // changed. In this case the queue cached representation to be faded // out. if (cachedNavigationGroup) addCachedElementToGroup(transitionGroup, cachedNavigationGroup, cachedNavigationGroupGlobalPosition); // If a cache of the action group exists, that means the content // changed. In this case the queue cached representation to be faded // out. if (cachedActionGroup) addCachedElementToGroup(transitionGroup, cachedActionGroup, cachedActionGroupGlobalPosition); // Create fade in animations for navigationContent and actionContent // of the next view. if (endView) { if (endView.navigationContent) { // Initialize the transformation offests transformOffsets = new TransformOffsets(); transformOffsets[animatedProperty] = slideDistance; slideTargets.push(transformOffsets); actionBar.navigationGroup.postLayoutTransformOffsets = transformOffsets; actionBar.navigationGroup.cacheAsBitmap = true; actionBar.navigationGroup.alpha = 0; fadeInTargets.push(actionBar.navigationGroup); // We reparent the titleComponent into the transition group so // that the items are properly clipped when animating vertically if (verticalTransition) transitionGroup.addElementAt(actionBar.navigationGroup, 0); } if (endView.actionContent) { // Initialize the transformation offests transformOffsets = new TransformOffsets(); transformOffsets[animatedProperty] = slideDistance; slideTargets.push(transformOffsets); actionBar.actionGroup.postLayoutTransformOffsets = transformOffsets; actionBar.actionGroup.cacheAsBitmap = true; actionBar.actionGroup.alpha = 0; fadeInTargets.push(actionBar.actionGroup); // We reparent the titleComponent into the transition group so // that the items are properly clipped when animating vertically if (verticalTransition) transitionGroup.addElementAt(actionBar.actionGroup, 0); } } // Ensure bitmaps are rendered prior to invocation of our effect. transitionGroup.validateNow(); // Setup fade out targets if (cachedTitleGroup) { // Initialize the transformation offests transformOffsets = new TransformOffsets(); slideTargets.push(transformOffsets); cachedTitleGroup.postLayoutTransformOffsets = transformOffsets; fadeOutTargets.push(cachedTitleGroup.displayObject); } if (cachedNavigationGroup) { // Initialize the transformation offests transformOffsets = new TransformOffsets(); slideTargets.push(transformOffsets); cachedNavigationGroup.postLayoutTransformOffsets = transformOffsets; fadeOutTargets.push(cachedNavigationGroup.displayObject); } if (cachedActionGroup) { // Initialize the transformation offests transformOffsets = new TransformOffsets(); slideTargets.push(transformOffsets); cachedActionGroup.postLayoutTransformOffsets = transformOffsets; fadeOutTargets.push(cachedActionGroup.displayObject); } // If no fade effects we aren't animating anything so return null if (fadeInTargets.length == 0 && fadeOutTargets.length == 0) return null; // Create fade in effect if (fadeInTargets.length > 0) { var fadeInEffect:Fade = new Fade(); fadeInEffect.targets = fadeInTargets; fadeInEffect.duration = duration; fadeInEffect.alphaFrom = 0; fadeInEffect.alphaTo = 1; actionBarEffect.addChild(fadeInEffect); } // Create fade out effect if (fadeOutTargets.length > 0) { var fadeOutEffect:Fade = new Fade(); fadeOutEffect.targets = fadeOutTargets; fadeOutEffect.duration = duration; fadeOutEffect.alphaFrom = 1; fadeOutEffect.alphaTo = 0; actionBarEffect.addChild(fadeOutEffect); } // Create slide in effect var vector:Vector. = new Vector.(); vector.push(new SimpleMotionPath(animatedProperty, null, null, -slideDistance)); var moveEffect:Animate = new Animate(); moveEffect.targets = slideTargets; moveEffect.motionPaths = vector; moveEffect.easer = new spark.effects.easing.Sine(.7); moveEffect.duration = duration; moveEffect.addEventListener(EffectEvent.EFFECT_UPDATE, actionBarMoveEffect_effectUpdateHandler); moveEffect.addEventListener(EffectEvent.EFFECT_END, actionBarMoveEffect_effectEndedHandler); actionBarEffect.addChild(moveEffect); return actionBarEffect; } /** * Called by the default prepareForPlay() implementation, * this method is responsible for creating the Spark effect played * on the tab bar when the transition starts. * This method should be overridden by subclasses. * By default, this returns null. * * @return An IEffect instance serving as the tab bar transition. * This effect is played by the default play() method implementation. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createTabBarEffect():IEffect { return null; } /** * Called by the default prepareForPlay() implementation, * this method is responsible for creating the Spark effect played * on the current and next view when the transition starts. * This method should be overridden by subclasses. * By default, this method returns null. * * @return An IEffect instance serving as the view transition. * This effect is played by the default play() method implementation. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createViewEffect():IEffect { return null; } /** * Called by the default prepareForPlay() implementation, * this method is responsible for creating the Spark effect played to * transition the entire navigator, inclusive of the control bar content, * when necessary. * This method should be overridden by subclasses. * By default, this method returns null. * * @return An IEffect instance serving as the view transition. * This effect is played by the default play() method implementation. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createConsolidatedEffect():IEffect { return null; } /** * Called by the transition to indicate that the transition * has completed. * This method dispatches the end event. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function transitionComplete():void { var stage:Stage; if (navigator) stage = navigator.stage; cleanUp(); activeTransitions.splice(activeTransitions.indexOf(this), 1); if (hasEventListener(FlexEvent.TRANSITION_END)) dispatchEvent(new FlexEvent(FlexEvent.TRANSITION_END)); if (stage && stage.hasEventListener(FlexEvent.TRANSITION_END)) stage.dispatchEvent(new FlexEvent(FlexEvent.TRANSITION_END)); } /** * Called after the transition completes. * This method is responsible for releasing any references * and temporary constructs used by the transition. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function cleanUp():void { if (!consolidatedTransition && transitionGroup) { if (cachedTitleGroup) transitionGroup.removeElement(cachedTitleGroup); if (cachedNavigationGroup) transitionGroup.removeElement(cachedNavigationGroup); if (cachedActionGroup) { transitionGroup.removeElement(cachedActionGroup); actionBar.actionGroup.cacheAsBitmap = false; } if (actionBar) { // Restore title group and title content to their original state. if (actionBar.titleGroup && actionBar.titleGroup.visible) { actionBar.titleGroup.postLayoutTransformOffsets = null; actionBar.titleGroup.cacheAsBitmap = false; } if (actionBar.titleDisplay && (actionBar.titleDisplay is DisplayObject) && DisplayObject(actionBar.titleDisplay).visible) { (actionBar.titleDisplay as UIComponent).postLayoutTransformOffsets = null; DisplayObject(actionBar.titleDisplay).cacheAsBitmap = false; } // Restore title group and title content to their original home. if (verticalTransition) { var titleComponent:UIComponent = actionBar.titleGroup; if (!titleComponent || !titleComponent.visible) titleComponent = actionBar.titleDisplay as UIComponent; if (titleComponent) { transitionGroup.removeElement(titleComponent); addComponentToContainer(titleComponent, actionBar.skin); } } // Restore navigation group to their proper home. if (endView.navigationContent && verticalTransition) { transitionGroup.removeElement(actionBar.navigationGroup); if (actionBar.titleDisplay) { var childIndex:uint = actionBar.skin.getChildIndex(actionBar.titleDisplay as DisplayObject); addComponentToContainerAt(actionBar.navigationGroup, actionBar.skin, childIndex); } else addComponentToContainer(actionBar.navigationGroup, actionBar.skin); } // Restore action group to their proper home. if (endView.actionContent && verticalTransition) { transitionGroup.removeElement(actionBar.actionGroup); if (actionBar.titleDisplay) { childIndex = actionBar.skin.getChildIndex(actionBar.titleDisplay as DisplayObject); addComponentToContainerAt(actionBar.actionGroup, actionBar.skin, childIndex); } else addComponentToContainer(actionBar.actionGroup, actionBar.skin); } removeComponentFromContainer(transitionGroup, actionBar.skin); actionBar.skin.scrollRect = null; // Force actionBar to update content group positions after // animating positions. If the width and height change during // the transition, we need relayout it's children because // during the transition they are removed from layout and // missed during the validation pass. See SDK-30142. // TODO (jasonsj): Consider ending transitions when orientation // changes if ((actionBar.width != cachedActionBarWidth) || (actionBar.height != cachedActionBarHeight)) { actionBar.skin.invalidateDisplayList(); } if (actionBar.actionGroup) actionBar.actionGroup.postLayoutTransformOffsets = null; if (actionBar.navigationGroup) actionBar.navigationGroup.postLayoutTransformOffsets = null; } verticalTransition = false; cachedActionBarHeight = 0; cachedActionBarWidth = 0; transitionGroup = null; cachedTitleGroup = null; cachedNavigationGroup = null; cachedActionGroup = null; } consolidatedTransition = false; actionBar = null; tabBar = null; parentNavigator = null; targetNavigator = null; navigator = null; startView = null; endView = null; // Re-enable layout manager if appropriate. if (suspendBackgroundProcessing) UIComponent.resumeBackgroundProcessing(); } /** * Determine if Flex can perform a transition on * action bar or tab bar content independently of the views. * *

Flex cannot perform a transition on the control bars independently:

*
    *
  • If the containing view navigator is a TabbedViewNavigator * and its tab bar's visibility changes between views.
  • *
  • If the value of the view navigator's overlayControls * property changes between views.
  • *
  • If the size or visibility of the action bar changes * between views.
  • *
* * @return false if Flex determines controls bars between views are * incompatible in some way. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function canTransitionControlBarContent():Boolean { // Short circuit if we've already been asked to not consider // control bars during transition. if (transitionControlsWithContent) return false; // Test for visibility or size of tab bar changing. if (targetNavigator is TabbedViewNavigator) { var tabBar:ButtonBarBase = TabbedViewNavigator(targetNavigator).tabBar; if (componentIsVisible(tabBar) != endView.tabBarVisible) return false; } // Test for visibility or size of action bar changing. if (navigator is ViewNavigator) { var actionBar:ActionBar = ViewNavigator(navigator).actionBar; if (componentIsVisible(actionBar) != endView.actionBarVisible) return false; } // Test for valid views. if (!startView || !endView) return false; // Test for value of overlayControls changing. if (startView.overlayControls != endView.overlayControls) return false; return true; } /** * Used to render snap shots of screen elements in * preparation for transitioning. * The bitmap is returned in the form of a BitmapImage object. * *

The BitmapImage is in target's parent coordiantes space - * it overlaps the target precisely if paranted to the same parent. * * When moving to a different parent, make sure to adjust the * transformation of the BitmapImage to correctly account for the * change in coordinate spaces. * * The updated value of the globalPosition parameter * can be used for that.

* * @param target Display object to capture. * * @param padding Padding around the object to be included in * the BitmapImage object. * * @param globalPosition When non-null, globalPosition * will be updated with the origin of the BitmapImage in global * coordiantes. When moving to a different coordinate space, this * value can be used to adjust the snapshot's position so its * global position on screen doesn't change. * * @return BitmapImage object representing the target. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function getSnapshot(target:UIComponent, padding:int = 4, globalPosition:Point = null):BitmapImage { if (!target || !target.visible || target.width == 0 || target.height == 0) return null; var snapshot:BitmapImage = new BitmapImage(); // Ensure bitmap leverages its own display object for performance // reasons. snapshot.alwaysCreateDisplayObject = true; // Capture image, with consideration for transform and color matrix. // Return null if an error is thrown. var bounds:Rectangle = new Rectangle(); try { snapshot.source = BitmapUtil.getSnapshotWithPadding(target, padding, true, bounds); } catch (e:SecurityError) { return null; } // Size and offset snapShot to match our image bounds data. snapshot.width = bounds.width; snapshot.height = bounds.height; var m:Matrix = new Matrix(); m.translate(bounds.left, bounds.top); // Apply target's inverse concatenated matrix: var parent:DisplayObjectContainer = target.parent; if (parent) { var inverted:Matrix = parent.transform.concatenatedMatrix.clone(); inverted.invert(); m.concat(inverted); } snapshot.setLayoutMatrix(m, false); // Exclude from layout. snapshot.includeInLayout = false; if (globalPosition) { var pt:Point = parent ? parent.localToGlobal(new Point(snapshot.x, snapshot.y)) : new Point(); globalPosition.x = pt.x; globalPosition.y = pt.y; } return snapshot; } //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- /** * @private * Remove listeners */ private function actionBarMoveEffect_effectEndedHandler(event:EffectEvent):void { event.target.removeEventListener(EffectEvent.EFFECT_UPDATE, actionBarMoveEffect_effectUpdateHandler); event.target.removeEventListener(EffectEvent.EFFECT_END, actionBarMoveEffect_effectEndedHandler); } /** * @private * Since layout is disabled, we need to force validation on all of the * participating display objects. */ private function actionBarMoveEffect_effectUpdateHandler(event:EffectEvent):void { if (!actionBar) return; // This code is a temporary performance fix for transitions. Since layout is // disabled during ViewTransitions, in the past this method would call // validateDisplayList() on the animation targets to update their internal position // matrices. We learned that this was causing a reduction in framerate due to // actionScript overhead. To workaround the issue we are moving the x and y positions // of the underlying displayObjects manually. This is a temporary fix to get // our performance numbers back up after checking in a fix for SDK-30839. // TODO (chiedozi): Clean up this code and use propery layout methods if (verticalTransition) { if (actionBar.actionGroup && actionBar.actionGroup.postLayoutTransformOffsets) actionBar.actionGroup.$y = actionBar.actionGroup.y + actionBar.actionGroup.postLayoutTransformOffsets.y; if (actionBar.navigationGroup && actionBar.navigationGroup.postLayoutTransformOffsets) actionBar.navigationGroup.$y = actionBar.navigationGroup.y + actionBar.navigationGroup.postLayoutTransformOffsets.y; if (actionBar.titleDisplay && UIComponent(actionBar.titleDisplay).postLayoutTransformOffsets) UIComponent(actionBar.titleDisplay).$y = UIComponent(actionBar.titleDisplay).y + UIComponent(actionBar.titleDisplay).postLayoutTransformOffsets.y; if (actionBar.titleGroup && actionBar.titleGroup.postLayoutTransformOffsets) actionBar.titleGroup.$y = actionBar.titleGroup.y + actionBar.titleGroup.postLayoutTransformOffsets.y; if (cachedTitleGroup && cachedTitleGroup.displayObject) cachedTitleGroup.displayObject.y = cachedTitleGroup.y + cachedTitleGroup.postLayoutTransformOffsets.y; if (cachedNavigationGroup && cachedNavigationGroup.displayObject) cachedNavigationGroup.displayObject.y = cachedNavigationGroup.y + cachedNavigationGroup.postLayoutTransformOffsets.y; if (cachedActionGroup && cachedActionGroup.displayObject) cachedActionGroup.displayObject.y = cachedActionGroup.y + cachedActionGroup.postLayoutTransformOffsets.y; } else { if (actionBar.actionGroup && actionBar.actionGroup.postLayoutTransformOffsets) actionBar.actionGroup.$x = actionBar.actionGroup.x + actionBar.actionGroup.postLayoutTransformOffsets.x; if (actionBar.navigationGroup && actionBar.navigationGroup.postLayoutTransformOffsets) actionBar.navigationGroup.$x = actionBar.navigationGroup.x + actionBar.navigationGroup.postLayoutTransformOffsets.x; if (actionBar.titleDisplay && UIComponent(actionBar.titleDisplay).postLayoutTransformOffsets) UIComponent(actionBar.titleDisplay).$x = UIComponent(actionBar.titleDisplay).x + UIComponent(actionBar.titleDisplay).postLayoutTransformOffsets.x; if (actionBar.titleGroup && actionBar.titleGroup.postLayoutTransformOffsets) actionBar.titleGroup.$x = actionBar.titleGroup.x + actionBar.titleGroup.postLayoutTransformOffsets.x; if (cachedTitleGroup && cachedTitleGroup.displayObject) cachedTitleGroup.displayObject.x = cachedTitleGroup.x + cachedTitleGroup.postLayoutTransformOffsets.x; if (cachedNavigationGroup && cachedNavigationGroup.displayObject) cachedNavigationGroup.displayObject.x = cachedNavigationGroup.x + cachedNavigationGroup.postLayoutTransformOffsets.x; if (cachedActionGroup && cachedActionGroup.displayObject) cachedActionGroup.displayObject.x = cachedActionGroup.x + cachedActionGroup.postLayoutTransformOffsets.x; } } /** * @private */ private function effectComplete(event:EffectEvent):void { effect.removeEventListener(EffectEvent.EFFECT_END, effectComplete); // Validate the last frame of the actionBar animation so that it // renders properly. We put this here because layout isn't reenabled // until the next frame, meaning this validation won't be applied for // two frames. if (!consolidatedTransition) actionBarMoveEffect_effectUpdateHandler(null); if (renderLastFrame) { // We don't call transitionComplete just yet, we want to ensure // that the last frame of animation actually gets rendered on screen // before we clean up after ourselves. This prevents a perceived // stutter on the very last frame. navigator.addEventListener(Event.ENTER_FRAME, enterFrameHandler); } else { enterFrameHandler(null); } } /** * @private */ private function enterFrameHandler(event:Event):void { if (event) navigator.removeEventListener(Event.ENTER_FRAME, enterFrameHandler); effect = null; transitionComplete(); } /** * @private * Helper method to test whether a component is visible to user. */ mx_internal function componentIsVisible(component:UIComponent):Boolean { return component && component.visible && component.width && component.height && component.alpha; } /** * @private * Helper method to add a UIComponent instance to either an IVisualElementContainer * or DisplayObjectContainer. */ mx_internal function addComponentToContainerAt(component:UIComponent, container:UIComponent, index:int):void { if (container is IVisualElementContainer) IVisualElementContainer(container).addElementAt(component, index); else container.addChildAt(component, index); } /** * @private * Helper method to add a UIComponent instance to either an IVisualElementContainer * or DisplayObjectContainer. */ mx_internal function addComponentToContainer(component:UIComponent, container:UIComponent):void { if (container is IVisualElementContainer) IVisualElementContainer(container).addElement(component); else container.addChild(component); } /** * @private * Helper method to remove a UIComponent instance from either an IVisualElementContainer * or DisplayObjectContainer. */ mx_internal function removeComponentFromContainer(component:UIComponent, container:UIComponent):void { if (container is IVisualElementContainer) IVisualElementContainer(container).removeElement(component); else container.removeChild(component); } /** * @private * Helper method to set the child index of the given component. */ mx_internal function setComponentChildIndex(component:UIComponent, container:UIComponent, index:int):void { if (container is IVisualElementContainer) IVisualElementContainer(container).setElementIndex(component, index); else container.setChildIndex(component, index); } /** * @private * Adds the element to the targetGroup and adjusts the position * so that the global position remains the same. * * Note the targetGroup must be already added to the display list and * positioned in order for this method to adjust the cachedElement's position * correctly. * * @param targetGroup The Group that will parent the cached element. * @param cachedElement The cached element - the return value of getSnapshot() * @param cachedElementGlobalPosition The global position returned from getSnapshot() * * @see #getSnapshot */ mx_internal function addCachedElementToGroup(targetGroup:Group, cachedElement:BitmapImage, cachedElementGlobalPosition:Point):void { targetGroup.addElement(cachedElement); // We are moving the cachedTitleGroup to the transitionGroup's coordinate space, // adjust the position var localOrigin:Point = targetGroup.globalToLocal(cachedElementGlobalPosition); cachedElement.x = localOrigin.x; cachedElement.y = localOrigin.y; } /** * @private * Helper method that returns index of the given component. */ mx_internal function getComponentChildIndex(component:UIComponent, container:UIComponent):int { if (container is IVisualElementContainer) return IVisualElementContainer(container).getElementIndex(component); else return container.getChildIndex(component); } } } ",12395,False,2443.1470891288222,median "// Urho3D material editor Window@ particleEffectWindow; ParticleEffect@ editParticleEffect; XMLFile@ oldParticleEffectState; bool inParticleEffectRefresh = false; View3D@ particleEffectPreview; Scene@ particlePreviewScene; Node@ particleEffectPreviewNode; Node@ particleEffectPreviewGizmoNode; Node@ particlePreviewCameraNode; Node@ particlePreviewLightNode; Light@ particlePreviewLight; ParticleEmitter@ particleEffectEmitter; float particleResetTimer; bool showParticlePreviewAxes = true; void CreateParticleEffectEditor() { if (particleEffectWindow !is null) return; particleEffectWindow = LoadEditorUI(""UI/EditorParticleEffectWindow.xml""); ui.root.AddChild(particleEffectWindow); particleEffectWindow.opacity = uiMaxOpacity; InitParticleEffectPreview(); InitParticleEffectBasicAttributes(); RefreshParticleEffectEditor(); int width = Min(ui.root.width - 60, 800); int height = Min(ui.root.height - 60, 600); particleEffectWindow.SetSize(width, height); CenterDialog(particleEffectWindow); HideParticleEffectEditor(); SubscribeToEvent(particleEffectWindow.GetChild(""NewButton"", true), ""Released"", ""NewParticleEffect""); SubscribeToEvent(particleEffectWindow.GetChild(""RevertButton"", true), ""Released"", ""RevertParticleEffect""); SubscribeToEvent(particleEffectWindow.GetChild(""SaveButton"", true), ""Released"", ""SaveParticleEffect""); SubscribeToEvent(particleEffectWindow.GetChild(""SaveAsButton"", true), ""Released"", ""SaveParticleEffectAs""); SubscribeToEvent(particleEffectWindow.GetChild(""CloseButton"", true), ""Released"", ""HideParticleEffectEditor""); SubscribeToEvent(particleEffectWindow.GetChild(""NewColorFrame"", true), ""Released"", ""EditParticleEffectColorFrameNew""); SubscribeToEvent(particleEffectWindow.GetChild(""RemoveColorFrame"", true), ""Released"", ""EditParticleEffectColorFrameRemove""); SubscribeToEvent(particleEffectWindow.GetChild(""ColorFrameSort"", true), ""Released"", ""EditParticleEffectColorFrameSort""); SubscribeToEvent(particleEffectWindow.GetChild(""NewTextureFrame"", true), ""Released"", ""EditParticleEffectTextureFrameNew""); SubscribeToEvent(particleEffectWindow.GetChild(""RemoveTextureFrame"", true), ""Released"", ""EditParticleEffectTextureFrameRemove""); SubscribeToEvent(particleEffectWindow.GetChild(""TextureFrameSort"", true), ""Released"", ""EditParticleEffectTextureFrameSort""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceX"", true), ""TextChanged"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceY"", true), ""TextChanged"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceZ"", true), ""TextChanged"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinX"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinY"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinZ"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxX"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxY"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxZ"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DampingForce"", true), ""TextChanged"", ""EditParticleEffectDampingForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ActiveTime"", true), ""TextChanged"", ""EditParticleEffectActiveTime""); SubscribeToEvent(particleEffectWindow.GetChild(""InactiveTime"", true), ""TextChanged"", ""EditParticleEffectInactiveTime""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinX"", true), ""TextChanged"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinY"", true), ""TextChanged"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true), ""TextChanged"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true), ""TextChanged"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMin"", true), ""TextChanged"", ""EditParticleEffectTimeToLive""); SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMax"", true), ""TextChanged"", ""EditParticleEffectTimeToLive""); SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMin"", true), ""TextChanged"", ""EditParticleEffectVelocity""); SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMax"", true), ""TextChanged"", ""EditParticleEffectVelocity""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationMin"", true), ""TextChanged"", ""EditParticleEffectRotation""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationMax"", true), ""TextChanged"", ""EditParticleEffectRotation""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMin"", true), ""TextChanged"", ""EditParticleEffectRotationSpeed""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMax"", true), ""TextChanged"", ""EditParticleEffectRotationSpeed""); SubscribeToEvent(particleEffectWindow.GetChild(""SizeAdd"", true), ""TextChanged"", ""EditParticleEffectSizeAdd""); SubscribeToEvent(particleEffectWindow.GetChild(""SizeMultiply"", true), ""TextChanged"", ""EditParticleEffectSizeMultiply""); SubscribeToEvent(particleEffectWindow.GetChild(""AnimationLodBias"", true), ""TextChanged"", ""EditParticleEffectAnimationLodBias""); SubscribeToEvent(particleEffectWindow.GetChild(""NumParticles"", true), ""TextChanged"", ""EditParticleEffectNumParticles""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeX"", true), ""TextChanged"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeY"", true), ""TextChanged"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeZ"", true), ""TextChanged"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMin"", true), ""TextChanged"", ""EditParticleEffectEmissionRate""); SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMax"", true), ""TextChanged"", ""EditParticleEffectEmissionRate""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceX"", true), ""TextFinished"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceY"", true), ""TextFinished"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceZ"", true), ""TextFinished"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinX"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinY"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinZ"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxX"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxY"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxZ"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DampingForce"", true), ""TextFinished"", ""EditParticleEffectDampingForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ActiveTime"", true), ""TextFinished"", ""EditParticleEffectActiveTime""); SubscribeToEvent(particleEffectWindow.GetChild(""InactiveTime"", true), ""TextFinished"", ""EditParticleEffectInactiveTime""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinX"", true), ""TextFinished"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinY"", true), ""TextFinished"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true), ""TextFinished"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true), ""TextFinished"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMin"", true), ""TextFinished"", ""EditParticleEffectTimeToLive""); SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMax"", true), ""TextFinished"", ""EditParticleEffectTimeToLive""); SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMin"", true), ""TextFinished"", ""EditParticleEffectVelocity""); SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMax"", true), ""TextFinished"", ""EditParticleEffectVelocity""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationMin"", true), ""TextFinished"", ""EditParticleEffectRotation""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationMax"", true), ""TextFinished"", ""EditParticleEffectRotation""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMin"", true), ""TextFinished"", ""EditParticleEffectRotationSpeed""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMax"", true), ""TextFinished"", ""EditParticleEffectRotationSpeed""); SubscribeToEvent(particleEffectWindow.GetChild(""SizeAdd"", true), ""TextFinished"", ""EditParticleEffectSizeAdd""); SubscribeToEvent(particleEffectWindow.GetChild(""SizeMultiply"", true), ""TextFinished"", ""EditParticleEffectSizeMultiply""); SubscribeToEvent(particleEffectWindow.GetChild(""AnimationLodBias"", true), ""TextFinished"", ""EditParticleEffectAnimationLodBias""); SubscribeToEvent(particleEffectWindow.GetChild(""NumParticles"", true), ""TextFinished"", ""EditParticleEffectNumParticles""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeX"", true), ""TextFinished"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeY"", true), ""TextFinished"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeZ"", true), ""TextFinished"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMin"", true), ""TextFinished"", ""EditParticleEffectEmissionRate""); SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMax"", true), ""TextFinished"", ""EditParticleEffectEmissionRate""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterShape"", true), ""ItemSelected"", ""EditParticleEffectEmitterShape""); SubscribeToEvent(particleEffectWindow.GetChild(""Scaled"", true), ""Toggled"", ""EditParticleEffectScaled""); SubscribeToEvent(particleEffectWindow.GetChild(""Sorted"", true), ""Toggled"", ""EditParticleEffectSorted""); SubscribeToEvent(particleEffectWindow.GetChild(""Relative"", true), ""Toggled"", ""EditParticleEffectRelative""); SubscribeToEvent(particleEffectWindow.GetChild(""ResetViewport"", true), ""Released"", ""ParticleEffectResetViewport""); SubscribeToEvent(particleEffectWindow.GetChild(""ShowAxes"", true), ""Toggled"", ""ParticleEffectShowAxes""); } void ParticleEffectResetViewport(StringHash eventType, VariantMap& eventData) { particleEffectPreviewNode.rotation = Quaternion(0, 0, 0); particleEffectPreviewNode.worldPosition = Vector3(0, 0, 0); particleEffectPreview.QueueUpdate(); } void ParticleEffectShowAxes(StringHash eventType, VariantMap& eventData) { CheckBox@ element = eventData[""Element""].GetPtr(); showParticlePreviewAxes = element.checked; particleEffectPreviewGizmoNode.enabled = showParticlePreviewAxes; particleEffectPreview.QueueUpdate(); } void EditParticleEffectColorFrameNew(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); uint num = editParticleEffect.numColorFrames; editParticleEffect.numColorFrames = num + 1; RefreshParticleEffectColorFrames(); EndParticleEffectEdit(); } void EditParticleEffectTextureFrameNew(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); uint num = editParticleEffect.numTextureFrames; editParticleEffect.numTextureFrames = num + 1; RefreshParticleEffectTextureFrames(); EndParticleEffectEdit(); } void EditParticleEffectColorFrameRemove(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; ListView@ lv = particleEffectWindow.GetChild(""ColorFrameListView"", true); if (lv !is null && lv.selection != M_MAX_UNSIGNED ) { BeginParticleEffectEdit(); editParticleEffect.RemoveColorFrame(lv.selection); RefreshParticleEffectColorFrames(); EndParticleEffectEdit(); } } void EditParticleEffectTextureFrameRemove(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; ListView@ lv = particleEffectWindow.GetChild(""TextureFrameListView"", true); if (lv !is null && lv.selection != M_MAX_UNSIGNED ) { BeginParticleEffectEdit(); editParticleEffect.RemoveTextureFrame(lv.selection); RefreshParticleEffectTextureFrames(); EndParticleEffectEdit(); } } void EditParticleEffectColorFrameSort(StringHash eventType, VariantMap& eventData) { RefreshParticleEffectColorFrames(); } void EditParticleEffectTextureFrameSort(StringHash eventType, VariantMap& eventData) { RefreshParticleEffectTextureFrames(); } void InitParticleEffectBasicAttributes() { CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceZ"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinZ"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxZ"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DampingForce"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ActiveTime"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""InactiveTime"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMinX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMinY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""TimeToLiveMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""TimeToLiveMax"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""VelocityMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""VelocityMax"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationMax"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationSpeedMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationSpeedMax"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""SizeAdd"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""SizeMultiply"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""AnimationLodBias"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""NumParticles"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeZ"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmissionRateMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmissionRateMax"", true))); } void EditParticleEffectConstantForce(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); Vector3 v = editParticleEffect.constantForce; if (element.name == ""ConstantForceX"") editParticleEffect.constantForce = Vector3(element.text.ToFloat(), v.y, v.z); if (element.name == ""ConstantForceY"") editParticleEffect.constantForce = Vector3(v.x, element.text.ToFloat(), v.z); if (element.name == ""ConstantForceZ"") editParticleEffect.constantForce = Vector3(v.x, v.y, element.text.ToFloat()); EndParticleEffectEdit(); } void EditParticleEffectDirection(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); Vector3 vMin = editParticleEffect.minDirection; Vector3 vMax = editParticleEffect.maxDirection; if (element.name == ""DirectionMinX"") editParticleEffect.minDirection = Vector3(element.text.ToFloat(), vMin.y, vMin.z); if (element.name == ""DirectionMinY"") editParticleEffect.minDirection = Vector3(vMin.x, element.text.ToFloat(), vMin.z); if (element.name == ""DirectionMinZ"") editParticleEffect.minDirection = Vector3(vMin.x, vMin.y, element.text.ToFloat()); if (element.name == ""DirectionMaxX"") editParticleEffect.maxDirection = Vector3(element.text.ToFloat(), vMax.y, vMax.z); if (element.name == ""DirectionMaxY"") editParticleEffect.maxDirection = Vector3(vMax.x, element.text.ToFloat(), vMax.z); if (element.name == ""DirectionMaxZ"") editParticleEffect.maxDirection = Vector3(vMax.x, vMax.y, element.text.ToFloat()); EndParticleEffectEdit(); } void EditParticleEffectDampingForce(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.dampingForce = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectActiveTime(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.activeTime = element.text.ToFloat(); particleEffectEmitter.Reset(); EndParticleEffectEdit(); } void EditParticleEffectInactiveTime(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.inactiveTime = element.text.ToFloat(); particleEffectEmitter.Reset(); EndParticleEffectEdit(); } void EditParticleEffectParticleSize(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); Vector2 vMin = editParticleEffect.minParticleSize; Vector2 vMax = editParticleEffect.maxParticleSize; if (element.name == ""ParticleSizeMinX"") editParticleEffect.minParticleSize = Vector2(element.text.ToFloat(), vMin.y); if (element.name == ""ParticleSizeMinY"") editParticleEffect.minParticleSize = Vector2(vMin.x, element.text.ToFloat()); if (element.name == ""ParticleSizeMaxX"") editParticleEffect.maxParticleSize = Vector2(element.text.ToFloat(), vMax.y); if (element.name == ""ParticleSizeMaxY"") editParticleEffect.maxParticleSize = Vector2(vMax.x, element.text.ToFloat()); EndParticleEffectEdit(); } void EditParticleEffectTimeToLive(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); float vMin = editParticleEffect.minTimeToLive; float vMax = editParticleEffect.maxTimeToLive; if (element.name == ""TimeToLiveMin"") editParticleEffect.minTimeToLive = element.text.ToFloat(); if (element.name == ""TimeToLiveMax"") editParticleEffect.maxTimeToLive = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectVelocity(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); float vMin = editParticleEffect.minVelocity; float vMax = editParticleEffect.maxVelocity; if (element.name == ""VelocityMin"") editParticleEffect.minVelocity = element.text.ToFloat(); if (element.name == ""VelocityMax"") editParticleEffect.maxVelocity = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectRotation(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); float vMin = editParticleEffect.minRotation; float vMax = editParticleEffect.maxRotation; if (element.name == ""RotationMin"") editParticleEffect.minRotation = element.text.ToFloat(); if (element.name == ""RotationMax"") editParticleEffect.maxRotation = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectRotationSpeed(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); float vMin = editParticleEffect.minRotationSpeed; float vMax = editParticleEffect.maxRotationSpeed; if (element.name == ""RotationSpeedMin"") editParticleEffect.minRotationSpeed = element.text.ToFloat(); if (element.name == ""RotationSpeedMax"") editParticleEffect.maxRotationSpeed = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectSizeAdd(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.sizeAdd = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectSizeMultiply(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.sizeMul = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectAnimationLodBias(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.animationLodBias = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectNumParticles(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.numParticles = element.text.ToInt(); particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } void EditParticleEffectEmitterSize(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); Vector3 v = editParticleEffect.emitterSize; if (element.name == ""EmitterSizeX"") editParticleEffect.emitterSize = Vector3(element.text.ToFloat(), v.y, v.z); if (element.name == ""EmitterSizeY"") editParticleEffect.emitterSize = Vector3(v.x, element.text.ToFloat(), v.z); if (element.name == ""EmitterSizeZ"") editParticleEffect.emitterSize = Vector3(v.x, v.y, element.text.ToFloat()); EndParticleEffectEdit(); } void EditParticleEffectEmissionRate(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); if (element.name == ""EmissionRateMin"") editParticleEffect.minEmissionRate = element.text.ToFloat(); if (element.name == ""EmissionRateMax"") editParticleEffect.maxEmissionRate = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectEmitterShape(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); DropDownList@ element = eventData[""Element""].GetPtr(); switch (element.selection) { case 0: editParticleEffect.emitterType = EMITTER_BOX; break; case 1: editParticleEffect.emitterType = EMITTER_SPHERE; break; } EndParticleEffectEdit(); } void EditParticleEffectMaterial(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; LineEdit@ element = eventData[""Element""].GetPtr(); Material@ res = cache.GetResource(""Material"", element.text); if (res !is null) { BeginParticleEffectEdit(); editParticleEffect.material = res; particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } } void PickEditParticleEffectMaterial(StringHash eventType, VariantMap& eventData) { @resourcePicker = GetResourcePicker(StringHash(""Material"")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector(localization.Get(""Pick "") + resourcePicker.typeName, ""OK"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter, false); SubscribeToEvent(uiFileSelector, ""FileSelected"", ""PickEditParticleEffectMaterialDone""); } void PickEditParticleEffectMaterialDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData[""OK""].GetBool()) { @resourcePicker = null; return; } String resourceName = eventData[""FileName""].GetString(); Resource@ res = GetPickedResource(resourceName); if (res !is null && editParticleEffect !is null && particleEffectEmitter !is null) { editParticleEffect.material = res; particleEffectEmitter.ApplyEffect(); RefreshParticleEffectMaterial(); } @resourcePicker = null; } void EditParticleEffectScaled(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); CheckBox@ element = eventData[""Element""].GetPtr(); editParticleEffect.scaled = element.checked; particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } void EditParticleEffectSorted(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); CheckBox@ element = eventData[""Element""].GetPtr(); editParticleEffect.sorted = element.checked; particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } void EditParticleEffectRelative(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); CheckBox@ element = eventData[""Element""].GetPtr(); editParticleEffect.relative = element.checked; particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } bool ToggleParticleEffectEditor() { if (particleEffectWindow.visible == false) ShowParticleEffectEditor(); else HideParticleEffectEditor(); return true; } void ShowParticleEffectEditor() { RefreshParticleEffectEditor(); particleEffectWindow.visible = true; particleEffectWindow.BringToFront(); } void HideParticleEffectEditor() { if (particleEffectWindow !is null) particleEffectWindow.visible = false; } void InitParticleEffectPreview() { particlePreviewScene = Scene(""particlePreviewScene""); particlePreviewScene.CreateComponent(""Octree""); Node@ zoneNode = particlePreviewScene.CreateChild(""Zone""); Zone@ zone = zoneNode.CreateComponent(""Zone""); zone.boundingBox = BoundingBox(-1000, 1000); zone.ambientColor = Color(0.15, 0.15, 0.15); zone.fogColor = Color(0, 0, 0); zone.fogStart = 10.0; zone.fogEnd = 1000.0; particlePreviewCameraNode = particlePreviewScene.CreateChild(""PreviewCamera""); particlePreviewCameraNode.position = Vector3(0, 0, -5); Camera@ camera = particlePreviewCameraNode.CreateComponent(""Camera""); camera.nearClip = 0.1f; camera.farClip = 1000.0f; particlePreviewLightNode = particlePreviewScene.CreateChild(""particlePreviewLight""); particlePreviewLightNode.direction = Vector3(0.5, -0.5, 0.5); particlePreviewLight = particlePreviewLightNode.CreateComponent(""Light""); particlePreviewLight.lightType = LIGHT_DIRECTIONAL; particlePreviewLight.specularIntensity = 0.5; particleEffectPreviewNode = particlePreviewScene.CreateChild(""PreviewEmitter""); particleEffectPreviewNode.rotation = Quaternion(0, 0, 0); particleEffectPreviewGizmoNode = particleEffectPreviewNode.CreateChild(""Gizmo""); StaticModel@ gizmo = particleEffectPreviewGizmoNode.CreateComponent(""StaticModel""); gizmo.model = cache.GetResource(""Model"", ""Models/Editor/Axes.mdl""); gizmo.materials[0] = cache.GetResource(""Material"", ""Materials/Editor/RedUnlit.xml""); gizmo.materials[1] = cache.GetResource(""Material"", ""Materials/Editor/GreenUnlit.xml""); gizmo.materials[2] = cache.GetResource(""Material"", ""Materials/Editor/BlueUnlit.xml""); gizmo.occludee = false; particleEffectEmitter = particleEffectPreviewNode.CreateComponent(""ParticleEmitter""); editParticleEffect = CreateNewParticleEffect(); particleEffectEmitter.effect = editParticleEffect; particleEffectPreview = particleEffectWindow.GetChild(""ParticleEffectPreview"", true); particleEffectPreview.SetView(particlePreviewScene, camera); SubscribeToEvent(particleEffectPreview, ""DragMove"", ""NavigateParticleEffectPreview""); } ParticleEffect@ CreateNewParticleEffect() { ParticleEffect@ effect = ParticleEffect(); Material@ res = cache.GetResource(""Material"", ""Materials/Particle.xml""); if (res is null) log.Error(""Could not load default material for new particle effect.""); effect.material = res; effect.AddColorTime(Color(1,1,1,1), 0.0f); return effect; } void EditParticleEffect(ParticleEffect@ effect) { if (effect is null) return; if (editParticleEffect !is null) UnsubscribeFromEvent(editParticleEffect, ""ReloadFinished""); if (!effect.name.empty) cache.ReloadResource(effect); editParticleEffect = effect; particleEffectEmitter.effect = editParticleEffect; if (editParticleEffect !is null) SubscribeToEvent(editParticleEffect, ""ReloadFinished"", ""RefreshParticleEffectEditor""); ShowParticleEffectEditor(); } void RefreshParticleEffectEditor() { inParticleEffectRefresh = true; RefreshParticleEffectPreview(); RefreshParticleEffectName(); RefreshParticleEffectBasicAttributes(); RefreshParticleEffectMaterial(); RefreshParticleEffectColorFrames(); RefreshParticleEffectTextureFrames(); inParticleEffectRefresh = false; } void RefreshParticleEffectColorFrames() { if (editParticleEffect is null) return; editParticleEffect.SortColorFrames(); ListView@ lv = particleEffectWindow.GetChild(""ColorFrameListView"", true); if (lv is null) return; lv.RemoveAllItems(); for (uint i = 0; i < editParticleEffect.numColorFrames; i++) { ColorFrame@ colorFrame = editParticleEffect.GetColorFrame(i); Button@ container = Button(); lv.AddItem(container); container.style = ""Button""; container.imageRect = IntRect(18, 2, 30, 14); container.minSize = IntVector2(0, 20); container.maxSize = IntVector2(2147483647, 20); container.layoutMode = LM_HORIZONTAL; container.layoutBorder = IntRect(3,1,3,1); container.layoutSpacing = 4; UIElement@ labelContainer = UIElement(); container.AddChild(labelContainer); labelContainer.style = ""HorizontalPanel""; labelContainer.minSize = IntVector2(0, 16); labelContainer.maxSize = IntVector2(2147483647, 16); labelContainer.verticalAlignment = VA_CENTER; { LineEdit@ le = LineEdit(); labelContainer.AddChild(le); le.name = ""ColorTime""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.minSize = IntVector2(0, 16); le.maxSize = IntVector2(40, 16); le.text = colorFrame.time; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } UIElement@ textContainer = UIElement(); labelContainer.AddChild(textContainer); textContainer.minSize = IntVector2(0, 16); textContainer.maxSize = IntVector2(2147483647, 16); textContainer.verticalAlignment = VA_CENTER; Text@ t = Text(); textContainer.AddChild(t); t.style = ""Text""; t.text = ""Color""; t.autoLocalizable = true; UIElement@ editContainer = UIElement(); container.AddChild(editContainer); editContainer.style = ""HorizontalPanel""; editContainer.minSize = IntVector2(0, 16); editContainer.maxSize = IntVector2(2147483647, 16); editContainer.verticalAlignment = VA_CENTER; { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""ColorR""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.text = colorFrame.color.r; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""ColorG""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.text = colorFrame.color.g; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""ColorB""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.text = colorFrame.color.b; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""ColorA""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.text = colorFrame.color.a; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } } } void RefreshParticleEffectTextureFrames() { if (editParticleEffect is null) return; editParticleEffect.SortTextureFrames(); ListView@ lv = particleEffectWindow.GetChild(""TextureFrameListView"", true); if (lv is null) return; lv.RemoveAllItems(); for (uint i = 0; i < editParticleEffect.numTextureFrames; i++) { TextureFrame@ textureFrame = editParticleEffect.GetTextureFrame(i); if (textureFrame is null) continue; Button@ container = Button(); lv.AddItem(container); container.style = ""Button""; container.imageRect = IntRect(18, 2, 30, 14); container.minSize = IntVector2(0, 20); container.maxSize = IntVector2(2147483647, 20); container.layoutMode = LM_HORIZONTAL; container.layoutBorder = IntRect(1,1,1,1); container.layoutSpacing = 4; UIElement@ labelContainer = UIElement(); container.AddChild(labelContainer); labelContainer.style = ""HorizontalPanel""; labelContainer.minSize = IntVector2(0, 16); labelContainer.maxSize = IntVector2(2147483647, 16); labelContainer.verticalAlignment = VA_CENTER; { LineEdit@ le = LineEdit(); labelContainer.AddChild(le); le.name = ""TextureTime""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.minSize = IntVector2(0, 16); le.maxSize = IntVector2(40, 16); le.text = textureFrame.time; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } UIElement@ textContainer = UIElement(); labelContainer.AddChild(textContainer); textContainer.minSize = IntVector2(0, 16); textContainer.maxSize = IntVector2(2147483647, 16); textContainer.verticalAlignment = VA_CENTER; Text@ t = Text(); textContainer.AddChild(t); t.style = ""Text""; t.text = ""Texture""; t.autoLocalizable = true; UIElement@ editContainer = UIElement(); container.AddChild(editContainer); editContainer.style = ""HorizontalPanel""; editContainer.minSize = IntVector2(0, 16); editContainer.maxSize = IntVector2(2147483647, 16); editContainer.verticalAlignment = VA_CENTER; { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""TextureMinX""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.text = textureFrame.uv.min.x; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""TextureMinY""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.text = textureFrame.uv.min.y; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""TextureMaxX""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.text = textureFrame.uv.max.x; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""TextureMaxY""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.text = textureFrame.uv.max.y; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } } } void EditParticleEffectColorFrame(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); uint i = element.vars[""ColorFrame""].GetInt(); ColorFrame@ cf = editParticleEffect.GetColorFrame(i); if (element.name == ""ColorTime"") cf.time = element.text.ToFloat(); if (element.name == ""ColorR"") cf.color = Color(element.text.ToFloat(), cf.color.g, cf.color.b, cf.color.a); if (element.name == ""ColorG"") cf.color = Color(cf.color.r, element.text.ToFloat(), cf.color.b, cf.color.a); if (element.name == ""ColorB"") cf.color = Color(cf.color.r, cf.color.g, element.text.ToFloat(), cf.color.a); if (element.name == ""ColorA"") cf.color = Color(cf.color.r, cf.color.g, cf.color.b, element.text.ToFloat()); editParticleEffect.SetColorFrame(i, cf); particleEffectEmitter.Reset(); EndParticleEffectEdit(); } void EditParticleEffectTextureFrame(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); uint i = element.vars[""TextureFrame""].GetInt(); TextureFrame@ tf = editParticleEffect.GetTextureFrame(i); if (element.name == ""TextureTime"") tf.time = element.text.ToFloat(); if (element.name == ""TextureMinX"") tf.uv = Rect(element.text.ToFloat(), tf.uv.min.y, tf.uv.max.x, tf.uv.max.y); if (element.name == ""TextureMinY"") tf.uv = Rect(tf.uv.min.x, element.text.ToFloat(), tf.uv.max.x, tf.uv.max.y); if (element.name == ""TextureMaxX"") tf.uv = Rect(tf.uv.min.x, tf.uv.min.y, element.text.ToFloat(), tf.uv.max.y); if (element.name == ""TextureMaxY"") tf.uv = Rect(tf.uv.min.x, tf.uv.min.y, tf.uv.max.x, element.text.ToFloat()); editParticleEffect.SetTextureFrame(i, tf); particleEffectEmitter.Reset(); EndParticleEffectEdit(); } void RefreshParticleEffectPreview() { if (particleEffectEmitter is null || editParticleEffect is null) return; cast(particleEffectWindow.GetChild(""ShowAxes"", true)).checked = showParticlePreviewAxes; particleEffectEmitter.effect = editParticleEffect; particleEffectEmitter.Reset(); particleEffectPreview.QueueUpdate(); } void RefreshParticleEffectName() { UIElement@ container = particleEffectWindow.GetChild(""NameContainer"", true); if (container is null) return; container.RemoveAllChildren(); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, 0, 0); if (editParticleEffect !is null) nameEdit.text = editParticleEffect.name; SubscribeToEvent(nameEdit, ""TextFinished"", ""EditParticleEffectName""); Button@ pickButton = CreateResourcePickerButton(container, null, 0, 0, ""smallButtonPick""); SubscribeToEvent(pickButton, ""Released"", ""PickEditParticleEffect""); } void RefreshParticleEffectBasicAttributes() { if (editParticleEffect is null) return; cast(particleEffectWindow.GetChild(""ConstantForceX"", true)).text = editParticleEffect.constantForce.x; cast(particleEffectWindow.GetChild(""ConstantForceY"", true)).text = editParticleEffect.constantForce.y; cast(particleEffectWindow.GetChild(""ConstantForceZ"", true)).text = editParticleEffect.constantForce.z; cast(particleEffectWindow.GetChild(""DirectionMinX"", true)).text = editParticleEffect.minDirection.x; cast(particleEffectWindow.GetChild(""DirectionMinY"", true)).text = editParticleEffect.minDirection.y; cast(particleEffectWindow.GetChild(""DirectionMinZ"", true)).text = editParticleEffect.minDirection.z; cast(particleEffectWindow.GetChild(""DirectionMaxX"", true)).text = editParticleEffect.maxDirection.x; cast(particleEffectWindow.GetChild(""DirectionMaxY"", true)).text = editParticleEffect.maxDirection.y; cast(particleEffectWindow.GetChild(""DirectionMaxZ"", true)).text = editParticleEffect.maxDirection.z; cast(particleEffectWindow.GetChild(""DampingForce"", true)).text = editParticleEffect.dampingForce; cast(particleEffectWindow.GetChild(""ActiveTime"", true)).text = editParticleEffect.activeTime; cast(particleEffectWindow.GetChild(""InactiveTime"", true)).text = editParticleEffect.inactiveTime; cast(particleEffectWindow.GetChild(""ParticleSizeMinX"", true)).text = editParticleEffect.minParticleSize.x; cast(particleEffectWindow.GetChild(""ParticleSizeMinY"", true)).text = editParticleEffect.minParticleSize.y; cast(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true)).text = editParticleEffect.maxParticleSize.x; cast(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true)).text = editParticleEffect.maxParticleSize.y; cast(particleEffectWindow.GetChild(""TimeToLiveMin"", true)).text = editParticleEffect.minTimeToLive; cast(particleEffectWindow.GetChild(""TimeToLiveMax"", true)).text = editParticleEffect.maxTimeToLive; cast(particleEffectWindow.GetChild(""VelocityMin"", true)).text = editParticleEffect.minVelocity; cast(particleEffectWindow.GetChild(""VelocityMax"", true)).text = editParticleEffect.maxVelocity; cast(particleEffectWindow.GetChild(""RotationMin"", true)).text = editParticleEffect.minRotation; cast(particleEffectWindow.GetChild(""RotationMax"", true)).text = editParticleEffect.maxRotation; cast(particleEffectWindow.GetChild(""RotationSpeedMin"", true)).text = editParticleEffect.minRotationSpeed; cast(particleEffectWindow.GetChild(""RotationSpeedMax"", true)).text = editParticleEffect.maxRotationSpeed; cast(particleEffectWindow.GetChild(""SizeAdd"", true)).text = editParticleEffect.sizeAdd; cast(particleEffectWindow.GetChild(""SizeMultiply"", true)).text = editParticleEffect.sizeMul; cast(particleEffectWindow.GetChild(""AnimationLodBias"", true)).text = editParticleEffect.animationLodBias; cast(particleEffectWindow.GetChild(""NumParticles"", true)).text = editParticleEffect.numParticles; cast(particleEffectWindow.GetChild(""EmitterSizeX"", true)).text = editParticleEffect.emitterSize.x; cast(particleEffectWindow.GetChild(""EmitterSizeY"", true)).text = editParticleEffect.emitterSize.y; cast(particleEffectWindow.GetChild(""EmitterSizeZ"", true)).text = editParticleEffect.emitterSize.z; cast(particleEffectWindow.GetChild(""EmissionRateMin"", true)).text = editParticleEffect.minEmissionRate; cast(particleEffectWindow.GetChild(""EmissionRateMax"", true)).text = editParticleEffect.maxEmissionRate; switch (editParticleEffect.emitterType) { case EMITTER_BOX: cast(particleEffectWindow.GetChild(""EmitterShape"", true)).selection = 0; break; case EMITTER_SPHERE: cast(particleEffectWindow.GetChild(""EmitterShape"", true)).selection = 1; break; } cast(particleEffectWindow.GetChild(""Scaled"", true)).checked = editParticleEffect.scaled; cast(particleEffectWindow.GetChild(""Sorted"", true)).checked = editParticleEffect.sorted; cast(particleEffectWindow.GetChild(""Relative"", true)).checked = editParticleEffect.relative; } void RefreshParticleEffectMaterial() { UIElement@ container = particleEffectWindow.GetChild(""ParticleMaterialContainer"", true); if (container is null) return; container.RemoveAllChildren(); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, 0, 0); if (editParticleEffect !is null) { if (editParticleEffect.material !is null) nameEdit.text = editParticleEffect.material.name; else { nameEdit.text = ""Materials/Particle.xml""; Material@ res = cache.GetResource(""Material"", ""Materials/Particle.xml""); if (res !is null) editParticleEffect.material = res; } } SubscribeToEvent(nameEdit, ""TextFinished"", ""EditParticleEffectMaterial""); Button@ pickButton = CreateResourcePickerButton(container, null, 0, 0, ""smallButtonPick""); SubscribeToEvent(pickButton, ""Released"", ""PickEditParticleEffectMaterial""); } void NavigateParticleEffectPreview(StringHash eventType, VariantMap& eventData) { int dx = eventData[""DX""].GetInt(); int dy = eventData[""DY""].GetInt(); if (particleEffectPreview.height > 0 && particleEffectPreview.width > 0) { if (!input.keyDown[KEY_LSHIFT]) { float yaw = dy * 20 * time.timeStep; float pitch = dx * 20 * time.timeStep; particleEffectPreviewNode.Rotate(Quaternion(yaw, pitch, 0)); } else { particleEffectPreviewNode.Translate(Vector3(0, 0, 1) * dx * 1.5 * time.timeStep, TS_WORLD); particleEffectPreviewNode.Translate(Vector3(0, 0, 1) * dy * 1.5 * time.timeStep, TS_WORLD); } particleEffectPreview.QueueUpdate(); } } void EditParticleEffectName(StringHash eventType, VariantMap& eventData) { LineEdit@ nameEdit = eventData[""Element""].GetPtr(); String newParticleEffectName = nameEdit.text.Trimmed(); if (!newParticleEffectName.empty && !(editParticleEffect !is null && newParticleEffectName == editParticleEffect.name)) { ParticleEffect@ newParticleEffect = cache.GetResource(""ParticleEffect"", newParticleEffectName); if (newParticleEffect !is null) EditParticleEffect(newParticleEffect); } } void PickEditParticleEffect() { @resourcePicker = GetResourcePicker(StringHash(""ParticleEffect"")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector(localization.Get(""Pick "") + resourcePicker.typeName, ""OK"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter, false); SubscribeToEvent(uiFileSelector, ""FileSelected"", ""PickEditParticleEffectDone""); } void PickEditParticleEffectDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData[""OK""].GetBool()) { @resourcePicker = null; return; } String resourceName = eventData[""FileName""].GetString(); Resource@ res = GetPickedResource(resourceName); if (res !is null) EditParticleEffect(cast(res)); @resourcePicker = null; } void NewParticleEffect() { BeginParticleEffectEdit(); EditParticleEffect(CreateNewParticleEffect()); EndParticleEffectEdit(); } void RevertParticleEffect() { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (editParticleEffect.name.empty) { NewParticleEffect(); return; } BeginParticleEffectEdit(); cache.ReloadResource(editParticleEffect); EndParticleEffectEdit(); RefreshParticleEffectEditor(); } void SaveParticleEffect() { if (editParticleEffect is null || editParticleEffect.name.empty) return; String fullName = cache.GetResourceFileName(editParticleEffect.name); if (fullName.empty) return; File saveFile(fullName, FILE_WRITE); editParticleEffect.Save(saveFile); } void SaveParticleEffectAs() { if (editParticleEffect is null) return; @resourcePicker = GetResourcePicker(StringHash(""ParticleEffect"")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector(""Save particle effect as"", ""Save"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, ""FileSelected"", ""SaveParticleEffectAsDone""); } void SaveParticleEffectAsDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); @resourcePicker = null; if (editParticleEffect is null) return; if (!eventData[""OK""].GetBool()) { @resourcePicker = null; return; } String fullName = eventData[""FileName""].GetString(); // Add default extension for saving if not specified String filter = eventData[""Filter""].GetString(); if (GetExtension(fullName).empty && filter != ""*.*"") fullName = fullName + filter.Substring(1); File saveFile(fullName, FILE_WRITE); if (editParticleEffect.Save(saveFile)) { saveFile.Close(); // Load the new resource to update the name in the editor ParticleEffect@ newEffect = cache.GetResource(""ParticleEffect"", GetResourceNameFromFullName(fullName)); if (newEffect !is null) EditParticleEffect(newEffect); } } void BeginParticleEffectEdit() { if (editParticleEffect is null) return; inParticleEffectRefresh = true; oldParticleEffectState = XMLFile(); XMLElement particleElem = oldParticleEffectState.CreateRoot(""particleeffect""); editParticleEffect.Save(particleElem); } void EndParticleEffectEdit() { if (editParticleEffect is null) return; if (!dragEditAttribute) { EditParticleEffectAction@ action = EditParticleEffectAction(); action.Define(particleEffectEmitter, editParticleEffect, oldParticleEffectState); SaveEditAction(action); } inParticleEffectRefresh = false; particleEffectPreview.QueueUpdate(); } ",12397,False,2433.8391829600705,median "CLASS zcl_abapgit_gui_page_sett_remo DEFINITION PUBLIC INHERITING FROM zcl_abapgit_gui_component FINAL CREATE PRIVATE . PUBLIC SECTION. INTERFACES zif_abapgit_gui_event_handler . INTERFACES zif_abapgit_gui_renderable . INTERFACES zif_abapgit_gui_hotkeys. CLASS-METHODS create IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RETURNING VALUE(ri_page) TYPE REF TO zif_abapgit_gui_renderable RAISING zcx_abapgit_exception . METHODS constructor IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RAISING zcx_abapgit_exception. PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_commit_value_tab, sha1 TYPE zif_abapgit_definitions=>ty_sha1, message TYPE c LENGTH 50, datetime TYPE c LENGTH 20, END OF ty_commit_value_tab . TYPES: ty_commit_value_tab_tt TYPE STANDARD TABLE OF ty_commit_value_tab WITH DEFAULT KEY . CONSTANTS: BEGIN OF c_mode, offline TYPE i VALUE 0, branch TYPE i VALUE 1, tag TYPE i VALUE 2, commit TYPE i VALUE 3, pull_request TYPE i VALUE 4, END OF c_mode . CONSTANTS: BEGIN OF c_id, general TYPE string VALUE 'general', repo_type TYPE string VALUE 'repo_type', head TYPE string VALUE 'head', url TYPE string VALUE 'url', branch TYPE string VALUE 'branch', tag TYPE string VALUE 'tag', commit TYPE string VALUE 'commmit', pull_request TYPE string VALUE 'pull_request', END OF c_id . CONSTANTS: BEGIN OF c_event, save TYPE string VALUE 'save', switch TYPE string VALUE 'switch', choose_url TYPE string VALUE 'choose_url', choose_branch TYPE string VALUE 'choose_branch', choose_tag TYPE string VALUE 'choose_tag', choose_commit TYPE string VALUE 'choose_commit', choose_pull_req TYPE string VALUE 'choose_pull_req', END OF c_event . DATA mo_form TYPE REF TO zcl_abapgit_html_form . DATA mo_form_data TYPE REF TO zcl_abapgit_string_map . DATA mo_form_util TYPE REF TO zcl_abapgit_html_form_utils . DATA mo_validation_log TYPE REF TO zcl_abapgit_string_map . DATA mo_repo TYPE REF TO zcl_abapgit_repo . DATA ms_repo_current TYPE zif_abapgit_persistence=>ty_repo . DATA ms_repo_new TYPE zif_abapgit_persistence=>ty_repo . DATA mv_pull_req TYPE string . DATA mv_mode TYPE i . DATA mv_original_url TYPE string . METHODS init IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RAISING zcx_abapgit_exception . METHODS choose_url RETURNING VALUE(rv_url) TYPE string RAISING zcx_abapgit_exception . METHODS choose_branch RETURNING VALUE(rv_branch) TYPE string RAISING zcx_abapgit_exception . METHODS choose_tag RETURNING VALUE(rv_tag) TYPE string RAISING zcx_abapgit_exception . METHODS choose_commit RETURNING VALUE(rv_commit) TYPE string RAISING zcx_abapgit_exception . METHODS choose_pull_req RETURNING VALUE(rv_pull) TYPE string RAISING zcx_abapgit_exception . METHODS check_protection RAISING zcx_abapgit_exception . METHODS switch_online_offline RAISING zcx_abapgit_exception . METHODS switch_to_branch_tag IMPORTING !iv_name TYPE string OPTIONAL RAISING zcx_abapgit_exception . METHODS switch_to_commit IMPORTING !iv_revert TYPE abap_bool DEFAULT abap_false !iv_commit TYPE string OPTIONAL RAISING zcx_abapgit_exception . METHODS switch_to_pull_req IMPORTING !iv_revert TYPE abap_bool DEFAULT abap_false !iv_pull TYPE string OPTIONAL RAISING zcx_abapgit_exception . METHODS validate_form IMPORTING !io_form_data TYPE REF TO zcl_abapgit_string_map RETURNING VALUE(ro_validation_log) TYPE REF TO zcl_abapgit_string_map RAISING zcx_abapgit_exception . METHODS get_form_schema RETURNING VALUE(ro_form) TYPE REF TO zcl_abapgit_html_form RAISING zcx_abapgit_exception . METHODS read_settings RAISING zcx_abapgit_exception . METHODS save_settings RAISING zcx_abapgit_exception . METHODS checkout_commit_build_list IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo_online EXPORTING !et_value_tab TYPE ty_commit_value_tab_tt !et_commits TYPE zif_abapgit_definitions=>ty_commit_tt RAISING zcx_abapgit_exception . METHODS checkout_commit_build_popup IMPORTING !it_commits TYPE zif_abapgit_definitions=>ty_commit_tt !it_value_tab TYPE ty_commit_value_tab_tt RETURNING VALUE(rs_selected_commit) TYPE zif_abapgit_definitions=>ty_commit RAISING zcx_abapgit_exception . METHODS get_mode IMPORTING !is_repo TYPE zif_abapgit_persistence=>ty_repo RETURNING VALUE(rv_mode) TYPE i . ENDCLASS. CLASS zcl_abapgit_gui_page_sett_remo IMPLEMENTATION. METHOD checkout_commit_build_list. DATA: lv_unix_time TYPE zcl_abapgit_time=>ty_unixtime, lv_date TYPE sy-datum, lv_date_string TYPE c LENGTH 12, lv_time TYPE sy-uzeit, lv_time_string TYPE c LENGTH 10. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_commit, TYPE ty_commit_value_tab. CLEAR: et_commits, et_value_tab. et_commits = zcl_abapgit_git_commit=>get_by_branch( iv_branch_name = io_repo->get_selected_branch( ) iv_repo_url = io_repo->get_url( ) iv_deepen_level = 99 )-commits. DELETE et_commits WHERE sha1 = io_repo->get_selected_commit( ). SORT et_commits BY time DESCENDING. IF et_commits IS INITIAL. zcx_abapgit_exception=>raise( |No commits are available in this branch.| ). ENDIF. LOOP AT et_commits ASSIGNING . APPEND INITIAL LINE TO et_value_tab ASSIGNING . -sha1 = -sha1. -message = -message. lv_unix_time = -time. zcl_abapgit_time=>get_utc( EXPORTING iv_unix = lv_unix_time IMPORTING ev_time = lv_time ev_date = lv_date ). WRITE: lv_date TO lv_date_string, lv_time TO lv_time_string. -datetime = |{ lv_date_string }, | && |{ lv_time_string }|. ENDLOOP. ENDMETHOD. METHOD checkout_commit_build_popup. DATA: lt_columns TYPE zif_abapgit_definitions=>ty_alv_column_tt, li_popups TYPE REF TO zif_abapgit_popups, lt_selected_values TYPE ty_commit_value_tab_tt. FIELD-SYMBOLS: TYPE ty_commit_value_tab, TYPE zif_abapgit_definitions=>ty_alv_column. APPEND INITIAL LINE TO lt_columns ASSIGNING . -name = 'SHA1'. -text = 'Hash'. -length = 8. APPEND INITIAL LINE TO lt_columns ASSIGNING . -name = 'MESSAGE'. -text = 'Message'. APPEND INITIAL LINE TO lt_columns ASSIGNING . -name = 'DATETIME'. -text = 'Datetime'. li_popups = zcl_abapgit_ui_factory=>get_popups( ). li_popups->popup_to_select_from_list( EXPORTING it_list = it_value_tab iv_title = |Checkout Commit| iv_end_column = 83 iv_striped_pattern = abap_true iv_optimize_col_width = abap_false iv_selection_mode = if_salv_c_selection_mode=>single it_columns_to_display = lt_columns IMPORTING et_list = lt_selected_values ). IF lt_selected_values IS INITIAL. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. READ TABLE lt_selected_values ASSIGNING INDEX 1. IF IS NOT ASSIGNED. zcx_abapgit_exception=>raise( |Though result set of popup wasn't empty selected value couldn't retrieved.| ). ENDIF. READ TABLE it_commits INTO rs_selected_commit WITH KEY sha1 = -sha1. ENDMETHOD. METHOD check_protection. IF mo_repo->is_offline( ) = abap_true. zcx_abapgit_exception=>raise( 'Unexpected switch for offline repo' ). ENDIF. IF mo_repo->get_local_settings( )-write_protected = abap_true. zcx_abapgit_exception=>raise( 'Cannot switch. Repository is write-protected in local settings' ). ENDIF. ENDMETHOD. METHOD choose_branch. DATA: lo_repo TYPE REF TO zcl_abapgit_repo_online, lv_url LIKE lo_repo->ms_data-url, lv_branch_name LIKE lo_repo->ms_data-branch_name, ls_branch TYPE zif_abapgit_definitions=>ty_git_branch. IF mo_repo->is_offline( ) = abap_true. RETURN. ENDIF. lo_repo ?= mo_repo. IF lo_repo->ms_data-switched_origin IS NOT INITIAL. SPLIT lo_repo->ms_data-switched_origin AT '@' INTO lv_url lv_branch_name. ELSE. lv_url = lo_repo->get_url( ). lv_branch_name = lo_repo->get_selected_branch( ). ENDIF. ls_branch = zcl_abapgit_ui_factory=>get_popups( )->branch_list_popup( iv_url = lv_url iv_default_branch = lv_branch_name iv_show_new_option = abap_false ). IF ls_branch IS NOT INITIAL. rv_branch = ls_branch-name. ENDIF. ENDMETHOD. METHOD choose_commit. DATA: lo_repo TYPE REF TO zcl_abapgit_repo_online, lt_value_tab TYPE ty_commit_value_tab_tt, lt_commits TYPE zif_abapgit_definitions=>ty_commit_tt, ls_selected_commit TYPE zif_abapgit_definitions=>ty_commit. IF mo_repo->is_offline( ) = abap_true. RETURN. ENDIF. lo_repo ?= mo_repo. checkout_commit_build_list( EXPORTING io_repo = lo_repo IMPORTING et_value_tab = lt_value_tab et_commits = lt_commits ). ls_selected_commit = checkout_commit_build_popup( it_commits = lt_commits it_value_tab = lt_value_tab ). IF ls_selected_commit IS NOT INITIAL. rv_commit = ls_selected_commit-sha1. ENDIF. ENDMETHOD. METHOD choose_pull_req. DATA: lo_repo TYPE REF TO zcl_abapgit_repo_online, lt_pulls TYPE zif_abapgit_pr_enum_provider=>ty_pull_requests, ls_pull LIKE LINE OF lt_pulls. IF mo_repo->is_offline( ) = abap_true. RETURN. ENDIF. lo_repo ?= mo_repo. lt_pulls = zcl_abapgit_pr_enumerator=>new( lo_repo )->get_pulls( ). IF lines( lt_pulls ) = 0. MESSAGE 'No pull requests found' TYPE 'S'. RETURN. ENDIF. ls_pull = zcl_abapgit_ui_factory=>get_popups( )->choose_pr_popup( lt_pulls ). IF ls_pull IS NOT INITIAL. rv_pull = ls_pull-head_url && '@' && ls_pull-head_branch. ENDIF. ENDMETHOD. METHOD choose_tag. DATA: lo_repo TYPE REF TO zcl_abapgit_repo_online, ls_tag TYPE zif_abapgit_definitions=>ty_git_tag. IF mo_repo->is_offline( ) = abap_true. RETURN. ENDIF. lo_repo ?= mo_repo. ls_tag = zcl_abapgit_ui_factory=>get_tag_popups( )->tag_select_popup( lo_repo ). IF ls_tag IS NOT INITIAL. rv_tag = ls_tag-name. ENDIF. ENDMETHOD. METHOD choose_url. "" todo, get url history from DB and show selection popup #3639 rv_url = ''. ENDMETHOD. METHOD constructor. super->constructor( ). CREATE OBJECT mo_validation_log. CREATE OBJECT mo_form_data. init( io_repo ). mv_original_url = ms_repo_current-url. mo_form = get_form_schema( ). mo_form_util = zcl_abapgit_html_form_utils=>create( mo_form ). read_settings( ). ENDMETHOD. METHOD create. DATA lo_component TYPE REF TO zcl_abapgit_gui_page_sett_remo. CREATE OBJECT lo_component EXPORTING io_repo = io_repo. ri_page = zcl_abapgit_gui_page_hoc=>create( iv_page_title = 'Remote Settings' io_page_menu = zcl_abapgit_gui_chunk_lib=>settings_repo_toolbar( iv_key = io_repo->get_key( ) iv_act = zif_abapgit_definitions=>c_action-repo_remote_settings ) ii_child_component = lo_component ). ENDMETHOD. METHOD get_form_schema. DATA: lv_button TYPE string, lv_label TYPE string, lv_icon TYPE string, lv_hint TYPE string, lv_placeholder TYPE string. ro_form = zcl_abapgit_html_form=>create( iv_form_id = 'repo-remote-settings-form' iv_help_page = 'https://docs.abapgit.org/settings-remote.html' ). IF mv_mode = c_mode-offline. lv_button = 'Switch to Online'. lv_icon = 'plug/darkgrey'. lv_label = 'Repository Name'. ELSE. lv_button = 'Switch to Offline'. lv_icon = 'cloud-upload-alt/darkgrey'. lv_label = 'Git Repository URL'. lv_hint = 'URL of original repository'. lv_placeholder = 'https://github.com/...git'. ENDIF. ro_form->start_group( iv_name = c_id-general iv_label = 'General' iv_hint = 'Change the general type and origin of the repository' )->text( iv_name = c_id-repo_type iv_label = |Type of Repository: { zcl_abapgit_html=>icon( lv_icon ) }| iv_readonly = abap_true )->text( iv_name = c_id-url iv_condense = abap_true iv_label = lv_label iv_hint = lv_hint iv_placeholder = lv_placeholder ). IF mv_mode <> c_mode-offline. ro_form->start_group( iv_name = c_id-head iv_label = 'Head' )->text( iv_name = c_id-branch iv_label = 'Branch' iv_hint = 'Switch to a branch of the repository' iv_readonly = abap_true iv_side_action = c_event-choose_branch )->text( iv_name = c_id-tag iv_label = 'Tag' iv_hint = 'Switch to a tag of the repository' iv_readonly = abap_true iv_side_action = c_event-choose_tag )->text( iv_name = c_id-commit iv_label = 'Commit' iv_hint = 'Switch to a commit of the repository' iv_readonly = abap_true iv_side_action = c_event-choose_commit )->text( iv_name = c_id-pull_request iv_label = 'Pull Request' iv_hint = 'Switch to a pull request of the repository or its forks' iv_readonly = abap_true iv_side_action = c_event-choose_pull_req ). ENDIF. ro_form->command( iv_label = 'Save Settings' iv_cmd_type = zif_abapgit_html_form=>c_cmd_type-input_main iv_action = c_event-save )->command( iv_label = lv_button iv_action = c_event-switch )->command( iv_label = 'Back' iv_action = zif_abapgit_definitions=>c_action-go_back ). ENDMETHOD. METHOD get_mode. IF is_repo-offline = abap_true. rv_mode = c_mode-offline. ELSEIF is_repo-selected_commit IS NOT INITIAL. rv_mode = c_mode-commit. ELSEIF is_repo-switched_origin IS NOT INITIAL. rv_mode = c_mode-pull_request. ELSEIF is_repo-branch_name CP zif_abapgit_definitions=>c_git_branch-tags. rv_mode = c_mode-tag. ELSE. rv_mode = c_mode-branch. ENDIF. ENDMETHOD. METHOD init. DATA lv_branch TYPE string. mo_repo = io_repo. "" Get repo settings when starting dialog TRY. ms_repo_current = zcl_abapgit_persist_factory=>get_repo( )->read( mo_repo->get_key( ) ). CATCH zcx_abapgit_not_found. zcx_abapgit_exception=>raise( 'Repository not found' ). ENDTRY. "" Initialize new repo settings which are modified using this form (and saved) mv_mode = get_mode( ms_repo_current ). IF mv_mode = c_mode-pull_request. lv_branch = ms_repo_current-branch_name. REPLACE zif_abapgit_definitions=>c_git_branch-heads_prefix IN lv_branch WITH ''. mv_pull_req = ms_repo_current-url && '@' && lv_branch. SPLIT ms_repo_current-switched_origin AT '@' INTO ms_repo_current-url ms_repo_current-branch_name. ENDIF. ms_repo_new = ms_repo_current. ENDMETHOD. METHOD read_settings. DATA: lv_type TYPE string, lv_url TYPE string, lv_rest TYPE string, lv_branch TYPE string, lv_tag TYPE string, lv_commit TYPE string, lv_pull_req TYPE string. lv_type = 'Online repository'. lv_url = ms_repo_new-url. CASE mv_mode. WHEN c_mode-offline. lv_type = 'Offline repository'. WHEN c_mode-branch. lv_branch = ms_repo_new-branch_name. WHEN c_mode-tag. lv_tag = ms_repo_new-branch_name. WHEN c_mode-commit. lv_commit = ms_repo_new-selected_commit. WHEN c_mode-pull_request. SPLIT ms_repo_new-switched_origin AT '@' INTO lv_url lv_rest.""original repo URL lv_pull_req = mv_pull_req. ENDCASE. mo_form_data->set( iv_key = c_id-repo_type iv_val = lv_type ). mo_form_data->set( iv_key = c_id-url iv_val = lv_url ). mo_form_data->set( iv_key = c_id-branch iv_val = lv_branch ). mo_form_data->set( iv_key = c_id-tag iv_val = lv_tag ). mo_form_data->set( iv_key = c_id-commit iv_val = lv_commit ). mo_form_data->set( iv_key = c_id-pull_request iv_val = lv_pull_req ). "" Set for is_dirty check mo_form_util->set_data( mo_form_data ). ENDMETHOD. METHOD save_settings. DATA: lv_key TYPE zif_abapgit_persistence=>ty_repo-key, lo_repo_online TYPE REF TO zcl_abapgit_repo_online, lo_repo_offline TYPE REF TO zcl_abapgit_repo_offline, lo_branch_list TYPE REF TO zcl_abapgit_git_branch_list, lv_url TYPE string, lv_branch TYPE string, lv_tag TYPE string, lv_commit TYPE string, lv_pull TYPE string. lv_url = mo_form_data->get( c_id-url ). lv_branch = mo_form_data->get( c_id-branch ). lv_tag = mo_form_data->get( c_id-tag ). lv_commit = mo_form_data->get( c_id-commit ). lv_pull = mo_form_data->get( c_id-pull_request ). "" Switch online / offline IF ms_repo_new-offline <> ms_repo_current-offline. "" Remember key, switch, retrieve new instance (todo, refactor #2244) lv_key = ms_repo_current-key. mo_repo->switch_repo_type( ms_repo_new-offline ). mo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( lv_key ). ENDIF. IF mo_repo->is_offline( ) = abap_true. "" Offline: Save repo name lo_repo_offline ?= mo_repo. lo_repo_offline->set_name( lv_url ). ELSE. "" Online: Save url lo_repo_online ?= mo_repo. lo_repo_online->set_url( lv_url ). "" Check branch/tag and reset to default if not found lo_branch_list = zcl_abapgit_git_transport=>branches( lv_url ). TRY. IF lv_branch IS INITIAL AND lv_tag IS INITIAL. lv_branch = lo_branch_list->get_head_symref( ). ELSEIF lv_tag IS INITIAL. lo_branch_list->find_by_name( lv_branch ). ELSE. lo_branch_list->find_by_name( lv_tag ). ENDIF. CATCH zcx_abapgit_exception. lv_branch = lo_branch_list->get_head_symref( ). ENDTRY. mv_original_url = lv_url. ENDIF. CASE mv_mode. WHEN c_mode-branch. switch_to_pull_req( iv_revert = abap_true ). switch_to_commit( iv_revert = abap_true ). switch_to_branch_tag( lv_branch ). WHEN c_mode-tag. switch_to_pull_req( iv_revert = abap_true ). switch_to_commit( iv_revert = abap_true ). switch_to_branch_tag( lv_tag ). WHEN c_mode-commit. switch_to_pull_req( iv_revert = abap_true ). switch_to_commit( iv_commit = lv_commit ). WHEN c_mode-pull_request. switch_to_commit( iv_revert = abap_true ). switch_to_pull_req( iv_pull = lv_pull ). ENDCASE. COMMIT WORK AND WAIT. MESSAGE 'Settings succesfully saved' TYPE 'S'. init( mo_repo ). ENDMETHOD. METHOD switch_online_offline. DATA lv_url TYPE string. ms_repo_new-offline = boolc( ms_repo_new-offline = abap_false ). mv_mode = get_mode( ms_repo_new ). lv_url = mo_form_data->get( c_id-url ). IF mv_mode = c_mode-offline AND lv_url CP 'http*'. "" Switch from URL to name lv_url = zcl_abapgit_url=>name( lv_url ). ENDIF. IF mv_mode <> c_mode-offline AND lv_url NP 'http*' AND mv_original_url CP 'http*'. "" Switch back to original URL lv_url = mv_original_url. ENDIF. mo_form_data->set( iv_key = c_id-url iv_val = lv_url ). ENDMETHOD. METHOD switch_to_branch_tag. DATA lo_repo TYPE REF TO zcl_abapgit_repo_online. check_protection( ). lo_repo ?= mo_repo. lo_repo->select_branch( iv_name ). ENDMETHOD. METHOD switch_to_commit. DATA lo_repo TYPE REF TO zcl_abapgit_repo_online. check_protection( ). lo_repo ?= mo_repo. IF iv_revert = abap_true. lo_repo->select_commit( '' ). ELSE. lo_repo->select_commit( |{ iv_commit }| ). ENDIF. ENDMETHOD. METHOD switch_to_pull_req. DATA: lo_repo TYPE REF TO zcl_abapgit_repo_online, lv_url TYPE string, lv_branch TYPE string. check_protection( ). lo_repo ?= mo_repo. "" Switching twice does not work so reset to original repo first lo_repo->switch_origin( '' ). IF iv_revert = abap_false. SPLIT iv_pull AT '@' INTO lv_url lv_branch. lo_repo->switch_origin( iv_url = lv_url iv_branch = zif_abapgit_definitions=>c_git_branch-heads_prefix && lv_branch ). ENDIF. ENDMETHOD. METHOD validate_form. DATA: lv_url TYPE string, lx_error TYPE REF TO zcx_abapgit_exception. ro_validation_log = mo_form_util->validate( io_form_data ). lv_url = mo_form_data->get( c_id-url ). IF mv_mode = c_mode-offline AND lv_url IS INITIAL. ro_validation_log->set( iv_key = c_id-url iv_val = 'Enter a name for the repository and save' ). ENDIF. IF mv_mode <> c_mode-offline AND lv_url NP 'http*'. ro_validation_log->set( iv_key = c_id-url iv_val = 'Enter the URL of the repository and save' ). ELSEIF mv_mode <> c_mode-offline. TRY. zcl_abapgit_url=>name( iv_url = lv_url iv_validate = abap_true ). CATCH zcx_abapgit_exception INTO lx_error. ro_validation_log->set( iv_key = c_id-url iv_val = lx_error->get_text( ) ). ENDTRY. ENDIF. ENDMETHOD. METHOD zif_abapgit_gui_event_handler~on_event. DATA: lv_url TYPE string, lv_branch TYPE string, lv_tag TYPE string, lv_pull TYPE string, lv_commit TYPE string. mo_form_data = mo_form_util->normalize( ii_event->form_data( ) ). CASE ii_event->mv_action. WHEN zif_abapgit_definitions=>c_action-go_back. IF ms_repo_new <> ms_repo_current. mo_repo->refresh( ). ENDIF. rs_handled-state = zcl_abapgit_gui=>c_event_state-go_back_to_bookmark. WHEN c_event-choose_url. lv_url = choose_url( ). IF lv_url IS INITIAL. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ELSE. ms_repo_new-url = lv_url. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ENDIF. WHEN c_event-choose_branch. lv_branch = choose_branch( ). IF lv_branch IS INITIAL. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ELSE. ms_repo_new-branch_name = lv_branch. mv_mode = c_mode-branch. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ENDIF. WHEN c_event-choose_tag. lv_tag = choose_tag( ). IF lv_tag IS INITIAL. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ELSE. ms_repo_new-branch_name = lv_tag. mv_mode = c_mode-tag. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ENDIF. WHEN c_event-choose_commit. lv_commit = choose_commit( ). IF lv_commit IS INITIAL. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ELSE. ms_repo_new-selected_commit = lv_commit. mv_mode = c_mode-commit. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ENDIF. WHEN c_event-choose_pull_req. lv_pull = choose_pull_req( ). IF lv_pull IS INITIAL. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ELSE. ms_repo_new-switched_origin = ms_repo_new-url. mv_pull_req = lv_pull. mv_mode = c_mode-pull_request. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ENDIF. WHEN c_event-switch OR c_event-save. IF ii_event->mv_action = c_event-switch. switch_online_offline( ). ENDIF. mo_validation_log = validate_form( mo_form_data ). IF mo_validation_log->is_empty( ) = abap_true. save_settings( ). ENDIF. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ENDCASE. "" If staying on form, initialize it with current settings IF rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. mo_form = get_form_schema( ). read_settings( ). ENDIF. ENDMETHOD. METHOD zif_abapgit_gui_hotkeys~get_hotkey_actions. DATA: ls_hotkey_action LIKE LINE OF rt_hotkey_actions. ls_hotkey_action-ui_component = 'Remote'. ls_hotkey_action-description = |Choose Branch|. ls_hotkey_action-action = c_event-choose_branch. ls_hotkey_action-hotkey = |b|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Choose Commit|. ls_hotkey_action-action = c_event-choose_commit. ls_hotkey_action-hotkey = |c|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Choose Pull Request|. ls_hotkey_action-action = c_event-choose_pull_req. ls_hotkey_action-hotkey = |p|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Choose Tag|. ls_hotkey_action-action = c_event-choose_tag. ls_hotkey_action-hotkey = |t|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Choose URL|. ls_hotkey_action-action = c_event-choose_url. ls_hotkey_action-hotkey = |u|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. IF mo_repo->is_offline( ) = abap_true. ls_hotkey_action-description = |Switch to Online|. ls_hotkey_action-action = c_event-switch. ls_hotkey_action-hotkey = |o|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ELSE. ls_hotkey_action-description = |Switch to Offline|. ls_hotkey_action-action = c_event-switch. ls_hotkey_action-hotkey = |o|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ENDIF. ENDMETHOD. METHOD zif_abapgit_gui_renderable~render. gui_services( )->register_event_handler( me ). IF mo_form_util->is_empty( mo_form_data ) = abap_true. read_settings( ). ENDIF. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( `
` ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_repo_top( io_repo = mo_repo iv_show_commit = abap_false iv_interactive_branch = abap_false ) ). ri_html->add( mo_form->render( io_values = mo_form_data io_validation_log = mo_validation_log ) ). ri_html->add( `
` ). gui_services( )->get_hotkeys_ctl( )->register_hotkeys( zif_abapgit_gui_hotkeys~get_hotkey_actions( ) ). ENDMETHOD. ENDCLASS. ",7311,False,1424.04747972557,median "CLASS zcl_abapgit_gui_page_settings DEFINITION PUBLIC FINAL CREATE PUBLIC INHERITING FROM zcl_abapgit_gui_page. PUBLIC SECTION. INTERFACES: zif_abapgit_gui_page_hotkey. CONSTANTS: BEGIN OF c_action, save_settings TYPE string VALUE 'save_settings', END OF c_action. METHODS constructor. METHODS zif_abapgit_gui_page~on_event REDEFINITION. PROTECTED SECTION. METHODS render_content REDEFINITION. PRIVATE SECTION. DATA mo_settings TYPE REF TO zcl_abapgit_settings . DATA mv_error TYPE abap_bool . DATA mt_post_fields TYPE tihttpnvp . METHODS post_commit_msg . METHODS post_development_internals . METHODS post_hotkeys . METHODS render_proxy RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_development_internals RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_form_begin RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_form_end RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_max_lines RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_adt_jump_enabled RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_commit_msg RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS post_proxy . METHODS post IMPORTING !it_post_fields TYPE tihttpnvp . METHODS validate_settings . METHODS parse_post IMPORTING !it_postdata TYPE cnht_post_data_tab RETURNING VALUE(rt_post_fields) TYPE tihttpnvp . METHODS persist_settings RAISING zcx_abapgit_exception . METHODS read_settings . METHODS render_section_begin IMPORTING !iv_header TYPE csequence RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_section_end RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_start_up RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_link_hints RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html RAISING zcx_abapgit_exception . METHODS render_hotkeys RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html RAISING zcx_abapgit_exception . METHODS get_possible_hotkey_actions RETURNING VALUE(rt_hotkey_actions) TYPE zif_abapgit_gui_page_hotkey=>tty_hotkey_action RAISING zcx_abapgit_exception . METHODS get_default_hotkeys RETURNING VALUE(rt_default_hotkeys) TYPE zif_abapgit_definitions=>tty_hotkey RAISING zcx_abapgit_exception . METHODS is_post_field_checked IMPORTING iv_name TYPE string RETURNING VALUE(rv_return) TYPE abap_bool . METHODS render_parallel_proc RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . ENDCLASS. CLASS ZCL_ABAPGIT_GUI_PAGE_SETTINGS IMPLEMENTATION. METHOD constructor. super->constructor( ). ms_control-page_title = 'SETTINGS'. ENDMETHOD. METHOD get_default_hotkeys. DATA: lt_actions TYPE zif_abapgit_gui_page_hotkey=>tty_hotkey_action, ls_hotkey LIKE LINE OF rt_default_hotkeys. FIELD-SYMBOLS: LIKE LINE OF lt_actions. lt_actions = zcl_abapgit_hotkeys=>get_default_hotkeys_from_pages( ). LOOP AT lt_actions ASSIGNING . ls_hotkey-action = -action. ls_hotkey-sequence = -default_hotkey. INSERT ls_hotkey INTO TABLE rt_default_hotkeys. ENDLOOP. ENDMETHOD. METHOD get_possible_hotkey_actions. DATA: ls_hotkey_action LIKE LINE OF rt_hotkey_actions. rt_hotkey_actions = zcl_abapgit_hotkeys=>get_default_hotkeys_from_pages( ). "" insert empty row at the beginning, so that we can unset a hotkey INSERT ls_hotkey_action INTO rt_hotkey_actions INDEX 1. ENDMETHOD. METHOD is_post_field_checked. FIELD-SYMBOLS: TYPE ihttpnvp. READ TABLE mt_post_fields ASSIGNING WITH KEY name = iv_name. IF sy-subrc = 0 AND ( -value = abap_true ""HTML value when using standard netweaver GUI OR -value = 'on' ). ""HTML value when using Netweaver Java GUI rv_return = abap_true. ENDIF. ENDMETHOD. METHOD parse_post. DATA lv_serialized_post_data TYPE string. CONCATENATE LINES OF it_postdata INTO lv_serialized_post_data. rt_post_fields = zcl_abapgit_html_action_utils=>parse_fields( lv_serialized_post_data ). ENDMETHOD. METHOD persist_settings. DATA lo_settings_persistence TYPE REF TO zcl_abapgit_persist_settings. lo_settings_persistence = zcl_abapgit_persist_settings=>get_instance( ). lo_settings_persistence->modify( mo_settings ). MESSAGE 'Settings succesfully saved' TYPE 'S'. ENDMETHOD. METHOD post. DATA: lv_i_param_value TYPE i. FIELD-SYMBOLS: TYPE ihttpnvp. CREATE OBJECT mo_settings. mt_post_fields = it_post_fields. post_proxy( ). post_commit_msg( ). post_development_internals( ). * todo, refactor to private POST_* methods IF is_post_field_checked( 'show_default_repo' ) = abap_true. mo_settings->set_show_default_repo( abap_true ). ELSE. mo_settings->set_show_default_repo( abap_false ). ENDIF. READ TABLE mt_post_fields ASSIGNING WITH KEY name = 'max_lines'. IF sy-subrc = 0. lv_i_param_value = -value. mo_settings->set_max_lines( lv_i_param_value ). ELSE. mo_settings->set_max_lines( 0 ). ENDIF. IF is_post_field_checked( 'adt_jump_enabled' ) = abap_true. mo_settings->set_adt_jump_enanbled( abap_true ). ELSE. mo_settings->set_adt_jump_enanbled( abap_false ). ENDIF. IF is_post_field_checked( 'link_hints_enabled' ) = abap_true. mo_settings->set_link_hints_enabled( abap_true ). ELSE. mo_settings->set_link_hints_enabled( abap_false ). ENDIF. READ TABLE mt_post_fields ASSIGNING WITH KEY name = 'link_hint_key'. IF sy-subrc = 0. mo_settings->set_link_hint_key( |{ -value }| ). ENDIF. READ TABLE mt_post_fields ASSIGNING WITH KEY name = 'link_hint_background_color'. IF sy-subrc = 0. mo_settings->set_link_hint_background_color( |{ -value }| ). ENDIF. IF is_post_field_checked( 'parallel_proc_disabled' ) = abap_true. mo_settings->set_parallel_proc_disabled( abap_true ). ELSE. mo_settings->set_parallel_proc_disabled( abap_false ). ENDIF. post_hotkeys( ). ENDMETHOD. METHOD post_commit_msg. DATA: lv_i_param_value TYPE i. FIELD-SYMBOLS: TYPE ihttpnvp. READ TABLE mt_post_fields ASSIGNING WITH KEY name = 'comment_length'. IF sy-subrc = 0. lv_i_param_value = -value. IF lv_i_param_value < zcl_abapgit_settings=>c_commitmsg_comment_length_dft. lv_i_param_value = zcl_abapgit_settings=>c_commitmsg_comment_length_dft. ENDIF. mo_settings->set_commitmsg_comment_length( lv_i_param_value ). ELSE. mo_settings->set_commitmsg_comment_length( zcl_abapgit_settings=>c_commitmsg_comment_length_dft ). ENDIF. READ TABLE mt_post_fields ASSIGNING WITH KEY name = 'body_size'. IF sy-subrc = 0. lv_i_param_value = -value. IF lv_i_param_value < zcl_abapgit_settings=>c_commitmsg_body_size_dft. lv_i_param_value = zcl_abapgit_settings=>c_commitmsg_body_size_dft. ENDIF. mo_settings->set_commitmsg_body_size( lv_i_param_value ). ELSE. mo_settings->set_commitmsg_body_size( zcl_abapgit_settings=>c_commitmsg_body_size_dft ). ENDIF. ENDMETHOD. METHOD post_development_internals. IF is_post_field_checked( 'critical_tests' ) = abap_true. mo_settings->set_run_critical_tests( abap_true ). ELSE. mo_settings->set_run_critical_tests( abap_false ). ENDIF. IF is_post_field_checked( 'experimental_features' ) = abap_true. mo_settings->set_experimental_features( abap_true ). ELSE. mo_settings->set_experimental_features( abap_false ). ENDIF. ENDMETHOD. METHOD post_hotkeys. DATA: lv_column TYPE string, lt_key_bindings TYPE zif_abapgit_definitions=>tty_hotkey. FIELD-SYMBOLS: TYPE ihttpnvp, TYPE zif_abapgit_definitions=>ty_hotkey. LOOP AT mt_post_fields ASSIGNING WHERE name CP 'key*'. FIND FIRST OCCURRENCE OF REGEX `key_(.*)_` IN -name SUBMATCHES lv_column. INSERT INITIAL LINE INTO TABLE lt_key_bindings ASSIGNING . CASE lv_column. WHEN 'sequence'. -sequence = -value. WHEN 'action'. -action = -value. ENDCASE. ENDLOOP. DELETE lt_key_bindings WHERE sequence IS INITIAL OR action IS INITIAL. mo_settings->set_hotkeys( lt_key_bindings ). ENDMETHOD. METHOD post_proxy. FIELD-SYMBOLS: TYPE ihttpnvp. READ TABLE mt_post_fields ASSIGNING WITH KEY name = 'proxy_url'. IF sy-subrc <> 0. mv_error = abap_true. ENDIF. mo_settings->set_proxy_url( -value ). READ TABLE mt_post_fields ASSIGNING WITH KEY name = 'proxy_port'. IF sy-subrc <> 0. mv_error = abap_true. ENDIF. mo_settings->set_proxy_port( -value ). IF is_post_field_checked( 'proxy_auth' ) = abap_true. mo_settings->set_proxy_authentication( abap_true ). ELSE. mo_settings->set_proxy_authentication( abap_false ). ENDIF. ENDMETHOD. METHOD read_settings. DATA lo_settings_persistence TYPE REF TO zcl_abapgit_persist_settings. lo_settings_persistence = zcl_abapgit_persist_settings=>get_instance( ). mo_settings = lo_settings_persistence->read( ). ENDMETHOD. METHOD render_adt_jump_enabled. DATA lv_checked TYPE string. IF mo_settings->get_adt_jump_enabled( ) = abap_true. lv_checked = 'checked'. ENDIF. CREATE OBJECT ro_html. ro_html->add( |

ABAP Development Tools (ADT)

| ). ro_html->add( ` Enable jump to ADT first` ). ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_commit_msg. CREATE OBJECT ro_html. ro_html->add( |

Commit Message

| ). ro_html->add( || ). ro_html->add( |
| ). ro_html->add( |get_commitmsg_comment_length( ) }"">| ). ro_html->add( |
| ). ro_html->add( || ). ro_html->add( |
| ). ro_html->add( |get_commitmsg_body_size( ) }"">| ). ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_content. CREATE OBJECT ro_html. read_settings( ). ro_html->add( render_form_begin( ) ). ro_html->add( render_section_begin( |Global settings| ) ). ro_html->add( render_proxy( ) ). ro_html->add( |
| ). ro_html->add( render_commit_msg( ) ). ro_html->add( |
| ). ro_html->add( render_development_internals( ) ). ro_html->add( render_section_end( ) ). ro_html->add( render_section_begin( |User specific settings| ) ). ro_html->add( render_start_up( ) ). ro_html->add( render_max_lines( ) ). ro_html->add( |
| ). ro_html->add( render_adt_jump_enabled( ) ). ro_html->add( |
| ). ro_html->add( render_parallel_proc( ) ). ro_html->add( |
| ). ro_html->add( render_link_hints( ) ). ro_html->add( |
| ). ro_html->add( render_hotkeys( ) ). ro_html->add( render_section_end( ) ). ro_html->add( render_form_end( ) ). ENDMETHOD. METHOD render_development_internals. DATA: lv_critical_tests TYPE string, lv_experimental TYPE string. IF mo_settings->get_run_critical_tests( ) = abap_true. lv_critical_tests = 'checked'. ENDIF. IF mo_settings->get_experimental_features( ) = abap_true. lv_experimental = 'checked'. ENDIF. CREATE OBJECT ro_html. ro_html->add( |

abapGit Development Internals settings

| ). ro_html->add( ` Enable critical unit tests (see LTCL_DANGEROUS)` ). ro_html->add( |
| ). ro_html->add( ` Enable experimental features` ). ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_form_begin. CREATE OBJECT ro_html. ro_html->add( '
' ). ro_html->add( `
` ). ENDMETHOD. METHOD render_form_end. CREATE OBJECT ro_html. ro_html->add( '' ). ro_html->add( '
' ). ro_html->add( '
' ). ENDMETHOD. METHOD render_hotkeys. DATA: lv_index TYPE i, lt_hotkeys TYPE zif_abapgit_definitions=>tty_hotkey, lv_selected TYPE string, lt_actions TYPE zif_abapgit_gui_page_hotkey=>tty_hotkey_action. FIELD-SYMBOLS: LIKE LINE OF lt_hotkeys, LIKE LINE OF lt_actions. lt_hotkeys = mo_settings->get_hotkeys( ). IF lines( lt_hotkeys ) = 0. lt_hotkeys = get_default_hotkeys( ). ENDIF. DO 3 TIMES. APPEND INITIAL LINE TO lt_hotkeys. ENDDO. CREATE OBJECT ro_html. ro_html->add( |

Hotkeys

| ). ro_html->add( |(Only available with installed abapGit repo)| ). ro_html->add( |
| ). ro_html->add( |
| ). ro_html->add( '' ). ro_html->add( '' ). lt_actions = get_possible_hotkey_actions( ). LOOP AT lt_hotkeys ASSIGNING . lv_index = sy-tabix. ro_html->add( '' ). ro_html->add( || ). ro_html->add( |' ). ro_html->add( '' ). ENDLOOP. ro_html->add( '' ). ro_html->add( '' ). ro_html->add( '
keyaction
-sequence }"">
' ). ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_link_hints. DATA: lv_checked TYPE string, lv_link_hint_key TYPE char01, lv_link_background_color TYPE string. IF mo_settings->get_link_hints_enabled( ) = abap_true. lv_checked = 'checked'. ENDIF. lv_link_hint_key = mo_settings->get_link_hint_key( ). lv_link_background_color = mo_settings->get_link_hint_background_color( ). CREATE OBJECT ro_html. ro_html->add( |

Vimium like link hints

| ). ro_html->add( ` Enable Vimium like link hints` ). ro_html->add( |
| ). ro_html->add( |
| ). ro_html->add( | Single key to activate links| ). ro_html->add( |
| ). ro_html->add( |
| ). ro_html->add( | Background Color (HTML colors e.g. lightgreen or #42f47a)| ). ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_max_lines. CREATE OBJECT ro_html. ro_html->add( |

List size

| ). ro_html->add( || ). ro_html->add( |
| ). ro_html->add( `get_max_lines( ) && `"">` ). ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_parallel_proc. DATA lv_checked TYPE string. IF mo_settings->get_parallel_proc_disabled( ) = abap_true. lv_checked = 'checked'. ENDIF. CREATE OBJECT ro_html. ro_html->add( |

Parallel processing

| ). ro_html->add( ` Disable parallel processing` ). ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_proxy. CREATE OBJECT ro_html. ro_html->add( |

Proxy

| ). ro_html->add( || ). ro_html->add( |
| ). ro_html->add( `get_proxy_url( ) && `"">` ). ro_html->add( |
| ). ro_html->add( || ). ro_html->add( |
| ). ro_html->add( `get_proxy_port( ) && `"">` ). ro_html->add( |
| ). ro_html->add( || ). IF mo_settings->get_proxy_authentication( ) = abap_true. ro_html->add( `` ). ELSE. ro_html->add( `` ). ENDIF. ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_section_begin. CREATE OBJECT ro_html. ro_html->add( |

{ iv_header }

| ). ro_html->add( |
| ). ENDMETHOD. METHOD render_section_end. CREATE OBJECT ro_html. ro_html->add( |
| ). ENDMETHOD. METHOD render_start_up. DATA lv_checked TYPE string. IF mo_settings->get_show_default_repo( ) = abap_true. lv_checked = 'checked'. ENDIF. CREATE OBJECT ro_html. ro_html->add( |

Start up

| ). ro_html->add( ` Show last repo` ). ro_html->add( |
| ). ro_html->add( |
| ). ENDMETHOD. METHOD validate_settings. IF ( mo_settings->get_proxy_url( ) IS NOT INITIAL AND mo_settings->get_proxy_port( ) IS INITIAL ) OR ( mo_settings->get_proxy_url( ) IS INITIAL AND mo_settings->get_proxy_port( ) IS NOT INITIAL ). MESSAGE 'If specifying proxy, specify both URL and port' TYPE 'W'. ENDIF. ENDMETHOD. METHOD zif_abapgit_gui_page_hotkey~get_hotkey_actions. RETURN. ENDMETHOD. METHOD zif_abapgit_gui_page~on_event. * todo, check input values eg INT DATA: lt_post_fields TYPE tihttpnvp. CASE iv_action. WHEN c_action-save_settings. lt_post_fields = parse_post( it_postdata ). post( lt_post_fields ). validate_settings( ). IF mv_error = abap_true. MESSAGE 'Error when saving settings. Open an issue at https://github.com/larshp/abapGit' TYPE 'E'. ELSE. persist_settings( ). ENDIF. ev_state = zif_abapgit_definitions=>c_event_state-go_back. ENDCASE. ENDMETHOD. ENDCLASS. ",5546,False,1206.5194198397317,median "/* StateBufferLoop.ino This example implements the for/next picture drawing loop as a state machine. Pro: Display refresh is distributed over several steps (only one page is drawn at a time, which consumes lesser time than refreshing the complete screen) Contra: (A) Artefacts may be visible. (B) It is more difficult to switch between different screens. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); } uint16_t seconds = 0; // this task should be called as often as possible void high_speed_task(void) { // place your commands here, they will be executed very often // as an example, calculated the seconds since startup... seconds = millis() / 1000; } // this procedure contains the u8g2 draw commands to draw someting on the screen void draw() { u8g2.setFont(u8g2_font_logisoso58_tn); u8g2.setCursor(0,60); u8g2.print(seconds); } // this is the state machine, which will replace the do - while loop void draw_page(void) { static uint8_t is_next_page = 0; // call to first page, if required if ( is_next_page == 0 ) { u8g2.firstPage(); is_next_page = 1; } // draw our screen draw(); // call to next page if ( u8g2.nextPage() == 0 ) { is_next_page = 0; // ensure, that first page is called } } // arduno main loop void loop(void) { high_speed_task(); draw_page(); } ",16164,True,4910.728910722766,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// // TODO (chiedozi): TabbedViewNavigator should override setActive and activate // the correct ViewNavigator. package spark.components { import flash.display.Stage; import flash.events.Event; import flash.events.IEventDispatcher; import flash.events.MouseEvent; import mx.core.ISelectableList; import mx.core.IVisualElement; import mx.core.UIComponent; import mx.core.mx_internal; import mx.effects.IEffect; import mx.effects.Parallel; import mx.events.CollectionEvent; import mx.events.CollectionEventKind; import mx.events.EffectEvent; import mx.events.FlexEvent; import mx.events.PropertyChangeEvent; import mx.events.PropertyChangeEventKind; import mx.managers.LayoutManager; import mx.resources.ResourceManager; import spark.components.supportClasses.ButtonBarBase; import spark.components.supportClasses.ViewNavigatorBase; import spark.effects.Animate; import spark.effects.animation.MotionPath; import spark.effects.animation.SimpleMotionPath; import spark.events.ElementExistenceEvent; import spark.events.IndexChangeEvent; import spark.events.RendererExistenceEvent; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when the current view navigator changes as a result of * a change to the selectedIndex property or a change * to the selected tab in the TabBar control. * * @eventType spark.events.IndexChangeEvent.CHANGE * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""change"", type=""spark.events.IndexChangeEvent"")] /** * Dispatched before the selected view navigator is changed. * Canceling this event prevents the active view navigator * from changing. * * @eventType spark.events.IndexChangeEvent.CHANGING * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""changing"", type=""spark.events.IndexChangeEvent"")] /** * Dispatched when the collection of view navigators managed by the * TabbedViewNavigator changes. * * @eventType mx.events.CollectionEvent.COLLECTION_CHANGE * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""collectionChange"", type=""mx.events.CollectionEvent"")] /** * Dispatched when the view navigator's selected index changes. * When this event is dispatched, the selectedIndex * and selectedNavigator properties reference the * newly selected view navigator. * * @eventType mx.events.FlexEvent.VALUE_COMMIT * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ [Event(name=""valueCommit"", type=""mx.events.FlexEvent"")] //-------------------------------------- // Other metadata //-------------------------------------- [IconFile(""TabbedViewNavigator.png"")] /** * The TabbedViewNavigator class is a container that manages a collection * of view navigator containers. * Only one view navigator is active and visible at a time. * This class includes a TabBar control that provides the ability to toggle between * the collection of view navigators. * *

The following image shows a TabbedViewNavigator with three sections: * Employees, Contacts, and Search:

* *

* *

* *

The TabbedViewNavigatorApplication container automatically creates * a single TabbedViewNavigator container for the entire application. * You can reference the TabbedViewNavigator object by using the navigator * property of the TabbedViewNavigatorApplication container.

* *

The active or selected navigator can be changed by clicking the corresponding * tab in the TabBar or by changing the selectedIndex property of * the component.

* *

The contents of a child view navigator is destroyed when it is deactivate, * and dynamically created when activated.

* * @see spark.components.View * @see spark.components.ViewNavigator * @see spark.components.TabBar * * @includeExample examples/TabbedViewNavigatorExample.mxml -noswf * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class TabbedViewNavigator extends ViewNavigatorBase implements ISelectableList { //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- // TODO (chiedozi): Consider having a NO_SELECTION constant to differentiate // between NO_PROPOSED_SELECTION and clearing the selection. See List. It // seems redundant because TabbedViewNavigator expects requireSelection to be // true on its TabBar. /** * @private * Static constant representing no proposed selection. */ private static const NO_PROPOSED_SELECTION:int = -1; /** * @private * The animation duration used when hiding and showing the action bar. */ private static const TAB_BAR_ANIMATION_DURATION:Number = 250; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function TabbedViewNavigator() { super(); addEventListener(ElementExistenceEvent.ELEMENT_ADD, elementAddHandler); addEventListener(ElementExistenceEvent.ELEMENT_REMOVE, elementRemoveHandler); } //-------------------------------------------------------------------------- // // Skin Parts // //-------------------------------------------------------------------------- [Bindable] [SkinPart(required=""false"")] /** * A skin part that defines the tab bar of the navigator. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var tabBar:ButtonBarBase; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var animateTabBarVisbility:Boolean = false; /** * @private */ private var contentGroupProps:Object; /** * @private * Determines if a changing event has already been dispatched. * This was introduced to prevent the IndexChangeEvent from * dispatching twice when the tabBar selection changes. */ private var changingEventDispatched:Boolean = false; /** * @private */ private var dataProviderChanged:Boolean = false; /** * @private */ private var explicitTabBarMouseEnabled:Boolean = false; /** * @private * Keeps track of the tab that was last selected. See * tabBarRendererClicked() for information on how it's used. */ private var lastSelectedIndex:int = -1; /** * @private */ private var selectedIndexChanged:Boolean = false; /** * @private */ private var selectedIndexAdjusted:Boolean = false; /** * @private */ private var showingTabBar:Boolean; /** * @private */ private var tabBarVisibilityEffect:IEffect; /** * @private */ private var tabBarProps:Object; /** * @private */ private var tabBarVisibilityChanged:Boolean = false; /** * @private */ mx_internal var selectedNavigatorChangingView:Boolean = false; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // activeView //---------------------------------- [Bindable(""viewChangeComplete"")] /** * @private */ override public function get activeView():View { if (selectedNavigator) return selectedNavigator.activeView; return null; } //---------------------------------- // exitApplicationOnBackKey //---------------------------------- /** * @private */ override mx_internal function get exitApplicationOnBackKey():Boolean { if (selectedNavigator) return selectedNavigator.exitApplicationOnBackKey; return super.exitApplicationOnBackKey; } //---------------------------------- // maintainNavigationStack //---------------------------------- private var _maintainNavigationStack:Boolean = true; /** * @private * Specifies whether the navigation stack of the view navigator * should remain intact when the view navigator is deactivated. * If true, when reactivated the view history * remains the same. * If false, the navigator displays the * first view in its navigation stack. * * @default true * * @see spark.components.ViewNavigator * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function get maintainNavigationStack():Boolean { return _maintainNavigationStack; } /** * @private */ mx_internal function set maintainNavigationStack(value:Boolean):void { _maintainNavigationStack = value; } //---------------------------------- // navigators //---------------------------------- /** * The view navigators that are managed by this TabbedViewNavigator. * Each view navigator is represented as a tab in the tab bar * of this TabbedViewNavigator. * Only one view navigator can be active at a time. * You can reference the active view navigator by using * the selectedNavigator property. * *

Changing this property causes the current view navigator to be removed, * and sets the selectedIndex to 0. * This operation cannot be canceled and is committed immediately.

* * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get navigators():Vector. { var mxmlContent:Array = currentContentGroup.getMXMLContent(); if (!mxmlContent) return null; // When this class was first released, navigators was typed Vector // and not Array. In 4.6, TabbedViewNavigator moved away from this // model and uses mxmlContent to manage children. To maintain backwards // compatibility, the return type for this method remained the same. // As a result, the mxmlContent array will need to converted. return Vector.(mxmlContent); } /** * @private */ public function set navigators(value:Vector.):void { // When this class was first released, navigators was typed Vector // and not Array. In 4.6, TabbedViewNavigator moved away from this // model and uses mxmlContent to manage children. To maintain backwards // compatibility, the return type for this method remained the same. // As a result, the value vector needs to be converted to an array var contentArray:Array = new Array(); for each (var navigator:ViewNavigatorBase in value) { contentArray.push(navigator); setupNavigator(navigator); } mxmlContent = contentArray; // The proposed selected index is reset because it is no longer valid // since the array of navigators has changed. selectedIndexChanged = false; // Invalidate property flags dataProviderChanged = true; invalidateProperties(); // Notify listeners that the collection changed internalDispatchEvent(CollectionEventKind.RESET); } //---------------------------------- // selectedNavigator //---------------------------------- [Bindable(""change"")] /** * The selected view navigator for the TabbedViewNavigator. * Only one view navigator can be active at a time. * The active view navigator can be set by changing the * selectedIndex property or by selecting * a tab in the TabBar control. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get selectedNavigator():ViewNavigatorBase { if (length == 0 || selectedIndex < 0 || selectedIndex >= length) return null; return getElementAt(selectedIndex) as ViewNavigatorBase; } //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- /** * Hides the tab bar of the navigator. * * @param animate Indicates whether a hide effect should play * as the tab bar disappears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function hideTabBar(animate:Boolean = true):void { if (!tabBar) return; showingTabBar = false; animateTabBarVisbility = animate; tabBarVisibilityChanged = true; invalidateProperties(); } /** * Shows the tab bar of the navigator * * @param animate Indicates whether a show effect should play * as the tab bar appears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function showTabBar(animate:Boolean = true):void { if (!tabBar) return; showingTabBar = true; animateTabBarVisbility = animate; tabBarVisibilityChanged = true; invalidateProperties(); } /** * @private * Updates the navigator's state based on the properties set * on the active view. The main use cases are to hide the * TabBar and the change the overlay state. * * @param view The active view. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ override public function updateControlsForView(view:View):void { super.updateControlsForView(view); if (view) { if (tabBar) tabBar.visible = tabBar.includeInLayout = view.tabBarVisible; overlayControls = view.overlayControls; } else { // If the current view is null, the tab bar is shown so that the // user still has a ui for changing the selected tab. if (tabBar) tabBar.visible = tabBar.includeInLayout = true; overlayControls = false; } tabBarVisibilityChanged = false; } /** * Calls the backKeyUpHandler() of the selected navigator. * *

TabbedViewNavigatorApplication automatically calls this method when * the back key is pressed.

* * @langversion 3.0 * @playerversion AIR 3.1 * @productversion Flex 4.6 */ override public function backKeyUpHandler():void { if (selectedNavigator) selectedNavigator.backKeyUpHandler(); } //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- /** * @private * Calculates the final positions for the tab bar visibility animations. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function prepareTabBarForAnimation(showAnimation:Boolean):void { var animateTabBarUp:Boolean; if (overlayControls) { // If the control is overlaid on top, the tabBar is animated up if // the tabBar is above the center of the navigator animateTabBarUp = (tabBar.y + (tabBar.height / 2)) <= height / 2; } else { // The tabBar is animated up if it is above the contentGroup animateTabBarUp = tabBar.y <= contentGroup.y; } // Need to validate to capture final positions and sizes of skin parts LayoutManager.getInstance().validateNow(); // This will store the final location and sizes of the components tabBarProps.end = captureAnimationValues(tabBar); contentGroupProps.end = captureAnimationValues(contentGroup); if (tabBarVisibilityChanged) { if (animateTabBarUp) { if (tabBarProps.start.visible) tabBarProps.end.y = -tabBar.height; else tabBarProps.start.y = -tabBar.height; } else { if (tabBarProps.start.visible) tabBarProps.end.y = this.height; else tabBarProps.start.y = this.height; } } tabBar.visible = true; tabBar.includeInLayout = false; tabBar.cacheAsBitmap = true; } /** * @private */ override mx_internal function canRemoveCurrentView():Boolean { return (!selectedNavigator || selectedNavigator.canRemoveCurrentView()); } /** * @private */ private function addNavigatorListeners(navigator:ViewNavigatorBase):void { navigator.addEventListener(""viewChangeComplete"", navigator_viewChangeCompleteHandler); navigator.addEventListener(""viewChangeStart"", navigator_viewChangeStartHandler); navigator.addEventListener(ElementExistenceEvent.ELEMENT_ADD, navigator_elementAddHandler); navigator.addEventListener(ElementExistenceEvent.ELEMENT_REMOVE, navigator_elementRemoveHandler); } /** * @private */ private function removeNavigatorListeners(navigator:ViewNavigatorBase):void { navigator.removeEventListener(""viewChangeComplete"", navigator_viewChangeCompleteHandler); navigator.removeEventListener(""viewChangeStart"", navigator_viewChangeStartHandler); navigator.removeEventListener(ElementExistenceEvent.ELEMENT_ADD, navigator_elementAddHandler); navigator.removeEventListener(ElementExistenceEvent.ELEMENT_REMOVE, navigator_elementRemoveHandler); } /** * @private */ private function setupNavigator(navigator:ViewNavigatorBase):void { navigator.setParentNavigator(this); navigator.visible = false; navigator.includeInLayout = false; // All navigators should be inactive when initialized. The proper // navigator will be activated during commitProperties(). navigator.setActive(false); startTrackingUpdates(navigator); } /** * @private */ private function cleanUpNavigator(navigator:ViewNavigatorBase):void { navigator.setParentNavigator(null); if (navigator.isActive) navigator.setActive(false); if (navigator.activeView) { navigator.activeView.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } removeNavigatorListeners(navigator); stopTrackingUpdates(navigator); } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ override protected function commitProperties():void { var changeEvent:IndexChangeEvent; if (selectedIndexChanged || selectedIndexAdjusted || dataProviderChanged) { var navigator:ViewNavigatorBase; // Store the old index var oldIndex:int = _selectedIndex; if (selectedIndex >= length) selectedIndex = (length > 0) ? 0 : NO_PROPOSED_SELECTION; var indexChangedPrevented:Boolean = false; // The selected index property can be changed programmitically on the // TabbedViewNavigator or by its tab bar in response to a user action. If // this was initiated by the tab bar, a chaning event would have already been // dispatched in tabBar_indexChanging(). if (initialized && selectedIndexChanged && !changingEventDispatched) { // If the active view's REMOVING event or the navigator's // CHANGING event was canceled, prevent the index change if (!indexCanChange(selectedIndex)) { _proposedSelectedIndex = NO_PROPOSED_SELECTION; indexChangedPrevented = true; } } changingEventDispatched = false; if (!indexChangedPrevented) { // If the data provider has changed, the navigator elements have // already been removed, so the following code doesn't need to run if (!selectedIndexAdjusted && !dataProviderChanged && _selectedIndex >= 0 && _selectedIndex < length) { navigator = getElementAt(_selectedIndex) as ViewNavigatorBase; navigator.setActive(false, !maintainNavigationStack); navigator.visible = false; navigator.includeInLayout = false; if (navigator.activeView) navigator.activeView.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); removeNavigatorListeners(navigator); } commitSelection(); if (_selectedIndex >= 0) { // If there is no focus or the item that had focus isn't // on the display list anymore, update the focus to be // the active view or the view navigator updateFocus(); navigator = getElementAt(_selectedIndex) as ViewNavigatorBase; navigator.setActive(true); navigator.visible = true; navigator.includeInLayout = true; addNavigatorListeners(navigator); // Update the states of the controls on the newly activated view navigator. // The updateControlsForView() method will automatically bubble up to all // parents of the navigator. navigator.updateControlsForView(navigator.activeView); // Force a validation of the new navigator to prevent a flicker from // occurring in cases where multiple validation passes are required // to completely validate a view if (initialized) currentContentGroup.validateNow(); if (navigator.activeView) { navigator.activeView.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } } // Dispatch selection change event if (hasEventListener(IndexChangeEvent.CHANGE)) { changeEvent = new IndexChangeEvent(IndexChangeEvent.CHANGE, false, false); changeEvent.oldIndex = oldIndex; changeEvent.newIndex = _selectedIndex; } } selectedIndexAdjusted = false; dataProviderChanged = false; selectedIndexChanged = false; } if (tabBarVisibilityChanged) commitVisibilityChanges(); // When true, this flag prevents tab bar animations from running. This flag // is only set to true if the application received an orientation event this // frame (See ViewNavigatorBase). The flag is reset at the end of commitProperties // so that animations run again. if (disableNextControlAnimation) disableNextControlAnimation = false; // Call base class' commitProperties after the above so that state changes // as a result of overlayControls are caught. This should be okay because // TabbedViewNavigator doesn't need any properties in its base class being // validated to complete the above code super.commitProperties(); // Dispatch the index change event after super.commitProperties() has changed // so the callbacks can deal with state changes performed by commitProperties. if (changeEvent) dispatchEvent(changeEvent); } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function commitSelection():void { _selectedIndex = _proposedSelectedIndex; _proposedSelectedIndex = NO_PROPOSED_SELECTION; lastSelectedIndex = _selectedIndex; if (hasEventListener(FlexEvent.VALUE_COMMIT)) dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } /** * @private * Commits the requested visibility changes made to the action * bar and tab bar. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function commitVisibilityChanges():void { // Can't change the visibility during a view transition if (selectedNavigatorChangingView) return; // If an animation is running, end it if (tabBarVisibilityEffect) tabBarVisibilityEffect.end(); // Change the visibility of the tabBar if the desired state // is different than the current state if (tabBar && showingTabBar != tabBar.visible) { // The animateTabBarVisibility flag is set to true if the // hideTabBar() or showTabBar() methods are called with the // animate flag set to true if (!disableNextControlAnimation && transitionsEnabled && animateTabBarVisbility) { tabBarProps = {target:tabBar, showing:showingTabBar}; tabBarVisibilityEffect = showingTabBar ? createTabBarShowEffect() : createTabBarHideEffect(); tabBarVisibilityEffect.addEventListener(EffectEvent.EFFECT_END, visibilityAnimation_effectEndHandler); tabBarVisibilityEffect.play(); } else { // Since the visibility is not being animated, toggle the state tabBar.visible = tabBar.includeInLayout = showingTabBar; if (activeView) activeView.setTabBarVisible(showingTabBar); } } tabBarVisibilityChanged = false; } /** * Creates the effect to play when the TabBar control is shown. * The produced effect is responsible for animating both the * TabBar and the content group of the navigator. * *

TabbedViewNavigator will expect the includeInLayout * and visible properties of the TabBar to be true * after this effect is run.

* * @return An effect to play when the TabBar control appears. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createTabBarShowEffect():IEffect { return createTabBarVisibilityEffect(true); } /** * Creates the effect to play when the TabBar control is hidden. * The produced effect is responsible for animating both the * TabBar and the content group of the navigator. * *

TabbedViewNavigator expects the includeInLayout * and visible properties of the TabBar to be false * after this effect runs.

* * @return An effect to play when the TabBar control is hidden. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function createTabBarHideEffect():IEffect { return createTabBarVisibilityEffect(false); } /** * Creates the animation that will be played when the TabBar is * hidden. * * @return The effect ot play * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function createTabBarVisibilityEffect(showAnimation:Boolean):IEffect { var effect:IEffect; var finalEffect:Parallel = new Parallel(); // Grab initial values tabBarProps.start = captureAnimationValues(tabBar); contentGroupProps = { start:captureAnimationValues(contentGroup) }; // Update actionBar layout properties tabBar.visible = tabBar.includeInLayout = showingTabBar; // Calculate final positions. This method will force a validation prepareTabBarForAnimation(showAnimation); var animate:Animate = new Animate(); animate.target = tabBar; animate.duration = TAB_BAR_ANIMATION_DURATION; animate.motionPaths = new Vector.(); animate.motionPaths.push(new SimpleMotionPath(""y"", tabBarProps.start.y, tabBarProps.end.y)); effect = animate; finalEffect.addChild(effect); // Create content group animation animate = new Animate(); animate.target = contentGroup; animate.duration = TAB_BAR_ANIMATION_DURATION; animate.motionPaths = new Vector.(); animate.motionPaths.push(new SimpleMotionPath(""y"", contentGroupProps.start.y, contentGroupProps.end.y)); animate.motionPaths.push(new SimpleMotionPath(""height"", contentGroupProps.start.height, contentGroupProps.end.height)); contentGroup.includeInLayout = false; finalEffect.addChild(animate); finalEffect.duration = TAB_BAR_ANIMATION_DURATION; return finalEffect; } /** * @private */ private function navigator_elementAddHandler(event:ElementExistenceEvent):void { event.element.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } /** * @private */ private function navigator_elementRemoveHandler(event:ElementExistenceEvent):void { event.element.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, view_propertyChangeHandler); } /** * @private * Dispatched when a property on a child navigator changed. */ private function navigator_propertyChangeHandler(event:PropertyChangeEvent):void { itemUpdated(event.target, event.property, event.oldValue, event.newValue); } /** * @private */ override protected function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == tabBar) { tabBar.addEventListener(IndexChangeEvent.CHANGING, tabBar_indexChanging); tabBar.dataGroup.addEventListener(RendererExistenceEvent.RENDERER_ADD, tabBar_elementAddHandler); tabBar.dataProvider = this; tabBar.requireSelection = true; } } /** * @private */ override protected function partRemoved(partName:String, instance:Object):void { super.partRemoved(partName, instance); if (instance == tabBar) { tabBar.dataGroup.removeEventListener(RendererExistenceEvent.RENDERER_ADD, tabBar_elementAddHandler); tabBar.removeEventListener(IndexChangeEvent.CHANGING, tabBar_indexChanging); tabBar.dataProvider = null; } } /** * @private */ override public function loadViewData(value:Object):void { super.loadViewData(value); var savedStacks:Vector.; var savedSelectedIndex:Number = value.selectedIndex as Number; // By the time this method is called, all skin parts should be // added to the component meaning that it is okay to directly // manipulate the child navigators. if (!isNaN(savedSelectedIndex) && savedSelectedIndex < length) selectedIndex = savedSelectedIndex; savedStacks = value.childrenStates as Vector.; if (savedStacks) { var navigator:ViewNavigatorBase; var len:Number = Math.min(savedStacks.length, length); for (var i:int = 0; i < len; i++) { navigator = getElementAt(i) as ViewNavigatorBase; navigator.loadViewData(savedStacks[i]); } } } /** * @private */ override public function saveViewData():Object { var savedData:Object = super.saveViewData(); var childrenStates:Vector. = new Vector.(); for (var i:int = 0; i < length; i++) childrenStates.push((getElementAt(i) as ViewNavigatorBase).saveViewData()); if (!savedData) savedData = {}; savedData.selectedIndex = selectedIndex; savedData.childrenStates = childrenStates; return savedData; } /** * @private * Redispatches the child navigator's COMPLETE event. */ private function navigator_viewChangeCompleteHandler(event:Event):void { if (hasEventListener(""viewChangeComplete"")) dispatchEvent(event); selectedNavigatorChangingView = false; if (tabBar) tabBar.mouseEnabled = explicitTabBarMouseEnabled; } /** * @private */ private function navigator_viewChangeStartHandler(event:Event):void { selectedNavigatorChangingView = true; // Disable mouse interaction with the tabBar if (tabBar) { explicitTabBarMouseEnabled = tabBar.mouseEnabled; tabBar.mouseEnabled = false; } } /** * @private */ private function tabBar_elementAddHandler(event:RendererExistenceEvent):void { event.target.addEventListener(MouseEvent.CLICK, tabBarRenderer_clickHandler); } /** * @private * Determines if the selection of the tab bar can change. */ private function tabBar_indexChanging(event:IndexChangeEvent):void { if (!indexCanChange(event.newIndex)) { event.preventDefault(); // Clear changing flag changingEventDispatched = false; } } /** * @private */ private function elementRemoveHandler(event:ElementExistenceEvent):void { cleanUpNavigator(event.element as ViewNavigatorBase); internalDispatchEvent(CollectionEventKind.REMOVE, event.element, event.index); // Element removed event is called before the element is removed from the // display list. So if the last navigator is about to be removed, numElements // should be 1 if (numElements == 1) selectedIndex = -1; } /** * @private */ private function elementAddHandler(event:ElementExistenceEvent):void { setupNavigator(event.element as ViewNavigatorBase); internalDispatchEvent(CollectionEventKind.ADD, event.element, event.index); // If the added element is the first view navigator, update the selection // to point to it if (numElements == 1) selectedIndex = 0; } /** * @private * Method is called when a tab is clicked by the user. The default * implementation checks if the clicked tab is currently selected, and if * so, pops the active navigator to its root view. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function tabBarRenderer_clickHandler(event:MouseEvent):void { // lastSelectedIndex is used instead of tabBar.selectedIndex // because by the time this method is called, the tabBar's // proposedSelectedIndex has changed, which causes its selectedIndex // method to return the proposed index instead of the currently // selected index. if ((event.target is IItemRenderer) && (IItemRenderer(event.target).itemIndex == lastSelectedIndex)) { if (selectedNavigator is ViewNavigator) ViewNavigator(selectedNavigator).popToFirstView(); } } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function view_propertyChangeHandler(event:PropertyChangeEvent):void { if (event.property == ""tabBarVisible"") { if (event.newValue) showTabBar(); else hideTabBar(); } else if (event.property == ""overlayControls"") { overlayControls = event.newValue; } } /** * @private * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function visibilityAnimation_effectEndHandler(event:EffectEvent):void { event.target.removeEventListener(EffectEvent.EFFECT_END, visibilityAnimation_effectEndHandler); tabBarVisibilityEffect = null; if (activeView) activeView.setTabBarVisible(tabBarProps.showing); // Check if the visible and cacheAsBitmap properties have been set. These are // only set if the default transitions are used. If developers create their // own animations, these properties won't be set. if (tabBarProps.start != undefined) { tabBar.visible = tabBar.includeInLayout = tabBarProps.end.visible; tabBar.cacheAsBitmap = tabBarProps.start.cacheAsBitmap; } tabBarProps = null; if (contentGroupProps) { contentGroup.includeInLayout = contentGroupProps.start.includeInLayout; contentGroup.cacheAsBitmap = contentGroupProps.start.cacheAsBitmap; // The default tab bar hide and show animation will animate the width and height // of the navigator's contentGroup. If the explicitWidth or explicitHeight properties // were NaN before the animation, they'll be set to real values by the animation. As // a result, it is necessary to restore them to NaN so that layout properly sizes these // components. if (isNaN(contentGroupProps.start.explicitHeight)) contentGroup.explicitHeight = NaN; if (isNaN(contentGroupProps.start.explicitWidth)) contentGroup.explicitWidth = NaN; if (!isNaN(contentGroupProps.start.percentWidth)) contentGroup.percentWidth = contentGroupProps.start.percentWidth; if (!isNaN(contentGroupProps.start.percentHeight)) contentGroup.percentHeight = contentGroupProps.start.percentHeight; contentGroupProps = null; } } //-------------------------------------------------------------------------- // // Methods: ISelectableList // //-------------------------------------------------------------------------- //---------------------------------- // selectedIndex //---------------------------------- /** * @private * The proposed selected index. This is a temporary variable that is * used until the selected index is committed. */ protected var _proposedSelectedIndex:int = NO_PROPOSED_SELECTION; /** * @private * The backing variable for selectedIndex. */ protected var _selectedIndex:int = NO_PROPOSED_SELECTION; [Bindable(""change"")] [Bindable(""valueCommit"")] /** * The 0-based index of the selected view navigator, or -1 if none is selected. * Setting the selectedIndex property deselects the currently selected * navigator and selects the navigator at the specified index. * *

The value is always between -1 and (navigators.length - 1). * If items at a lower index than selectedIndex are * removed from the component, the selected index is adjusted downward * accordingly.

* *

If the selected item is removed, the selected index is set to:

* *
    *
  • -1 if there are no remaining items.
  • *
  • selectedIndex - 1 if there is at least one item.
  • *
* * @default -1 * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get selectedIndex():int { if (_proposedSelectedIndex != NO_PROPOSED_SELECTION) return _proposedSelectedIndex; return _selectedIndex; } /** * @private */ public function set selectedIndex(value:int):void { if (!dataProviderChanged && value == selectedIndex) return; if (activeView) activeView.dispatchEvent(new Event(""_navigationChange_"")); _proposedSelectedIndex = value; selectedIndexChanged = true; invalidateProperties(); } /** * @private * This method determines the navigator can change its selected index. * This function will be called if the selection changed on the * tab bar, or if the selectedIndex property has changed. */ private function indexCanChange(proposedSelection:int):Boolean { changingEventDispatched = true; if (!canRemoveCurrentView()) return false; if (hasEventListener(IndexChangeEvent.CHANGING)) { var e:IndexChangeEvent = new IndexChangeEvent(IndexChangeEvent.CHANGING, false, true); e.oldIndex = _selectedIndex; e.newIndex = proposedSelection; if (!dispatchEvent(e)) return false; } return true; } //---------------------------------- // length //---------------------------------- /** * The number of child view navigators being managed by the * this component. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get length():int { return numElements; } /** * Add the specified view navigator to the end of the list. * Equivalent to calling addItemAt(item, length);. * * @param item The view navigator to add. * It must extend the ViewNavigatorBase class. * * @see spark.components.supportClasses.ViewNavigatorBase * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function addItem(item:Object):void { addItemAt(item, length); } /** * Add the view navigator at the specified index. * Any view navigator that was after this index is moved down by one. * * @param item The view navigator to add. * It must extend the ViewNavigatorBase class. * * @param index The index at which to place the item. * * @throws RangeError If index is less than 0 or greater than the length * * @see spark.components.supportClasses.ViewNavigatorBase * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function addItemAt(item:Object, index:int):void { // If the added type is not a ViewNavigatorBase, we ignore the call // TODO (chiedozi): Consider throwing an exception here if (!(item is ViewNavigatorBase)) return; if (index < 0 || index > length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } setupNavigator(ViewNavigatorBase(item)); addElementAt(ViewNavigatorBase(item), index); if (selectedIndex == NO_PROPOSED_SELECTION || numElements == 1) { selectedIndex = 0; } else if (index <= selectedIndex) { selectedIndex++; selectedIndexAdjusted = true; } } /** * Get the view navigator object at the specified index. * * @param index The index in the list from which to retrieve the item. * * @param prefetch Indicating both the direction and amount of items * to fetch during the request, should the item not be local. * * @return The navigator at the specified index, or null if there is none. * * @throws RangeError If the index < 0 or index >= length * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function getItemAt(index:int, prefetch:int = 0):Object { if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } return getElementAt(index); } /** * Return the index of the view navigator if it is in the list * of view navigators. * * @param item The view navigator object to locate. * * @return The index of the view navigator, or -1 if the item is not in the list. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function getItemIndex(item:Object):int { return getElementIndex(item as ViewNavigatorBase); } /** * Notify external components that a property on a view navigator has * been updated. * * @param item The view navigator that was updated. * * @param property A String, QName, or int * specifying the property that was updated. * * @param oldValue The old value of that property. * If property was null, this can be the old value of the item. * * @param newValue The new value of that property. * If property was null, there's no need to specify this * as the item is assumed to be the new value. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function itemUpdated(item:Object, property:Object = null, oldValue:Object = null, newValue:Object = null):void { var event:PropertyChangeEvent = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); event.kind = PropertyChangeEventKind.UPDATE; event.source = item; event.property = property; event.oldValue = oldValue; event.newValue = newValue; internalDispatchEvent(CollectionEventKind.UPDATE, event); } /** * Remove all child view navigators from the navigator. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeAll():void { // Deactive the active navigator and its view if (selectedNavigator) selectedNavigator.setActive(false); // Remove all navigators navigators = null; } /** * Remove the view navigator at the specified index and return it. * The index of any items that were after this index are decreased by one. * * @param index The index from which to remove the item. * * @return The item that was removed. * * @throws RangeError If index < 0 or index >= length. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function removeItemAt(index:int):Object { if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } if (index <= selectedIndex) { selectedIndex--; selectedIndexAdjusted = true; } var removed:Object = removeElementAt(index); return removed; } /** * Add the view navigator at the specified index. * If an item was already at that index, the new item replaces it, * and it is returned. * * @param item The view navigator to place at the index. * * @param index The index at which to place the navigator. * * @return The navigator that was replaced, or null if none. * * @throws RangeError If index is less than 0 or greater than or equal to length * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function setItemAt(item:Object, index:int):Object { // If the added type is not a ViewNavigatorBase, we ignore the call // TODO (chiedozi): Consider throwing an exception here if (!(item is ViewNavigator)) return null; if (index < 0 || index >= length) { var message:String = ResourceManager.getInstance().getString( ""collections"", ""outOfBounds"", [ index ]); throw new RangeError(message); } var oldItem:Object = removeElementAt(index); addElementAt(item as ViewNavigatorBase, index); // Let the navigator know that the item at the selectedIndex changed. // The commitProperties method will pick this up. if (index == selectedIndex) { selectedIndexAdjusted = true; invalidateProperties(); } if (hasEventListener(CollectionEvent.COLLECTION_CHANGE)) { var updateInfo:PropertyChangeEvent; updateInfo = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); updateInfo.kind = PropertyChangeEventKind.UPDATE; updateInfo.oldValue = oldItem; updateInfo.newValue = item; updateInfo.property = index; internalDispatchEvent(CollectionEventKind.REPLACE, updateInfo, index); } return oldItem; } /** * Return an Array that is populated in the same order as the IList * implementation. * * @return The Array. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function toArray():Array { return contentGroup.getMXMLContent(); } /** * @private * Dispatches a collection event with the specified information. * * @param kind String indicates what the kind property of the event should be * @param item Object reference to the item that was added or removed * @param location int indicating where in the source the item was added. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function internalDispatchEvent(kind:String, item:Object = null, location:int = -1):void { if (hasEventListener(CollectionEvent.COLLECTION_CHANGE)) { var event:CollectionEvent = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE); event.kind = kind; event.items.push(item); event.location = location; dispatchEvent(event); } // now dispatch a complementary PropertyChangeEvent if (hasEventListener(PropertyChangeEvent.PROPERTY_CHANGE) && (kind == CollectionEventKind.ADD || kind == CollectionEventKind.REMOVE)) { var objEvent:PropertyChangeEvent = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE); objEvent.property = location; if (kind == CollectionEventKind.ADD) objEvent.newValue = item; else objEvent.oldValue = item; dispatchEvent(objEvent); } } /** * @private * If the item is an IEventDispatcher watch it for updates. * This is called by addItemAt and when the source is initially * assigned. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function startTrackingUpdates(item:Object):void { if (item && (item is IEventDispatcher)) { IEventDispatcher(item).addEventListener( PropertyChangeEvent.PROPERTY_CHANGE, navigator_propertyChangeHandler, false, 0, true); } } /** * @private * If the item is an IEventDispatcher stop watching it for updates. * This is called by removeItemAt, removeAll, and before a new * source is assigned. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ private function stopTrackingUpdates(item:Object):void { if (item && item is IEventDispatcher) { IEventDispatcher(item).removeEventListener( PropertyChangeEvent.PROPERTY_CHANGE, navigator_propertyChangeHandler); } } } }",12056,True,2598.8936378245585,median "package com.company.assembleegameclient.parameters { import com.company.assembleegameclient.game.events.ReconnectEvent; import com.company.assembleegameclient.objects.GameObject; import com.company.assembleegameclient.objects.ObjectLibrary; import com.company.assembleegameclient.objects.ObjectProperties; import com.company.assembleegameclient.objects.Player; import com.company.assembleegameclient.objects.Portal; import com.company.util.KeyCodes; import com.company.util.MoreDateUtil; import com.company.util.MoreStringUtil; import flash.display.DisplayObject; import flash.events.Event; import flash.geom.Point; import flash.net.SharedObject; import flash.utils.ByteArray; import flash.utils.Dictionary; public class Parameters { public static const CLIENT_VERSION:String = ""1.2.0.2.0""; public static const PORT:int = 2050; public static const UNITY_LAUNCHER_VERSION:String = ""2019.3.14f1""; public static const UNITY_GAME_VERSION:String = ""2019.4.9f1""; public static const FELLOW_GUILD_COLOR:uint = 10944349; public static const NAME_CHOSEN_COLOR:uint = 16572160; public static const PLAYER_ROTATE_SPEED:Number = 0.003; public static const BREATH_THRESH:int = 20; public static const SERVER_CHAT_NAME:String = """"; public static const CLIENT_CHAT_NAME:String = ""*Client*""; public static const ERROR_CHAT_NAME:String = ""*Error*""; public static const HELP_CHAT_NAME:String = ""*Help*""; public static const GUILD_CHAT_NAME:String = ""*Guild*""; public static const NAME_CHANGE_PRICE:int = 1000; public static const GUILD_CREATION_PRICE:int = 1000; public static const TUTORIAL_GAMEID:int = -1; public static const NEXUS_GAMEID:int = -2; public static const RANDOM_REALM_GAMEID:int = -3; public static const MAPTEST_GAMEID:int = -6; public static const MAX_SINK_LEVEL:Number = 18; public static const TERMS_OF_USE_URL:String = ""http://legal.decagames.com/tos/""; public static const PRIVACY_POLICY_URL:String = ""http://legal.decagames.com/privacy/""; public static const USER_GENERATED_CONTENT_TERMS:String = ""/UGDTermsofUse.html""; public static const RANDOM1:String = ""5a4d2016bc16dc64883194ffd9""; public static const RANDOM2:String = ""c91d9eec420160730d825604e0""; public static const RSA_PUBLIC_KEY:String = ""-----BEGIN PUBLIC KEY-----\\n"" + ""MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCKFctVrhfF3m2Kes0FBL"" + ""/JFeOcmNg9eJz8k/hQy1kadD+XFUpluRqa//Uxp2s9W2qE0EoUCu59ugcf"" + ""/p7lGuL99UoSGmQEynkBvZct+/M40L0E0rZ4BVgzLOJmIbXMp0J4PnPcb6VLZ"" + ""vxazGcmSfjauC7F3yWYqUbZd/HCBtawwIDAQAB"" + ""\\n-----END PUBLIC KEY-----""; public static const skinTypes16:Vector. = new [1027,1028,1029,1030,10973,19494,19531,6346,30056,5505,7766,7769]; public static const itemTypes16:Vector. = new [5473,5474,5475,5476,10939,19494,19531,6347,5506]; public static const DefaultAAIgnore:Vector. = new [2312,2313,2370,2392,2393,2400,2401,3413,3418,3419,3420,3421,3427,3454,3638,3645,29594,29597,29710,29711,29742,29743,29746,29748,29781,30001]; public static const DefaultAAException:Vector. = new [2309, 2310, 2311, 3448, 3449, 3472, 3334, 5952, 2354, 2369, 3368, 3366, 3367, 3391, 3389, 3390, 5920, 2314, 3412, 3639, 3634, 2327, 2335, 2336, 1755, 24582, 0x5f1f, 24363, 24135, 24133, 24134, 24132, 24136, 3356, 3357, 3358, 3359, 56 * 60, 3361, 3362, 3363, 3364, 2352, 2330, 28780, 28781, 28795, 28942, 28957, 28988, 28938, 29291, 29018, 29517, 24338, 493 * 60, 29712]; public static const DefaultPriorityList:Vector. = new Vector.(0); public static const spamFilter:Vector. = new [ ""reaimbags,net"", ""r0tmg.0rg"", ""oryxsh0p.net"", ""wh!tebag,net"", ""wh!tebag.net"", ""realmshop.info"", ""realmshop.lnfo"", ""rotmgmarket.c"", ""rpgstash,com"", ""rpgstash.com"", ""realmitems"", ""reaimitems"", ""reaimltems"", ""realmltems"", ""realmpower,net"", ""reaimpower.net"", ""realmpower.net"", ""reaimpower,net"", ""rea!mkings.xyz"", ""buyrotmg.c"", ""lifepot. org"", ""rotmgmax.me"", ""rotmgmax,me"", ""rotmgmax me"", ""oryx.ln"", ""rpgstash com"", ""rwtmg"", ""rotmg.io"", ""jasonprimate"", ""rotmgmax"", ""realmpower"", ""reaimpower""]; public static const defaultExclusions:Vector. = new Vector.(0); public static const defaultInclusions:Vector. = new [10 * 60, 601, 602, 603, 2295, 2296, 2297, 2298, 2524, 2525, 2526, 2527, 8608, 8609, 8610, 8611, 8615, 8617, 8616, 8618, 8962, 9017, 9015, 9016, 9055, 9054, 9052, 9053, 9059, 9058, 9056, 9057, 9063, 9062, 151 * 60, 9061, 32697, 32698, 32699, 545 * 60, 3004, 3005, 3006, 3007, 3088, 3100, 3096, 3091, 3113, 3114, 3112, 3111, 3032, 3033, 3034, 3035, 3177, 3266]; public static const hpPotions:Vector. = new [1799,2594,2623,2632,2633,2689,2836,2837,2838,2839,2795,2868,2870,2872,2874,2876]; public static const mpPotions:Vector. = new [2595,2634,2797,2798,2840,2841,2842,2843,2796,2869,2871,2873,2875,2877,3098]; public static const lmPotions:Vector. = new [2793,9070,5471,9730,2794,9071,5472,9731]; public static const raPotions:Vector. = new [2591,5465,9064,9729,2592,5466,9065,9727,2593,5467,9066,9726,2612,5468,9067,9724,2613,5469,9068,9725,2636,5470,9069,9728]; public static var root:DisplayObject; public static var data:Object = null; public static var drawProj_:Boolean = true; public static var giftChestLootMode:int = 0; public static var iDrankVaultUnlocker:Boolean = false; public static var sendLogin_:Boolean = true; public static var player:Player = null; public static var reconRealm:ReconnectEvent = null; public static var reconDung:ReconnectEvent = null; public static var reconNexus:ReconnectEvent = null; public static var reconOryx:ReconnectEvent = null; public static var dungTime:uint = 0; public static var ignoreRecon:Boolean; public static var lockRecon:Boolean = false; public static var followName:String = """"; public static var followPlayer:GameObject; public static var followingName:Boolean = false; public static var questFollow:Boolean = false; public static var lowCPUMode:Boolean = false; public static var preload:Boolean = false; public static var forceCharId:int = -1; public static var ignoringSecurityQuestions:Boolean = false; public static var ignoredShotCount:int = 0; public static var Cache_CHARLIST_valid:Boolean = false; public static var Cache_CHARLIST_data:String = """"; public static var receivingPots:Boolean; public static var givingPotions:Boolean; public static var recvrName:String; public static var dailyCalendar1RunOnce:Boolean = false; public static var dailyCalendar2RunOnce:Boolean = false; public static var autoAcceptTrades:Boolean; public static var autoDrink:Boolean; public static var watchInv:Boolean; public static var timerActive:Boolean; public static var phaseChangeAt:int; public static var phaseName:String; public static var usingPortal:Boolean; public static var portalID:int; public static var portalSpamRate:int = 80; public static var realmJoining:Boolean; public static var realmName:String; public static var bazaarJoining:Boolean; public static var bazaarLR:String; public static var bazaarDist:Number; public static var manualTutorial:Boolean; public static var epmAVG:int = -1; public static var eLLength:int = 25; public static var fameBot:Boolean = false; public static var suicideMode:Boolean = false; public static var suicideAT:int = -1; public static var fameBotPortalId:int = 0; public static var fameBotPortal:Portal; public static var fameBotPortalPoint:Point; public static var famePointOffset: Number = 0; public static var fameSlideX: Number = 0; public static var fameSlideY: Number = 0; public static var fameWaitStartTime:int = 0; public static var fameWaitNTTime:int = 0; public static var fameWalkSleep_toFountainOrHall:int = 0; public static var fameWalkSleep_toRealms:int = 0; public static var fameWalkSleep2:int = 0; public static var fameWalkSleepStart:int = 0; public static var fpmGain:int = 0; public static var fpmStart:int = -1; public static var warnDensity:Boolean = false; public static var drownDamagePerSec:int = 94; public static var VHS:int = 0; public static var VHSRecordLength:int = -1; public static var VHSIndex:int = -1; public static var abi:Boolean = true; public static var oldFSmode:String = ""exactFit""; public static var keyHolders:String; public static var statsChar:String = ""α""; public static var keyk:Boolean; public static var keynames:String; public static var keyrate:int = 90; public static var needToRecalcDesireables:Boolean = false; public static var needsMapCheck:int = 0; public static var worldMessage:String = """"; public static var constructToggle:Boolean = false; public static var paramIPJoinedOnce:Boolean = true; public static var paramServerJoinedOnce:Boolean = true; public static var currentMapHash:ByteArray = null; public static var savingMap_:Boolean = false; public static var swapINVandBP:Boolean = false; public static var swapINVandBPcounter:int = 0; public static var threadSupport:Boolean = false; public static var enteringRealm:Boolean = false; public static var RANDOM1_BA:ByteArray = new ByteArray(); public static var RANDOM2_BA:ByteArray = new ByteArray(); public static var reconList:Dictionary = new Dictionary(); public static var appendage:Vector. = new Vector.(0); public static var filtered:Vector. = new Vector.(0); public static var dmgCounter:Array = []; public static var emptyOffer:Vector. = new [false, false, false, false, false, false, false, false, false, false, false, false]; public static var potionsToTrade:Vector. = new [false, false, false, false, false, false, false, false, false, false, false, false]; public static var timerPhaseTimes:Dictionary = new Dictionary(); public static var timerPhaseNames:Dictionary = new Dictionary(); public static var famePoint:Point = new Point(0, 0); public static var VHSRecord:Vector. = new Vector.(); public static var VHSNext:Point = new Point(); public static var announcedBags:Vector. = new Vector.(0); public static var mapSavingExclusionClasses:Vector. = new [""Player"", ""Pet""]; public static var charNames:Vector. = new Vector.(0); public static var charIds:Vector. = new Vector.(0); public static var mystics:Vector. = new Vector.(0); private static var savedOptions_:SharedObject = null; private static var keyNames_:Dictionary = new Dictionary(); private static var ctrlrInputNames_:Dictionary = new Dictionary(); public static function load():void { try { savedOptions_ = SharedObject.getLocal(""AssembleeGameClientOptions"", ""/""); data = savedOptions_.data; } catch (error:Error) { data = {}; } setDefaults(); setIgnores(); setCustomPriorityList(); Parameters.RANDOM1_BA = MoreStringUtil.hexStringToByteArray(""5a4d2016bc16dc64883194ffd9""); Parameters.RANDOM2_BA = MoreStringUtil.hexStringToByteArray(""c91d9eec420160730d825604e0""); setTimerPhases(); setAutolootDesireables(); fixFilter(); save(); } public static function setCustomPriorityList():void { var _local1:* = null; for each(var _local2:int in Parameters.data.CustomPriorityList) { _local1 = ObjectLibrary.propsLibrary_[_local2]; if (_local1) _local1.customBoss_ = true; } } public static function fixFilter():void { var _local9:Boolean = false; var _local7:int = 0; var _local1:int = 0; var _local11:int = 0; var _local8:Boolean = false; var _local10:* = null; var _local4:* = null; filtered.length = 0; var _local6:Vector. = new [""rwtmg"",""rwtstore"",""rwtshop"",""rotmgrwt"", ""realmgood"",""reaimgood"",""rpgrip"",""rpgrlp"",""realmshop"",""reaimshop"",""realmsh0p"",""reaimsh0p"", ""realmp0wer"",""reaimp0wer"",""realmpower"",""reaimpower"",""relmgood"",""reimgood"",""hyuk3d"", ""realmservices"",""rotmgstore"",""nv9p4r"",""v4sfdb"",""wgajrj"",""4hzb5"",""realmrwt"",""rotmgcheap"", ""realmgen"",""reaimgen"",""guills"",""rwtrealm"",""rwtgang"",""rea1mgen"",""rwtking"",""discordgg"", ""discordio"",""discordcom"",""realmstock"",""r883q5c""]; for each(var _local5:String in _local6) { _local9 = false; for each(var _local2:String in data.spamFilter) { if (_local5 == _local2) { _local9 = true; break; } } if (!_local9) { filtered.push(_local5); } } filtered = filtered.concat(_local6); for each(_local2 in data.spamFilter) { _local2 = _local2.toLowerCase(); _local10 = []; _local7 = _local2.length; if (_local7 > 0) { _local11 = 0; while (_local11 < _local7) { _local1 = _local2.charCodeAt(_local11); if (_local1 >= 48 && _local1 <= 57 || _local1 >= 97 && _local1 <= 122) { _local10.push(_local1); } _local11++; } } _local4 = String.fromCharCode.apply(String, _local10); if (_local4.length > 0) { _local8 = false; for each(var _local3:String in filtered) { if (_local3 == _local4) { _local8 = true; } } if (!_local8) { filtered.push(_local4); } } } } public static function setTimerPhases():void { timerPhaseTimes[""{\\""key\\"":\\""server.oryx_closed_realm\\""}""] = 2 * 60 * 1000; timerPhaseNames[""{\\""key\\"":\\""server.oryx_closed_realm\\""}""] = ""Realm Closed""; timerPhaseTimes[""{\\""key\\"":\\""server.oryx_minions_failed\\""}""] = 200 * 60; timerPhaseNames[""{\\""key\\"":\\""server.oryx_minions_failed\\""}""] = ""Oryx Shake""; timerPhaseTimes[""DIE! DIE! DIE!!!""] = 23000; timerPhaseNames[""DIE! DIE! DIE!!!""] = ""Vulnerable in""; timerPhaseTimes[""NO! This cannot be...""] = 4000; timerPhaseNames[""NO! This cannot be""] = ""Oryx 3 counter""; timerPhaseTimes[""Despicable mortals! A single realm freed is meaningless! Millions more remain in my grasp!""] = 15000; timerPhaseTimes[""Despicable mortals! A single realm freed is meaningless! Millions more remain in my grasp!""] = ""Oryx 3 vulnerable in"" timerPhaseTimes[""FALL BEFORE MY CELESTIAL STRENGTH!""] = 30000; timerPhaseTimes[""Despicable mortals! A single realm freed is meaningless! Millions more remain in my grasp!""] = ""Celestial phase"" } public static function setAutolootDesireables():void { var _local2:int = 0; var _local3:int = 0; var _local1:ObjectProperties = null; var _local4:* = null; var _local10:int = 0; var _local9:* = ObjectLibrary.xmlLibrary_; for each(_local4 in ObjectLibrary.xmlLibrary_) { _local3 = _local4.@type; _local1 = ObjectLibrary.propsLibrary_[_local3]; if (_local1 && _local1.isItem_) { _local1.desiredLoot_ = false; if (_local1.isPotion_ && desiredPotion(_local3)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootWeaponTier != 999 && desiredWeapon(_local4, _local3, Parameters.data.autoLootWeaponTier)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootAbilityTier != 999 && desiredAbility(_local4, _local3, Parameters.data.autoLootAbilityTier)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootArmorTier != 999 && desiredArmor(_local4, _local3, Parameters.data.autoLootArmorTier)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootRingTier != 999 && desiredRing(_local4, _local3, Parameters.data.autoLootRingTier)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootUTs && desiredUT(_local4)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootSkins && desiredSkin(_local4, _local4.@id)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootPetSkins && desiredPetSkin(_local4, _local4.@id, int(_local4.@type))) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootKeys && desiredKey(_local4, _local4.@id)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootMarks && String(_local4.@id).indexOf(""Mark of "") != -1) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootConsumables && ""Consumable"" in _local4) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootSoulbound && ""Soulbound"" in _local4) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootEggs != -1 && desiredEgg(_local4, Parameters.data.autoLootEggs)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootFeedPower != -1 && desiredFeedPower(_local4, Parameters.data.autoLootFeedPower)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootFameBonus != -1 && desiredFameBonus(_local4, Parameters.data.autoLootFameBonus)) { _local1.desiredLoot_ = true; } else if (Parameters.data.autoLootStackables && _local1.stackable_ || ""Quantity"" in _local4 && ""ExtraTooltipData"" in _local4 && _local4.ExtraTooltipData.EffectInfo.(@name == ""Stack limit"")) { _local1.desiredLoot_ = true; } } } var _local12:int = 0; var _local11:* = Parameters.data.autoLootExcludes; for each(_local2 in Parameters.data.autoLootExcludes) { _local1 = ObjectLibrary.propsLibrary_[_local2]; if (_local1) { _local1.desiredLoot_ = false; } } var _local14:int = 0; var _local13:* = Parameters.data.autoLootIncludes; for each(_local2 in Parameters.data.autoLootIncludes) { _local1 = ObjectLibrary.propsLibrary_[_local2]; if (_local1) { _local1.desiredLoot_ = true; } } } public static function desiredPotion(_arg_1:int):Boolean { if (Parameters.data.autoLootHPPots) { if (hpPotions.indexOf(_arg_1) >= 0) { return true; } } if (Parameters.data.autoLootMPPots) { if (mpPotions.indexOf(_arg_1) >= 0) { return true; } } if (Parameters.data.autoLootLifeManaPots) { if (lmPotions.indexOf(_arg_1) >= 0) { return true; } } if (Parameters.data.autoLootRainbowPots) { if (raPotions.indexOf(_arg_1) >= 0) { return true; } } return false; } public static function desiredWeapon(_arg_1:XML, _arg_2:int, _arg_3:int):Boolean { if (!(""SlotType"" in _arg_1 && ""Tier"" in _arg_1)) { return false; } var _local4:Vector. = new [3, 2, 24, 17, 1, 8]; return _arg_1.Tier >= _arg_3 && _local4.indexOf(_arg_1.SlotType) >= 0; } public static function desiredAbility(_arg_1:XML, _arg_2:int, _arg_3:int):Boolean { if (!(""SlotType"" in _arg_1 && ""Tier"" in _arg_1)) { return false; } var _local4:Vector. = new [13, 16, 21, 18, 22, 15, 23, 12, 5, 25, 19, 11, 4, 20]; return _arg_1.Tier >= _arg_3 && _local4.indexOf(_arg_1.SlotType) >= 0; } public static function desiredArmor(_arg_1:XML, _arg_2:int, _arg_3:int):Boolean { if (!(""SlotType"" in _arg_1 && ""Tier"" in _arg_1)) { return false; } var _local4:Vector. = new [6, 7, 14]; return _arg_1.Tier >= _arg_3 && _local4.indexOf(_arg_1.SlotType) >= 0; } public static function desiredRing(_arg_1:XML, _arg_2:int, _arg_3:int):Boolean { if (!(""SlotType"" in _arg_1 && ""Tier"" in _arg_1)) { return false; } return _arg_1.Tier >= _arg_3 && _arg_1.SlotType == 9; } public static function desiredUT(_arg_1:XML):Boolean { var _local2:int = 0; if (!(""SlotType"" in _arg_1)) { return false; } if (""BagType"" in _arg_1) { _local2 = _arg_1.BagType; return _local2 == 6 || _local2 == 9; } return false; } public static function desiredST(param1:XML) : Boolean { var _local2:int = 0; if(!(""SlotType"" in param1)) { return false; } if(""BagType"" in param1) { _local2 = param1.BagType; return _local2 == 8; } return false; } public static function desiredSkin(_arg_1:XML, _arg_2:String):Boolean { if (_arg_1.Activate == ""UnlockSkin"") { return true; } if (_arg_2.lastIndexOf(""Mystery Skin"") >= 0) { return true; } return false; } public static function desiredPetSkin(_arg_1:XML, _arg_2:String, _arg_3:int):Boolean { var _local4:Vector. = new [8973, 8974, 8975]; if (_arg_2.lastIndexOf(""Pet Stone"") >= 0) { return true; } if (_local4.indexOf(_arg_3) >= 0) { return true; } return false; } public static function desiredKey(_arg_1:XML, _arg_2:String):Boolean { if (_arg_1.Activate == ""CreatePortal"") { return true; } if (_arg_2.indexOf(""Mystery Key"") >= 0) { return true; } return false; } public static function desiredEgg(_arg_1:XML, _arg_2:int):Boolean { var _local3:int = 0; if (""Rarity"" in _arg_1) { if (_arg_1.Rarity == ""Common"") { _local3 = 0; } else if (_arg_1.Rarity == ""Uncommon"") { _local3 = 1; } else if (_arg_1.Rarity == ""Rare"") { _local3 = 2; } else if (_arg_1.Rarity == ""Legendary"") { _local3 = 3; } return _local3 >= _arg_2; } return false; } public static function desiredFeedPower(_arg_1:XML, _arg_2:int):Boolean { return ""feedPower"" in _arg_1 && _arg_1.feedPower >= _arg_2; } public static function desiredFameBonus(_arg_1:XML, _arg_2:int):Boolean { return ""FameBonus"" in _arg_1 && _arg_1.FameBonus >= _arg_2; } public static function setIgnores():void { var _local3:* = null; for each(var _local2:int in Parameters.data.AAIgnore) { if (_local2 in ObjectLibrary.propsLibrary_) { _local3 = ObjectLibrary.propsLibrary_[_local2]; _local3.ignored = true; } if (_local2 in ObjectLibrary.xmlLibrary_) { ObjectLibrary.xmlLibrary_[_local2].props_.ignored = true; } } for each(var _local1:int in Parameters.data.AAException) { if (_local1 in ObjectLibrary.propsLibrary_) { _local3 = ObjectLibrary.propsLibrary_[_local1]; _local3.excepted = true; } if (_local1 in ObjectLibrary.xmlLibrary_) { ObjectLibrary.xmlLibrary_[_local1].props_.excepted = true; } } } public static function save():void { try { if (savedOptions_) { savedOptions_.flush(); } } catch (error:Error) { } } public static function setKey(_arg_1:String, _arg_2:uint):void { for (var _local3:String in keyNames_) { if (data[_local3] == _arg_2) { data[_local3] = 0; } } data[_arg_1] = _arg_2; } public static function setDefaults():void { setDefaultKey(""moveLeft"", 65); setDefaultKey(""moveRight"", 68); setDefaultKey(""moveUp"", 87); setDefaultKey(""moveDown"", 83); setDefaultKey(""rotateLeft"", 81); setDefaultKey(""rotateRight"", 69); setDefaultKey(""useSpecial"", 32); setDefaultKey(""interact"", 86); setDefaultKey(""useInvSlot1"", 49); setDefaultKey(""useInvSlot2"", 50); setDefaultKey(""useInvSlot3"", 51); setDefaultKey(""useInvSlot4"", 52); setDefaultKey(""useInvSlot5"", 53); setDefaultKey(""useInvSlot6"", 54); setDefaultKey(""useInvSlot7"", 55); setDefaultKey(""useInvSlot8"", 56); setDefaultKey(""escapeToNexus2"", 116); setDefaultKey(""escapeToNexus"", 82); setDefaultKey(""autofireToggle"", 67); setDefaultKey(""scrollChatUp"", 33); setDefaultKey(""scrollChatDown"", 34); setDefaultKey(""miniMapZoomOut"", 189); setDefaultKey(""miniMapZoomIn"", 187); setDefaultKey(""resetToDefaultCameraAngle"", 70); setDefaultKey(""togglePerformanceStats"", 88); setDefaultKey(""options"", 79); setDefaultKey(""toggleCentering"", 84); setDefaultKey(""chat"", 13); setDefaultKey(""chatCommand"", 191); setDefaultKey(""tell"", 9); setDefaultKey(""guildChat"", 71); setDefaultKey(""toggleFullscreen"", 0); setDefaultKey(""useHealthPotion"", 90); setDefaultKey(""GPURenderToggle"", 0); setDefaultKey(""friendList"", 0); setDefaultKey(""useMagicPotion"", 89); setDefaultKey(""switchTabs"", 72); setDefaultKey(""particleEffect"", 0); setDefaultKey(""toggleHPBar"", 0); setDefaultKey(""toggleProjectiles"", 0); setDefaultKey(""toggleMasterParticles"", 0); setDefaultKey(""toggleRealmQuestDisplay"", 0); setDefault(""playMusic"", false); setDefault(""playSFX"", true); setDefault(""playPewPew"", true); setDefault(""centerOnPlayer"", true); setDefault(""preferredServer"", null); setDefault(""bestServer"", null); setDefault(""preferredChallengerServer"", null); setDefault(""bestChallengerServer"", null); setDefault(""needsTutorial"", false); setDefault(""cameraAngle"", 0); setDefault(""defaultCameraAngle"", 0); setDefault(""showQuestPortraits"", true); setDefault(""fullscreenMode"", false); setDefault(""showProtips"", false); setDefault(""joinDate"", MoreDateUtil.getDayStringInPT()); setDefault(""lastDailyAnalytics"", null); setDefault(""allowRotation"", true); setDefault(""allowMiniMapRotation"", false); setDefault(""charIdUseMap"", {}); setDefault(""textBubbles"", false); setDefault(""showTradePopup"", true); setDefault(""paymentMethod"", null); setDefault(""filterLanguage"", false); setDefault(""showGuildInvitePopup"", true); setDefault(""showBeginnersOffer"", false); setDefault(""beginnersOfferTimeLeft"", 0); setDefault(""beginnersOfferShowNow"", false); setDefault(""beginnersOfferShowNowTime"", 0); setDefault(""inventorySwap"", true); setDefault(""particleEffect"", false); setDefault(""uiQuality"", false); setDefault(""disableEnemyParticles"", false); setDefault(""disableAllyShoot"", 0); setDefault(""disablePlayersHitParticles"", false); setDefault(""cursorSelect"", ""4""); setDefault(""GPURender"", false); setDefault(""forceChatQuality"", false); setDefault(""hidePlayerChat"", false); setDefault(""chatStarRequirement"", 0); setDefault(""chatAll"", true); setDefault(""chatWhisper"", true); setDefault(""chatGuild"", true); setDefault(""chatTrade"", true); setDefault(""toggleBarText"", 0); setDefault(""toggleToMaxText"", false); setDefault(""particleEffect"", true); if (""playMusic"" in data && data.playMusic == true) { setDefault(""musicVolume"", 1); } else { setDefault(""musicVolume"", 0); } if (""playSFX"" in data && data.playMusic == true) { setDefault(""SFXVolume"", 0.2); } else { setDefault(""SFXVolume"", 0); } setDefaultKey(""friendList"", 0); setDefault(""tradeWithFriends"", false); setDefault(""chatFriend"", false); setDefault(""friendStarRequirement"", 0); setDefault(""HPBar"", 1); setDefault(""newMiniMapColors"", false); setDefault(""noParticlesMaster"",false); setDefault(""noAllyNotifications"", false); setDefault(""noAllyDamage"", false); setDefault(""noEnemyDamage"", false); setDefault(""forceEXP"", 1); setDefault(""showFameGain"", false); setDefault(""curseIndication"", false); setDefault(""showTierTag"", true); setDefault(""characterGlow"", 0); setDefault(""gravestones"", 0); setDefault(""chatNameColor"", 0); setDefault(""expandRealmQuestsDisplay"", true); setDefault(""showChallengerInfo"", true); if (!(""needsSurvey"" in data)) { data.needsSurvey = data.needsTutorial; switch (int(Math.random() * 5)) { case 0: data.surveyDate = 0; data.playTimeLeftTillSurvey = 5 * 60; data.surveyGroup = ""5MinPlaytime""; break; case 1: data.surveyDate = 0; data.playTimeLeftTillSurvey = 10 * 60; data.surveyGroup = ""10MinPlaytime""; break; case 2: data.surveyDate = 0; data.playTimeLeftTillSurvey = 30 * 60; data.surveyGroup = ""30MinPlaytime""; break; case 3: data.surveyDate = new Date().time + 7 * 24 * 60 * 60 * 1000; data.playTimeLeftTillSurvey = 2 * 60; data.surveyGroup = ""1WeekRealtime""; break; case 4: data.surveyDate = new Date().time + 14 * 24 * 60 * 60 * 1000; data.playTimeLeftTillSurvey = 2 * 60; data.surveyGroup = ""2WeekRealtime""; } } setDefault(""lastTab"", ""Options.Controls""); setDefault(""ssdebuffBitmask"", 0); setDefault(""ssdebuffBitmask2"", 0); setDefault(""ccdebuffBitmask"", 0); setDefault(""spamFilter"", spamFilter); setDefault(""AutoLootOn"", false); setDefault(""AutoHealPercentage"", 99); setDefault(""AAOn"", true); setDefault(""AAMinManaPercent"", 50); setDefault(""AATargetLead"", true); setDefault(""AABoundingDist"", 4); setDefault(""aimMode"", 2); setDefault(""AutoAbilityOn"", false); setDefault(""showQuestBar"", false); setDefault(""AutoNexus"", 25); setDefault(""AutoHeal"", 65); setDefault(""autoHPPercent"", 40); setDefault(""autoMPPercent"", -1); setDefault(""autompPotDelay"", 200); setDefault(""TombCycleBoss"", 3368); setDefault(""XYZdistance"", 1); setDefaultKey(""XYZleftHotkey"", 0); setDefaultKey(""XYZupHotkey"", 0); setDefaultKey(""XYZdownHotkey"", 0); setDefaultKey(""XYZrightHotkey"", 0); setDefaultKey(""TombCycleKey"", 0); setDefaultKey(""anchorTeleport"", 0); setDefaultKey(""DrinkAllHotkey"", 0); setDefaultKey(""SelfTPHotkey"", 0); setDefaultKey(""syncLeadHotkey"", 118); setDefaultKey(""syncFollowHotkey"", 119); setDefault(""vaultOnly"", false); setDefault(""AutoResponder"", false); setDefault(""FocusFPS"", false); setDefault(""bgFPS"", 10); setDefault(""fgFPS"", 60); setDefault(""timeScale"",1) setDefault(""timeScaleArr"",new Vector.(0)) setDefault(""timeScaleArrIndex"",0) setDefaultKey(""timeScaleKey"",0) setDefault(""hideLockList"", false); setDefault(""hidePets2"", 1); setDefault(""hideOtherDamage"", false); setDefault(""mscale"", 1); setDefault(""stageScale"", ""noScale""); setDefault(""uiscale"", true); setDefault(""offsetVoidBow"", false); setDefault(""offsetColossus"", false); setDefault(""coloOffset"", 0.225); setDefault(""ethDisable"", false); setDefault(""cultiststaffDisable"", false); setDefault(""offsetCelestialBlade"", false); setDefault(""alphaOnOthers"", false); setDefault(""alphaMan"", 0.4); setDefault(""lootPreview"", true); setDefault(""showQuestBar"", false); setDefaultKey(""LowCPUModeHotKey"", 0); setDefaultKey(""Cam45DegInc"", 0); setDefaultKey(""Cam45DegDec"", 0); setDefaultKey(""QuestTeleport"", 0); setDefaultKey(""ReconRealm"", 97); setDefaultKey(""PassesCoverHotkey"", 0); setDefaultKey(""AAHotkey"", 0); setDefaultKey(""AAModeHotkey"", 0); setDefaultKey(""AutoAbilityHotkey"", 0); setDefaultKey(""AutoLootHotkey"", 0); setDefault(""damageIgnored"", false); setDefault(""ignoreIce"", false); setDefaultKey(""TextPause"", 113); setDefaultKey(""TextThessal"", 114); setDefaultKey(""TextCem"", 112); setDefault(""AAException"", DefaultAAException); setDefault(""AAIgnore"", DefaultAAIgnore); setDefault(""CustomPriorityList"", DefaultPriorityList); setDefault(""passThroughInvuln"", false); setDefault(""autoaimAtInvulnerable"", false); setDefault(""showDamageOnEnemy"", false); setDefault(""fameBlockTP"", false); setDefault(""fameBlockAbility"", false); setDefault(""fameBlockCubes"", false); setDefault(""fameBlockGodsOnly"", false); setDefault(""fameBlockThirsty"", false); setDefault(""spellbombHPThreshold"", 50 * 60); setDefault(""skullHPThreshold"", 800); setDefault(""skullTargets"", 5); setDefault(""liteMonitor"", true); setDefaultKey(""TogglePlayerFollow"", 2 * 60); setDefaultKey(""resetClientHP"", 0); setDefaultKey(""famebotToggleHotkey"", 0); setDefault(""addMoveRecPoint"", false); setDefault(""trainOffset"", 500); setDefault(""densityThreshold"", 625); setDefault(""teleDistance"", 64); setDefault(""WalkAroundRocks"", false); setDefault(""famebotContinue"", 0); setDefault(""fameTpCdTime"", 5000); setDefault(""famePointOffset"", 1.5); setDefault(""skipPopups"", false); setDefault(""TradeDelay"", true); setDefault(""showHPBarOnAlly"", true); setDefault(""showEXPFameOnAlly"", true); setDefault(""showClientStat"", false); setDefault(""liteParticle"", false); setDefault(""onlyAimAtExcepted"", false); setDefault(""ignoreStatusText"", false); setDefault(""ignoreQuiet"", false); setDefault(""ignoreWeak"", false); setDefault(""ignoreSlowed"", false); setDefault(""ignoreSick"", false); setDefault(""ignoreDazed"", false); setDefault(""ignoreStunned"", false); setDefault(""ignoreParalyzed"", false); setDefault(""ignoreBleeding"", false); setDefault(""ignoreArmorBroken"", false); setDefault(""ignorePetStasis"", false); setDefault(""ignorePetrified"", false); setDefault(""ignoreSilenced"", false); setDefault(""ignoreBlind"", true); setDefault(""ignoreHallucinating"", true); setDefault(""ignoreDrunk"", true); setDefault(""ignoreConfused"", true); setDefault(""ignoreUnstable"", false); setDefault(""ignoreDarkness"", true); setDefault(""autoDecrementHP"", false); setDefault(""bigLootBags"", false); setDefault(""replaceCon"", false); setDefault(""AutoSyncClientHP"", false); setDefault(""extraPlayerMenu"", true); setDefault(""safeWalk"", false); setDefault(""evenLowerGraphics"", false); setDefault(""showCHbar"", true); setDefault(""rightClickOption"", 0); setDefault(""dynamicHPcolor"", true); setDefault(""keyList"", false); setDefault(""uiTextSize"", 15); setDefault(""mobNotifier"", true); setDefault(""showMobInfo"", false); setDefault(""aaDistance"", 1); setDefault(""hideLowCPUModeChat"", false); setDefault(""fameOryx"", false); setDefault(""tiltCam"", false); setDefault(""showBG"",false); setDefault(""BossPriority"", true); setDefaultKey(""sayCustom1"", 0); setDefaultKey(""sayCustom2"", 0); setDefaultKey(""sayCustom3"", 0); setDefaultKey(""sayCustom4"", 0); setDefault(""customMessage1"", """"); setDefault(""customMessage2"", """"); setDefault(""customMessage3"", """"); setDefault(""customMessage4"", """"); setDefault(""autoLootExcludes"", Parameters.defaultExclusions); setDefault(""autoLootIncludes"", Parameters.defaultInclusions); setDefault(""autoLootUpgrades"", false); setDefault(""autoLootWeaponTier"", 11); setDefault(""autoLootAbilityTier"", 5); setDefault(""autoLootArmorTier"", 12); setDefault(""autoLootRingTier"", 5); setDefault(""autoLootSkins"", true); setDefault(""autoLootPetSkins"", true); setDefault(""autoLootKeys"", true); setDefault(""autoLootHPPots"", true); setDefault(""autoLootMPPots"", true); setDefault(""autoLootHPPotsInv"", true); setDefault(""autoLootMPPotsInv"", false); setDefault(""autoLootLifeManaPots"", true); setDefault(""autoLootRainbowPots"", true); setDefault(""autoLootUTs"", true); setDefault(""autoLootFameBonus"", 5); setDefault(""autoLootFeedPower"", -1); setDefault(""autoLootMarks"", false); setDefault(""autoLootConsumables"", false); setDefault(""autoLootSoulbound"", false); setDefault(""autoLootEggs"", 1); setDefault(""autoLootStackables"", true); setDefault(""showFameGoldRealms"", false); setDefault(""showEnemyCounter"", true); setDefault(""showTimers"", true); setDefault(""showAOGuildies"", false); setDefault(""autoDrinkFromBags"", false); setDefault(""cacheCharList"", false); setDefault(""PassesCover"", false); setDefault(""chatLength"", 10); setDefault(""autohpPotDelay"", 400); setDefault(""mapHack"", false); setDefault(""fixTabHotkeys"", true); setDefault(""noRotate"", false); setDefault(""customSounds"",false); setDefault(""customVolume"",1); setDefault(""aimAtQuest"", 0); setDefault(""followIntoPortals"", false); setDefault(""spamPrismNumber"", 0); setDefault(""instaNexus"", true); setDefault(""rightClickSelectAll"", false); setDefault(""lastVersionCheck1"", -1); setDefault(""shownGotoWarning"", false); setDefaultControllerInput(""ctrlEnterPortal"", 4); setDefaultControllerInput(""ctrlTeleQuest"", 7); setDefaultControllerInput(""ctrlNexus"", 5); setDefaultControllerInput(""ctrlAbility"", 6); setDefaultControllerInput(""ctrlItemMenu"", 14); setDefault(""useControllerNumber"", 0); setDefault(""selectedItemColor"", 0); setDefault(""cNameBypass"", false); setDefault(""AutoDungeonEnterList"", new Vector.(0)); setDefault(""customVersion"", """"); setDefault(""autoLootInVault"", false); setDefault(""seenUnityPopup"", false); setDefault(""showWhiteBagEffect"", true); setDefault(""customFPS"",60); setDefault(""fameDistDelta"", 0.5); setDefault(""fameCheckMS"", 150); setDefault(""perfStats"", false); setDefault(""showOrangeBagEffect"",false); setDefault(""mouseCameraMultiplier"",0); setDefault(""frameSkipMS"",-1); setDefault(""showInventoryTooltip"",true); setDefault(""autoEnterPortals"",false); setDefault(""bypassTpPositionCheck"",false); setDefault(""reconnectDelay"",250); setDefault(""mysticAAShootGroup"",false); setDefaultKey(""walkKey"", KeyCodes.SHIFT); setDefault(""projFace"", true); setDefault(""disableSorting"", false); setDefault(""noClip"", false); setDefaultKey(""noClipKey"", KeyCodes.UNSET); setDefault(""fakeLag"", 0); setDefault(""renderDistance"", 16); setDefault(""showRange"", false); setDefault(""multiLeader"", """"); } private static function setDefaultKey(_arg_1:String, _arg_2:uint):void { if (!(_arg_1 in data)) { data[_arg_1] = _arg_2; } keyNames_[_arg_1] = true; } private static function setDefaultControllerInput(_arg_1:String, _arg_2:uint):void { if (!(_arg_1 in data)) { data[_arg_1] = _arg_2; } ctrlrInputNames_[_arg_1] = true; } private static function setDefault(_arg_1:String, _arg_2:*):void { if (!(_arg_1 in data)) { data[_arg_1] = _arg_2; } } public function Parameters() { super(); } } } ",12121,False,2040.7619923928526,median "/* * Send arbitrary IR codes via a web server or MQTT. * Copyright David Conran 2016, 2017, 2018 * * NOTE: An IR LED circuit *MUST* be connected to ESP8266 GPIO4 (D2). See IR_LED * * WARN: This is very advanced & complicated example code. Not for beginners. * You are strongly suggested to try & look at other example code first. * * # Instructions * * ## Before First Boot (i.e. Compile time) * - Set the MQTT_SERVER define below to the address of your MQTT server. * - Arduino IDE: * o Install the following libraries via Library Manager * - WiFiManager (https://github.com/tzapu/WiFiManager) * - PubSubClient (https://pubsubclient.knolleary.net/) * o You MUST change to have the following (or larger) value: * #define MQTT_MAX_PACKET_SIZE 512 * - PlatformIO IDE: * If you are using PlatformIO, this should already been done for you in * the accompanying platformio.ini file. * * ## First Boot (Initial setup) * The ESP8266 board will boot into the WiFiManager's AP mode. * i.e. It will create a WiFi Access Point with a SSID like: ""ESP123456"" etc. * Connect to that SSID. Then point your browser to http://192.168.4.1/ and * configure the ESP8266 to connect to your desired WiFi network. * It will remember the new WiFi connection details on next boot. * More information can be found here: * https://github.com/tzapu/WiFiManager#how-it-works * * If you need to reset the WiFi settings, visit: * http:///reset * * ## Normal Use (After setup) * Enter 'http:///ir?type=7&code=E0E09966 * http:///ir?type=4&code=0xf50&bits=12 * http:///ir?code=C1A2E21D&repeats=8&type=19 * http:///ir?type=31&code=40000,1,1,96,24,24,24,48,24,24,24,24,24,48,24,24,24,24,24,48,24,24,24,24,24,24,24,24,1058 * http:///ir?type=18&code=190B8050000000E0190B8070000010f0 * http:///ir?repeats=1&type=25&code=0000,006E,0022,0002,0155,00AA,0015,0040,0015,0040,0015,0015,0015,0015,0015,0015,0015,0015,0015,0015,0015,0040,0015,0040,0015,0015,0015,0040,0015,0015,0015,0015,0015,0015,0015,0040,0015,0015,0015,0015,0015,0040,0015,0040,0015,0015,0015,0015,0015,0015,0015,0015,0015,0015,0015,0040,0015,0015,0015,0015,0015,0040,0015,0040,0015,0040,0015,0040,0015,0040,0015,0640,0155,0055,0015,0E40 * * or * * Send a MQTT message to the topic 'ir_server/send' using the following * format (Order is important): * protocol_num,hexcode e.g. 7,E0E09966 which is Samsung(7), Power On code, * default bit size, default nr. of repeats. * protocol_num,hexcode,bits e.g. 4,f50,12 which is Sony(4), Power Off code, * 12 bits & default nr. of repeats. * protocol_num,hexcode,bits,repeats e.g. 19,C1A2E21D,0,8 which is * Sherwood(19), Vol Up, default bit size & * repeated 8 times. * 30,frequency,raw_string e.g. 30,38000,9000,4500,500,1500,500,750,500,750 * Raw (30) @ 38kHz with a raw code of ""9000,4500,500,1500,500,750,500,750"" * 31,code_string e.g. 31,40000,1,1,96,24,24,24,48,24,24,24,24,24,48,24,24,24,24,24,48,24,24,24,24,24,24,24,24,1058 * GlobalCache (31) & ""40000,1,1,96,..."" (Sony Vol Up) * 25,Rrepeats,hex_code_string e.g. 25,R1,0000,006E,0022,0002,0155,00AA,0015,0040,0015,0040,0015,0015,0015,0015,0015,0015,0015,0015,0015,0015,0015,0040,0015,0040,0015,0015,0015,0040,0015,0015,0015,0015,0015,0015,0015,0040,0015,0015,0015,0015,0015,0040,0015,0040,0015,0015,0015,0015,0015,0015,0015,0015,0015,0015,0015,0040,0015,0015,0015,0015,0015,0040,0015,0040,0015,0040,0015,0040,0015,0040,0015,0640,0155,0055,0015,0E40 * Pronto (25), 1 repeat, & ""0000 006E 0022 0002 ..."" (Sherwood Amp Tape Input) * ac_protocol_num,really_long_hexcode e.g. 18,190B8050000000E0190B8070000010F0 * Kelvinator (18) Air Con on, Low Fan, 25 deg etc. * NOTE: Ensure you zero-pad to the correct number of * digits for the bit/byte size you want to send * as some A/C units have units have different * sized messages. e.g. Fujitsu A/C units. * In short: * No spaces after/before commas. * Values are comma separated. * The first value is always in Decimal. * For simple protocols, the next value (hexcode) is always hexadecimal. * The optional bit size is in decimal. * * Unix command line usage example: * # Install a MQTT client * $ sudo apt install mosquitto-clients * # Send a 32-bit NEC code of 0x1234abcd via MQTT. * $ mosquitto_pub -h 10.20.0.253 -t ir_server/send -m '3,1234abcd,32' * * This server will send (back) what ever IR message it just transmitted to * the MQTT topic 'ir_server/sent' to confirm it has been performed. This works * for messages requested via MQTT or via HTTP. * Note: Other status messages are also sent to 'ir_server/sent' from time to * time. * Unix command line usage example: * # Listen to MQTT acknowledgements. * $ mosquitto_sub -h 10.20.0.253 -t ir_server/sent * * If DEBUG is turned on, there is additional information printed on the Serial * Port. * * ## Updates * You can upload new firmware over the air (OTA) via the form on the device's * main page. No need to connect to the device again via USB. \\o/ * Your WiFi settings should be remembered between updates. \\o/ \\o/ * * Copyright Notice: * Code for this has been borrowed from lots of other OpenSource projects & * resources. I'm *NOT* claiming complete Copyright ownership of all the code. * Likewise, feel free to borrow from this as much as you want. */ #define MQTT_ENABLE // Comment this out if you don't want to use MQTT at all. #include #include #include #include #include #include #include #include #include #include #include #ifdef MQTT_ENABLE // -------------------------------------------------------------------- // * * * IMPORTANT * * * // You must change to have the following value. // #define MQTT_MAX_PACKET_SIZE 512 // -------------------------------------------------------------------- #include #endif // MQTT_ENABLE #include #include // Configuration parameters // GPIO the IR LED is connected to/controlled by. GPIO 4 = D2. #define IR_LED 4 // define IR_LED 3 // For an ESP-01 we suggest you use RX/GPIO3/Pin 7. #define HTTP_PORT 80 // The port the HTTP server is listening on. // Name of the device you want in mDNS. // NOTE: Changing this will change the MQTT path too unless you override it // via MQTTprefix below. #define HOSTNAME ""ir_server"" // We obtain our network config via DHCP by default but allow an easy way to // use a static IP config. #define USE_STATIC_IP false // Change to 'true' if you don't want to use DHCP. #if USE_STATIC_IP const IPAddress kIPAddress = IPAddress(10, 0, 1, 78); const IPAddress kGateway = IPAddress(10, 0, 1, 1); const IPAddress kSubnetMask = IPAddress(255, 255, 255, 0); #endif // USE_STATIC_IP #ifdef MQTT_ENABLE // Address of your MQTT server. #define MQTT_SERVER ""10.20.0.253"" // <=- CHANGE ME #define MQTT_PORT 1883 // Default port used by MQTT servers. // Set if your MQTT server requires a Username & Password to connect. const char* mqtt_user = """"; const char* mqtt_password = """"; #define MQTT_RECONNECT_TIME 5000 // Delay(ms) between reconnect tries. #define MQTTprefix HOSTNAME // Change this if you want the MQTT topic to be // independent of the hostname. #define MQTTack MQTTprefix ""/sent"" // Topic we send back acknowledgements on #define MQTTcommand MQTTprefix ""/send"" // Topic we get new commands from. #endif // MQTT_ENABLE // HTML arguments we will parse for IR code information. #define argType ""type"" #define argData ""code"" #define argBits ""bits"" #define argRepeat ""repeats"" #define _MY_VERSION_ ""v0.5"" #if IR_LED != 1 // Disable debug output if the LED is on the TX (D1) pin. #undef DEBUG #define DEBUG true // Change to 'false' to disable all serial output. #else #undef DEBUG #define DEBUG false #endif // NOTE: Make sure you set your Serial Monitor to the same speed. #define BAUD_RATE 115200 // Serial port Baud rate. // Globals ESP8266WebServer server(HTTP_PORT); IRsend irsend = IRsend(IR_LED); MDNSResponder mdns; WiFiClient espClient; WiFiManager wifiManager; uint16_t *codeArray; uint32_t lastReconnectAttempt = 0; // MQTT last attempt reconnection number bool boot = true; bool ir_lock = false; // Primitive locking for gating the IR LED. uint32_t sendReqCounter = 0; int8_t offset; // The calculated period offset for this chip and library. #ifdef MQTT_ENABLE String lastMqttCmd = ""None""; uint32_t lastMqttCmdTime = 0; // MQTT client parameters void callback(char* topic, byte* payload, unsigned int length); PubSubClient mqtt_client(MQTT_SERVER, MQTT_PORT, callback, espClient); // Create a unique MQTT client id. String mqtt_clientid = MQTTprefix + String(ESP.getChipId(), HEX); #endif // MQTT_ENABLE // Debug messages get sent to the serial port. void debug(String str) { #ifdef DEBUG uint32_t now = millis(); Serial.printf(""%07u.%03u: %s\\n"", now / 1000, now % 1000, str.c_str()); #endif // DEBUG } String timeSince(uint32_t const start) { if (start == 0) return ""Never""; uint32_t diff = 0; uint32_t now = millis(); if (start < now) diff = now - start; else diff = UINT32_MAX - start + now; diff /= 1000; // Convert to seconds. if (diff == 0) return ""Now""; // Note: millis() can only count up to 45 days, so uint8_t is safe. uint8_t days = diff / (60 * 60 * 24); uint8_t hours = (diff / (60 * 60)) % 24; uint8_t minutes = (diff / 60) % 60; uint8_t seconds = diff % 60; String result = """"; if (days) result += String(days) + "" day""; if (days > 1) result += ""s""; if (hours) result += "" "" + String(hours) + "" hour""; if (hours > 1) result += ""s""; if (minutes) result += "" "" + String(minutes) + "" minute""; if (minutes > 1) result += ""s""; if (seconds) result += "" "" + String(seconds) + "" second""; if (seconds > 1) result += ""s""; result.trim(); return result + "" ago""; } // Quick and dirty check for any unsafe chars in a string // that may cause HTML shenanigans. e.g. An XSS. bool hasUnsafeHTMLChars(String input) { static char unsafe[] = ""';!-\\""<>=&{}()""; for (uint8_t i = 0; unsafe[i]; i++) if (input.indexOf(unsafe[i]) != -1) return true; return false; } // Root web page with example usage etc. void handleRoot() { server.send(200, ""text/html"", ""IR MQTT server"" """" ""

ESP8266 IR MQTT Server

"" ""

"" ""

Information

"" ""

IP address: "" + WiFi.localIP().toString() + ""
"" ""Booted: "" + timeSince(1) + ""
"" + ""Version: "" _MY_VERSION_ ""
"" ""Period Offset: "" + String(offset) + ""us
"" ""IR Lib Version: "" _IRREMOTEESP8266_VERSION_ ""
"" ""ESP8266 Core Version: "" + ESP.getCoreVersion() + ""
"" ""Total send requests: "" + String(sendReqCounter) + ""

"" #ifdef MQTT_ENABLE ""

MQTT Information

"" ""

Server: "" MQTT_SERVER "":"" + String(MQTT_PORT) + "" ("" + (mqtt_client.connected() ? ""Connected"" : ""Disconnected"") + "")
"" ""Client id: "" + mqtt_clientid + ""
"" ""Command topic: "" MQTTcommand ""
"" ""Acknowledgements topic: "" MQTTack ""
"" ""Last command seen: "" + // lastMqttCmd is unescaped untrusted input. // Avoid any possible HTML/XSS when displaying it. (hasUnsafeHTMLChars(lastMqttCmd) ? ""Contains unsafe HTML characters"" : lastMqttCmd) + "" ("" + timeSince(lastMqttCmdTime) + "")

"" #endif // MQTT_ENABLE ""

"" ""

Hardcoded examples

"" ""

"" ""Sherwood Amp On (GlobalCache)

"" ""

"" ""Sherwood Amp Off (Raw)

"" ""

"" ""Sherwood Amp Input TAPE (Pronto)

"" ""

TV on (Samsung)

"" ""

Power Off (Sony 12bit)

"" ""

"" ""

Send a simple IR message

"" ""

"" ""Type: "" """" "" Code: 0x"" "" Bit size: "" """" "" Repeats: "" "" "" ""
"" ""

"" ""

Send an IRremote Raw IR message

"" ""

"" """" ""String: (freq,array data) "" "" "" ""
"" ""

"" ""

Send a GlobalCache"" "" IR message

"" ""

"" """" ""String: 1:1,1,"" "" "" ""
"" ""

"" ""

Send a Pronto code IR message

"" ""

"" """" ""String (comma separated): "" "" Repeats: "" "" "" ""
"" ""

"" ""

Send an Air Conditioner IR message

"" ""

"" ""Type: "" """" "" State code: 0x"" """" "" "" ""
"" ""

"" ""

Update IR Server firmware

"" ""Warning:
"" ""Updating your firmware may screw up your access to the device. "" ""If you are going to use this, know what you are doing first "" ""(and you probably do).
"" ""

"" ""Firmware to upload: "" """" ""
"" """"); } // Reset web page void handleReset() { server.send(200, ""text/html"", ""Reset Config"" """" ""

Resetting the WiFiManager config back to defaults.

"" ""

Device restarting. Try connecting in a few seconds.

"" """"); // Do the reset. wifiManager.resetSettings(); delay(10); ESP.restart(); delay(1000); } // Parse an Air Conditioner A/C Hex String/code and send it. // Args: // irType: Nr. of the protocol we need to send. // str: A hexadecimal string containing the state to be sent. void parseStringAndSendAirCon(const uint16_t irType, const String str) { uint8_t strOffset = 0; uint8_t state[STATE_SIZE_MAX] = {0}; // All array elements are set to 0. uint16_t stateSize = 0; if (str.startsWith(""0x"") || str.startsWith(""0X"")) strOffset = 2; // Calculate how many hexadecimal characters there are. uint16_t inputLength = str.length() - strOffset; if (inputLength == 0) { debug(""Zero length AirCon code encountered. Ignored.""); return; // No input. Abort. } switch (irType) { // Get the correct state size for the protocol. case KELVINATOR: stateSize = KELVINATOR_STATE_LENGTH; break; case TOSHIBA_AC: stateSize = TOSHIBA_AC_STATE_LENGTH; break; case DAIKIN: stateSize = DAIKIN_COMMAND_LENGTH; break; case MITSUBISHI_AC: stateSize = MITSUBISHI_AC_STATE_LENGTH; break; case TROTEC: stateSize = TROTEC_COMMAND_LENGTH; break; case ARGO: stateSize = ARGO_COMMAND_LENGTH; break; case GREE: stateSize = GREE_STATE_LENGTH; break; case FUJITSU_AC: // Fujitsu has four distinct & different size states, so make a best guess // which one we are being presented with based on the number of // hexadecimal digits provided. i.e. Zero-pad if you need to to get // the correct length/byte size. stateSize = inputLength / 2; // Every two hex chars is a byte. // Use at least the minimum size. stateSize = std::max(stateSize, (uint16_t) (FUJITSU_AC_STATE_LENGTH_SHORT - 1)); // If we think it isn't a ""short"" message. if (stateSize > FUJITSU_AC_STATE_LENGTH_SHORT) // Then it has to be at least the smaller version of the ""normal"" size. stateSize = std::max(stateSize, (uint16_t) (FUJITSU_AC_STATE_LENGTH - 1)); // Lastly, it should never exceed the maximum ""normal"" size. stateSize = std::min(stateSize, (uint16_t) FUJITSU_AC_STATE_LENGTH); break; case HAIER_AC: stateSize = HAIER_AC_STATE_LENGTH; break; case HAIER_AC_YRW02: stateSize = HAIER_AC_YRW02_STATE_LENGTH; break; case HITACHI_AC: stateSize = HITACHI_AC_STATE_LENGTH; break; case HITACHI_AC1: stateSize = HITACHI_AC1_STATE_LENGTH; break; case HITACHI_AC2: stateSize = HITACHI_AC2_STATE_LENGTH; break; default: // Not a protocol we expected. Abort. debug(""Unexpected AirCon protocol detected. Ignoring.""); return; } if (inputLength > stateSize * 2) { debug(""AirCon code to large for the given protocol.""); return; } // Ptr to the least significant byte of the resulting state for this protocol. uint8_t *statePtr = &state[stateSize - 1]; // Convert the string into a state array of the correct length. for (uint16_t i = 0; i < inputLength; i++) { // Grab the next least sigificant hexadecimal digit from the string. uint8_t c = tolower(str[inputLength + strOffset - i - 1]); if (isxdigit(c)) { if (isdigit(c)) c -= '0'; else c = c - 'a' + 10; } else { debug(""Aborting! Non-hexadecimal char found in AirCon state: "" + str); return; } if (i % 2 == 1) { // Odd: Upper half of the byte. *statePtr += (c << 4); statePtr--; // Advance up to the next least significant byte of state. } else { // Even: Lower half of the byte. *statePtr = c; } } // Make the appropriate call for the protocol type. switch (irType) { #if SEND_KELVINATOR case KELVINATOR: irsend.sendKelvinator(reinterpret_cast(state)); break; #endif #if SEND_TOSHIBA_AC case TOSHIBA_AC: irsend.sendToshibaAC(reinterpret_cast(state)); break; #endif #if SEND_DAIKIN case DAIKIN: irsend.sendDaikin(reinterpret_cast(state)); break; #endif #if MITSUBISHI_AC case MITSUBISHI_AC: irsend.sendMitsubishiAC(reinterpret_cast(state)); break; #endif #if SEND_TROTEC case TROTEC: irsend.sendTrotec(reinterpret_cast(state)); break; #endif #if SEND_ARGO case ARGO: irsend.sendArgo(reinterpret_cast(state)); break; #endif #if SEND_GREE case GREE: irsend.sendGree(reinterpret_cast(state)); break; #endif #if SEND_FUJITSU_AC case FUJITSU_AC: irsend.sendFujitsuAC(reinterpret_cast(state), stateSize); break; #endif #if SEND_HAIER_AC case HAIER_AC: irsend.sendHaierAC(reinterpret_cast(state)); break; #endif #if SEND_HAIER_AC_YRW02 case HAIER_AC_YRW02: irsend.sendHaierACYRW02(reinterpret_cast(state)); break; #endif #if SEND_HITACHI_AC case HITACHI_AC: irsend.sendHitachiAC(reinterpret_cast(state)); break; #endif #if SEND_HITACHI_AC1 case HITACHI_AC1: irsend.sendHitachiAC1(reinterpret_cast(state)); break; #endif #if SEND_HITACHI_AC2 case HITACHI_AC2: irsend.sendHitachiAC2(reinterpret_cast(state)); break; #endif } } // Count how many values are in the String. // Args: // str: String containing the values. // sep: Character that separates the values. // Returns: // The number of values found in the String. uint16_t countValuesInStr(const String str, char sep) { int16_t index = -1; uint16_t count = 1; do { index = str.indexOf(sep, index + 1); count++; } while (index != -1); return count; } // Dynamically allocate an array of uint16_t's. // Args: // size: Nr. of uint16_t's need to be in the new array. // Returns: // A Ptr to the new array. Restarts the ESP8266 if it fails. uint16_t * newCodeArray(const uint16_t size) { uint16_t *result; result = reinterpret_cast(malloc(size * sizeof(uint16_t))); // Check we malloc'ed successfully. if (result == NULL) { // malloc failed, so give up. Serial.printf(""\\nCan't allocate %d bytes. (%d bytes free)\\n"", size * sizeof(uint16_t), ESP.getFreeHeap()); Serial.println(""Giving up & forcing a reboot.""); ESP.restart(); // Reboot. delay(500); // Wait for the restart to happen. return result; // Should never get here, but just in case. } return result; } #if SEND_GLOBALCACHE // Parse a GlobalCache String/code and send it. // Args: // str: A GlobalCache formatted String of comma separated numbers. // e.g. ""38000,1,1,170,170,20,63,20,63,20,63,20,20,20,20,20,20,20,20,20, // 20,20,63,20,63,20,63,20,20,20,20,20,20,20,20,20,20,20,20,20,63, // 20,20,20,20,20,20,20,20,20,20,20,20,20,63,20,20,20,63,20,63,20, // 63,20,63,20,63,20,63,20,1798"" // Note: The leading ""1:1,1,"" of normal GC codes should be removed. void parseStringAndSendGC(const String str) { uint16_t count; uint16_t *code_array; String tmp_str; // Remove the leading ""1:1,1,"" if present. if (str.startsWith(""1:1,1,"")) tmp_str = str.substring(6); else tmp_str = str; // Find out how many items there are in the string. count = countValuesInStr(tmp_str, ','); // Now we know how many there are, allocate the memory to store them all. code_array = newCodeArray(count); // Now convert the strings to integers and place them in code_array. count = 0; uint16_t start_from = 0; int16_t index = -1; do { index = tmp_str.indexOf(',', start_from); code_array[count] = tmp_str.substring(start_from, index).toInt(); start_from = index + 1; count++; } while (index != -1); irsend.sendGC(code_array, count); // All done. Send it. free(code_array); // Free up the memory allocated. } #endif // SEND_GLOBALCACHE #if SEND_PRONTO // Parse a Pronto Hex String/code and send it. // Args: // str: A comma-separated String of nr. of repeats, then hexadecimal numbers. // e.g. ""R1,0000,0067,0000,0015,0060,0018,0018,0018,0030,0018,0030,0018, // 0030,0018,0018,0018,0030,0018,0018,0018,0018,0018,0030,0018, // 0018,0018,0030,0018,0030,0018,0030,0018,0018,0018,0018,0018, // 0030,0018,0018,0018,0018,0018,0030,0018,0018,03f6"" // or // ""0000,0067,0000,0015,0060,0018"". i.e. without the Repeat value // Requires at least PRONTO_MIN_LENGTH comma-separated values. // sendPronto() only supports raw pronto code types, thus so does this. // repeats: Nr. of times the message is to be repeated. // This value is ignored if an embeddd repeat is found in str. void parseStringAndSendPronto(const String str, uint16_t repeats) { uint16_t count; uint16_t *code_array; int16_t index = -1; uint16_t start_from = 0; // Find out how many items there are in the string. count = countValuesInStr(str, ','); // Check if we have the optional embedded repeats value in the code string. if (str.startsWith(""R"") || str.startsWith(""r"")) { // Grab the first value from the string, as it is the nr. of repeats. index = str.indexOf(',', start_from); repeats = str.substring(start_from + 1, index).toInt(); // Skip the 'R'. start_from = index + 1; count--; // We don't count the repeats value as part of the code array. } // We need at least PRONTO_MIN_LENGTH values for the code part. if (count < PRONTO_MIN_LENGTH) return; // Now we know how many there are, allocate the memory to store them all. code_array = newCodeArray(count); // Rest of the string are values for the code array. // Now convert the hex strings to integers and place them in code_array. count = 0; do { index = str.indexOf(',', start_from); // Convert the hexadecimal value string to an unsigned integer. code_array[count] = strtoul(str.substring(start_from, index).c_str(), NULL, 16); start_from = index + 1; count++; } while (index != -1); irsend.sendPronto(code_array, count, repeats); // All done. Send it. free(code_array); // Free up the memory allocated. } #endif // SEND_PRONTO #if SEND_RAW // Parse an IRremote Raw Hex String/code and send it. // Args: // str: A comma-separated String containing the freq and raw IR data. // e.g. ""38000,9000,4500,600,1450,600,900,650,1500,..."" // Requires at least two comma-separated values. // First value is the transmission frequency in Hz or kHz. void parseStringAndSendRaw(const String str) { uint16_t count; uint16_t freq = 38000; // Default to 38kHz. uint16_t *raw_array; // Find out how many items there are in the string. count = countValuesInStr(str, ','); // We expect the frequency as the first comma separated value, so we need at // least two values. If not, bail out. if (count < 2) return; count--; // We don't count the frequency value as part of the raw array. // Now we know how many there are, allocate the memory to store them all. raw_array = newCodeArray(count); // Grab the first value from the string, as it is the frequency. int16_t index = str.indexOf(',', 0); freq = str.substring(0, index).toInt(); uint16_t start_from = index + 1; // Rest of the string are values for the raw array. // Now convert the strings to integers and place them in raw_array. count = 0; do { index = str.indexOf(',', start_from); raw_array[count] = str.substring(start_from, index).toInt(); start_from = index + 1; count++; } while (index != -1); irsend.sendRaw(raw_array, count, freq); // All done. Send it. free(raw_array); // Free up the memory allocated. } #endif // SEND_RAW // Parse the URL args to find the IR code. void handleIr() { uint64_t data = 0; String data_str = """"; int ir_type = 3; // Default to NEC codes. uint16_t nbits = 0; uint16_t repeat = 0; for (uint16_t i = 0; i < server.args(); i++) { if (server.argName(i) == argType) ir_type = atoi(server.arg(i).c_str()); if (server.argName(i) == argData) { data = getUInt64fromHex(server.arg(i).c_str()); data_str = server.arg(i); } if (server.argName(i) == argBits) nbits = atoi(server.arg(i).c_str()); if (server.argName(i) == argRepeat) repeat = atoi(server.arg(i).c_str()); } debug(""New code received via HTTP""); sendIRCode(ir_type, data, data_str.c_str(), nbits, repeat); handleRoot(); } void handleNotFound() { String message = ""File Not Found\\n\\n""; message += ""URI: ""; message += server.uri(); message += ""\\nMethod: ""; message += (server.method() == HTTP_GET)?""GET"":""POST""; message += ""\\nArguments: ""; message += server.args(); message += ""\\n""; for (uint8_t i=0; i < server.args(); i++) message += "" "" + server.argName(i) + "": "" + server.arg(i) + ""\\n""; server.send(404, ""text/plain"", message); } void setup_wifi() { delay(10); // We start by connecting to a WiFi network wifiManager.setTimeout(300); // Time out after 5 mins. #if USE_STATIC_IP // Use a static IP config rather than the one supplied via DHCP. wifiManager.setSTAStaticIPConfig(kIPAddress, kGateway, kSubnetMask); #endif // USE_STATIC_IP if (!wifiManager.autoConnect()) { debug(""Wifi failed to connect and hit timeout.""); delay(3000); // Reboot. A.k.a. ""Have you tried turning it Off and On again?"" ESP.reset(); delay(5000); } debug(""WiFi connected. IP address: "" + WiFi.localIP().toString()); } void setup(void) { irsend.begin(); offset = irsend.calibrate(); #ifdef DEBUG // Use SERIAL_TX_ONLY so that the RX pin can be freed up for GPIO/IR use. Serial.begin(BAUD_RATE, SERIAL_8N1, SERIAL_TX_ONLY); while (!Serial) // Wait for the serial connection to be establised. delay(50); Serial.println(); debug(""IRMQTTServer "" _MY_VERSION_"" has booted.""); #endif // DEBUG setup_wifi(); // Wait a bit for things to settle. delay(1500); lastReconnectAttempt = 0; if (mdns.begin(HOSTNAME, WiFi.localIP())) { debug(""MDNS responder started""); } // Setup the root web page. server.on(""/"", handleRoot); // Setup the page to handle web-based IR codes. server.on(""/ir"", handleIr); // Setup a reset page to cause WiFiManager information to be reset. server.on(""/reset"", handleReset); // Setup the URL to allow Over-The-Air (OTA) firmware updates. server.on(""/update"", HTTP_POST, [](){ server.sendHeader(""Connection"", ""close""); server.send(200, ""text/plain"", (Update.hasError())?""FAIL"":""OK""); ESP.restart(); }, [](){ HTTPUpload& upload = server.upload(); if (upload.status == UPLOAD_FILE_START) { WiFiUDP::stopAll(); debug(""Update: "" + upload.filename); uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; if (!Update.begin(maxSketchSpace)) { // start with max available size #ifdef DEBUG Update.printError(Serial); #endif // DEBUG } } else if (upload.status == UPLOAD_FILE_WRITE) { if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { #ifdef DEBUG Update.printError(Serial); #endif // DEBUG } } else if (upload.status == UPLOAD_FILE_END) { if (Update.end(true)) { // true to set the size to the current progress debug(""Update Success: "" + (String) upload.totalSize + ""\\nRebooting...""); } } yield(); }); // Set up an error page. server.onNotFound(handleNotFound); server.begin(); debug(""HTTP server started""); } #ifdef MQTT_ENABLE // MQTT subscribing to topic void subscribing(const String topic_name) { // subscription to topic for receiving data if (mqtt_client.subscribe(topic_name.c_str())) { debug(""Subscription OK to "" + topic_name); } } bool reconnect() { // Loop a few times or until we're reconnected uint16_t tries = 1; while (!mqtt_client.connected() && tries <= 3) { int connected = false; // Attempt to connect debug(""Attempting MQTT connection to "" MQTT_SERVER "":"" + String(MQTT_PORT) + ""... ""); if (mqtt_user && mqtt_password) connected = mqtt_client.connect(mqtt_clientid.c_str(), mqtt_user, mqtt_password); else connected = mqtt_client.connect(mqtt_clientid.c_str()); if (connected) { // Once connected, publish an announcement... mqtt_client.publish(MQTTack, ""Connected""); debug(""connected.""); // Subscribing to topic(s) subscribing(MQTTcommand); } else { debug(""failed, rc="" + String(mqtt_client.state()) + "" Try again in a bit.""); // Wait for a bit before retrying delay(tries << 7); // Linear increasing back-off (x128) } tries++; } return mqtt_client.connected(); } #endif // MQTT_ENABLE void loop(void) { server.handleClient(); #ifdef MQTT_ENABLE // MQTT client connection management if (!mqtt_client.connected()) { uint32_t now = millis(); // Reconnect if it's longer than MQTT_RECONNECT_TIME since we last tried. if (now - lastReconnectAttempt > MQTT_RECONNECT_TIME) { lastReconnectAttempt = now; debug(""client mqtt not connected, trying to connect""); // Attempt to reconnect if (reconnect()) { lastReconnectAttempt = 0; if (boot) { mqtt_client.publish(MQTTack, ""IR Server just booted""); boot = false; } else { mqtt_client.publish(MQTTack, ""IR Server just (re)connected to MQTT""); } } } } else { // MQTT loop mqtt_client.loop(); } #endif // MQTT_ENABLE delay(100); } // Arduino framework doesn't support strtoull(), so make our own one. uint64_t getUInt64fromHex(char const *str) { uint64_t result = 0; uint16_t offset = 0; // Skip any leading '0x' or '0X' prefix. if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) offset = 2; for (; isxdigit((unsigned char)str[offset]); offset++) { char c = str[offset]; result *= 16; if (isdigit(c)) /* '0' .. '9' */ result += c - '0'; else if (isupper(c)) /* 'A' .. 'F' */ result += c - 'A' + 10; else /* 'a' .. 'f'*/ result += c - 'a' + 10; } return result; } // Transmit the given IR message. // // Args: // ir_type: enum of the protocol to be sent. // code: Numeric payload of the IR message. Most protocols use this. // code_str: The unparsed code to be sent. Used by complex protocol encodings. // bits: Nr. of bits in the protocol. 0 means use the protocol's default. // repeat: Nr. of times the message is to be repeated. (Not all protcols.) void sendIRCode(int const ir_type, uint64_t const code, char const * code_str, uint16_t bits, uint16_t repeat) { // Create a pseudo-lock so we don't try to send two codes at the same time. while (ir_lock) delay(20); ir_lock = true; // send the IR message. switch (ir_type) { #if SEND_RC5 case RC5: // 1 if (bits == 0) bits = RC5_BITS; irsend.sendRC5(code, bits, repeat); break; #endif #if SEND_RC6 case RC6: // 2 if (bits == 0) bits = RC6_MODE0_BITS; irsend.sendRC6(code, bits, repeat); break; #endif #if SEND_NEC case NEC: // 3 if (bits == 0) bits = NEC_BITS; irsend.sendNEC(code, bits, repeat); break; #endif #if SEND_SONY case SONY: // 4 if (bits == 0) bits = SONY_12_BITS; repeat = std::max(repeat, (uint16_t) SONY_MIN_REPEAT); irsend.sendSony(code, bits, repeat); break; #endif #if SEND_PANASONIC case PANASONIC: // 5 if (bits == 0) bits = PANASONIC_BITS; irsend.sendPanasonic64(code, bits, repeat); break; #endif #if SEND_JVC case JVC: // 6 if (bits == 0) bits = JVC_BITS; irsend.sendJVC(code, bits, repeat); break; #endif #if SEND_SAMSUNG case SAMSUNG: // 7 if (bits == 0) bits = SAMSUNG_BITS; irsend.sendSAMSUNG(code, bits, repeat); break; #endif #if SEND_WHYNTER case WHYNTER: // 8 if (bits == 0) bits = WHYNTER_BITS; irsend.sendWhynter(code, bits, repeat); break; #endif #if SEND_AIWA_RC_T501 case AIWA_RC_T501: // 9 if (bits == 0) bits = AIWA_RC_T501_BITS; repeat = std::max(repeat, (uint16_t) AIWA_RC_T501_MIN_REPEAT); irsend.sendAiwaRCT501(code, bits, repeat); break; #endif #if SEND_LG case LG: // 10 if (bits == 0) bits = LG_BITS; irsend.sendLG(code, bits, repeat); break; #endif #if SEND_MITSUBISHI case MITSUBISHI: // 12 if (bits == 0) bits = MITSUBISHI_BITS; repeat = std::max(repeat, (uint16_t) MITSUBISHI_MIN_REPEAT); irsend.sendMitsubishi(code, bits, repeat); break; #endif #if SEND_DISH case DISH: // 13 if (bits == 0) bits = DISH_BITS; repeat = std::max(repeat, (uint16_t) DISH_MIN_REPEAT); irsend.sendDISH(code, bits, repeat); break; #endif #if SEND_SHARP case SHARP: // 14 if (bits == 0) bits = SHARP_BITS; irsend.sendSharpRaw(code, bits, repeat); break; #endif #if SEND_COOLIX case COOLIX: // 15 if (bits == 0) bits = COOLIX_BITS; irsend.sendCOOLIX(code, bits, repeat); break; #endif case DAIKIN: // 16 case KELVINATOR: // 18 case MITSUBISHI_AC: // 20 case GREE: // 24 case ARGO: // 27 case TROTEC: // 28 case TOSHIBA_AC: // 32 case FUJITSU_AC: // 33 case HAIER_AC: // 38 case HAIER_AC_YRW02: // 44 case HITACHI_AC: // 40 case HITACHI_AC1: // 41 case HITACHI_AC2: // 42 parseStringAndSendAirCon(ir_type, code_str); break; #if SEND_DENON case DENON: // 17 if (bits == 0) bits = DENON_BITS; irsend.sendDenon(code, bits, repeat); break; #endif #if SEND_SHERWOOD case SHERWOOD: // 19 if (bits == 0) bits = SHERWOOD_BITS; repeat = std::max(repeat, (uint16_t) SHERWOOD_MIN_REPEAT); irsend.sendSherwood(code, bits, repeat); break; #endif #if SEND_RCMM case RCMM: // 21 if (bits == 0) bits = RCMM_BITS; irsend.sendRCMM(code, bits, repeat); break; #endif #if SEND_SANYO case SANYO_LC7461: // 22 if (bits == 0) bits = SANYO_LC7461_BITS; irsend.sendSanyoLC7461(code, bits, repeat); break; #endif #if SEND_RC5 case RC5X: // 23 if (bits == 0) bits = RC5X_BITS; irsend.sendRC5(code, bits, repeat); break; #endif #if SEND_PRONTO case PRONTO: // 25 parseStringAndSendPronto(code_str, repeat); break; #endif #if SEND_NIKAI case NIKAI: // 29 if (bits == 0) bits = NIKAI_BITS; irsend.sendNikai(code, bits, repeat); break; #endif #if SEND_RAW case RAW: // 30 parseStringAndSendRaw(code_str); break; #endif #if SEND_GLOBALCACHE case GLOBALCACHE: // 31 parseStringAndSendGC(code_str); break; #endif #if SEND_MIDEA case MIDEA: // 34 if (bits == 0) bits = MIDEA_BITS; irsend.sendMidea(code, bits, repeat); break; #endif #if SEND_MAGIQUEST case MAGIQUEST: // 35 if (bits == 0) bits = MAGIQUEST_BITS; irsend.sendMagiQuest(code, bits, repeat); break; #endif #if SEND_LASERTAG case LASERTAG: // 36 if (bits == 0) bits = LASERTAG_BITS; irsend.sendLasertag(code, bits, repeat); break; #endif #if SEND_CARRIER_AC case CARRIER_AC: // 37 if (bits == 0) bits = CARRIER_AC_BITS; irsend.sendCarrierAC(code, bits, repeat); break; #endif #if SEND_MITSUBISHI2 case MITSUBISHI2: // 39 if (bits == 0) bits = MITSUBISHI_BITS; repeat = std::max(repeat, (uint16_t) MITSUBISHI_MIN_REPEAT); irsend.sendMitsubishi2(code, bits, repeat); break; #endif #if SEND_GICABLE case GICABLE: // 43 if (bits == 0) bits = GICABLE_BITS; repeat = std::max(repeat, (uint16_t) GICABLE_MIN_REPEAT); irsend.sendGICable(code, bits, repeat); break; #endif } sendReqCounter++; // Release the lock. ir_lock = false; // Indicate that we sent the message. debug(""Sent the IR message.""); debug(""Type: "" + String(ir_type)); // For ""long"" codes we basically repeat what we got. if (hasACState((decode_type_t) ir_type) || ir_type == PRONTO || ir_type == RAW || ir_type == GLOBALCACHE) { debug(""Code: ""); debug(code_str); debug(""Repeats: "" + String(repeat)); // Confirm what we were asked to send was sent. #ifdef MQTT_ENABLE if (ir_type == PRONTO && repeat > 0) mqtt_client.publish(MQTTack, (String(ir_type) + "",R"" + String(repeat) + "","" + String(code_str)).c_str()); else mqtt_client.publish(MQTTack, (String(ir_type) + "","" + String(code_str)).c_str()); #endif // MQTT_ENABLE } else { // For ""short"" codes, we break it down a bit more before we report. debug(""Code: 0x"" + uint64ToString(code, 16)); debug(""Bits: "" + String(bits)); debug(""Repeats: "" + String(repeat)); #ifdef MQTT_ENABLE mqtt_client.publish(MQTTack, (String(ir_type) + "","" + uint64ToString(code, 16) + "","" + String(bits) + "","" + String(repeat)).c_str()); #endif // MQTT_ENABLE } } #ifdef MQTT_ENABLE void receivingMQTT(String const topic_name, String const callback_str) { char* tok_ptr; uint64_t code = 0; uint16_t nbits = 0; uint16_t repeat = 0; debug(""Receiving data by MQTT topic "" + topic_name); // Make a copy of the callback string as strtok destroys it. char* callback_c_str = strdup(callback_str.c_str()); debug(""MQTT Payload (raw): "" + callback_str); // Save the message as the last command seen (global). lastMqttCmd = callback_str; lastMqttCmdTime = millis(); // Get the numeric protocol type. int ir_type = strtoul(strtok_r(callback_c_str, "","", &tok_ptr), NULL, 10); char* next = strtok_r(NULL, "","", &tok_ptr); // If there is unparsed string left, try to convert it assuming it's hex. if (next != NULL) { code = getUInt64fromHex(next); next = strtok_r(NULL, "","", &tok_ptr); } else { // We require at least two value in the string. Give up. return; } // If there is still string left, assume it is the bit size. if (next != NULL) { nbits = atoi(next); next = strtok_r(NULL, "","", &tok_ptr); } // If there is still string left, assume it is the repeat count. if (next != NULL) repeat = atoi(next); free(callback_c_str); // send received MQTT value by IR signal sendIRCode(ir_type, code, callback_str.substring(callback_str.indexOf("","") + 1).c_str(), nbits, repeat); } // Callback function, when the gateway receive an MQTT value on the topics // subscribed this function is called void callback(char* topic, byte* payload, unsigned int length) { // In order to republish this payload, a copy must be made // as the orignal payload buffer will be overwritten whilst // constructing the PUBLISH packet. // Allocate the correct amount of memory for the payload copy byte* payload_copy = reinterpret_cast(malloc(length + 1)); // Copy the payload to the new buffer memcpy(payload_copy, payload, length); // Conversion to a printable string payload_copy[length] = '\\0'; String callback_string = String(reinterpret_cast(payload_copy)); String topic_name = String(reinterpret_cast(topic)); // launch the function to treat received data receivingMQTT(topic_name, callback_string); // Free the memory free(payload_copy); } #endif // MQTT_ENABLE ",16353,True,2560.3712095750443,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { COMPILE::JS public class XMLList { import org.apache.royale.debugging.throwError; import org.apache.royale.language.toAttributeName; /** * regex to match the xml declaration */ private static const xmlDecl:RegExp = /^\\s*<\\?xml[^?]*\\?>/im; /** * mimics the top-level XMLList function (supports 'this' correctly) * * @royalesuppressexport * @royaleignorecoercion XMLList */ public static function conversion(val:* = null):XMLList{ if (val && val.constructor == XMLList) return val as XMLList; else return new XMLList(val); } public function XMLList(expression:Object = null) { addIndex(0); if(expression != null) parseExpression(expression); } /** * @royaleignorecoercion String */ private function parseExpression(expression:Object):void { if(expression is XMLList) { targetObject = expression.targetObject; targetProperty = expression.targetProperty; var len:int = expression.length(); for(var i:int=0;i"") == 0 && expstr.indexOf("""") == expstr.length - 3) expression = expstr.substr(2, expstr.length - 5); } try { var item:XML = new XML(expression); if (item.nodeKind() == 'text' && item.getValue() == '') return; this[0] = item; } catch (e:Error) { if (typeof(expression) === ""string"") { var decl:String = xmlDecl.exec(expression); if (decl) expression = expression.replace(decl,''); // try adding a wrapping node and then grab the children expression = """" + expression + """"; try { var xml:XML = new XML(expression); var list:XMLList = xml.children(); var m:int = list.length(); for (var j:int = 0; j < m; j++) { this[j] = list[j]; } } catch (e2:Error) { throw e; // throw original error } } else throw e; } } } /** * [[ResolveValue]] from the e4x spec * @royaleignorecoercion QName * @royaleignorecoercion XMLList */ private function resolveValue():*{ if (_xmlArray.length > 0) return this; if ((_targetObject == null || _targetProperty == null) || (_targetProperty is QName && (QName(_targetProperty).isAttribute || QName(_targetProperty).localName == '*'))) return null; //2,a var base:* = (!_targetObject || _targetObject is XML) ? _targetObject : (_targetObject as XMLList).resolveValue(); if (base==null) return null; var target:XMLList = base.child(_targetProperty); if (target.length() == 0) { if (base is XMLList && (base.length() > 1)) return null; base.setChild(_targetProperty, ''); target = base.child(_targetProperty); } return target; } private var _xmlArray:Array = []; /* 9.2.1.2 [[Put]] (P, V) Overview The XMLList type overrides the internal [[Put]] method defined by the Object type. The XMLList [[Put]] method is used to modify or replace an XML object within the XMLList and the context of its parent. In addition, when the XMLList contains a single property with an XML object, the [[Put]] method is used to modify, replace, and insert properties or XML attributes of that value by name. The input argument P identifies which portion of the XMLList and associated XML objects will be affected and may be a numeric property name, an unqualified name for an XML attribute (distinguished from XML valued property names by a leading “@” symbol) or set of XML elements, a QName for a set of XML elements, an AttributeName for a set of XML attributes or the properties wildcard “*”. When the input argument P is an unqualified XML element name, it identifies XML elements in the default namespace. When the input argument P is an unqualified XML attribute name, it identifies XML attributes in no namespace. The input argument V may be a value of type XML, XMLList or any value that can be converted to a String with ToString(). NOTE Unlike the internal Object [[Put]] method, the internal XMLList [[Put]] method is never used for modifying the set of methods associated with XMLList objects. Semantics When the [[Put]] method of an XMLList object x is called with property name P and value V, the following steps are taken: 1. Let i = ToUint32(P) 2. If ToString(i) == P a. If x.[[TargetObject]] is not null i. Let r be the result of calling the [[ResolveValue]] method of x.[[TargetObject]] ii. If r == null, return b. Else let r = null c. If i is greater than or equal to x.[[Length]] i. If Type(r) is XMLList 1. If r.[[Length]] is not equal to 1, return 2. Else let r = r[0] ii. If r.[[Class]] is not equal to ""element"", return iii. Create a new XML object y with y.[[Parent]] = r, y.[[Name]] = x.[[TargetProperty]], y.[[Attributes]] = {}, y.[[Length]] = 0 iv. If Type(x.[[TargetProperty]]) is AttributeName 1. Let attributeExists be the result of calling the [[Get]] method of r with argument y.[[Name]] 2. If (attributeExists.[[Length]] > 0), return 3. Let y.[[Class]] = ""attribute"" v. Else if x.[[TargetProperty]] == null or x.[[TargetProperty]].localName == ""*"" 1. Let y.[[Name]] = null 2. Let y.[[Class]] = ""text"" vi. Else let y.[[Class]] = ""element"" vii. Let i = x.[[Length]] viii. If (y.[[Class]] is not equal to ""attribute"") 1. If r is not null a. If (i > 0) i. Let j = 0 ii. While (j < r.[[Length]]-1) and (r[j] is not the same object as x[i-1]) 1. Let j = j + 1 b. Else i. Let j = r.[[Length]]-1 c. Call the [[Insert]] method of r with arguments ToString(j+1) and y 2. If Type(V) is XML, let y.[[Name]] = V.[[Name]] 3. Else if Type(V) is XMLList, let y.[[Name]] = V.[[TargetProperty]] ix. Call the [[Append]] method of x with argument y d. If (Type(V) ∉ {XML, XMLList}) or (V.[[Class]] ∈ {""text"", ""attribute""}), let V = ToString(V) e. If x[i].[[Class]] == ""attribute"" i. Let z = ToAttributeName(x[i].[[Name]]) ii. Call the [[Put]] method of x[i].[[Parent]] with arguments z and V iii. Let attr be the result of calling [[Get]] on x[i].[[Parent]] with argument z iv. Let x[i] = attr[0] f. Else if Type(V) is XMLList i. Create a shallow copy c of V ii. Let parent = x[i].[[Parent]] iii. If parent is not null 1. Let q be the property of parent, such that parent[q] is the same object as x[i] 2. Call the [[Replace]] method of parent with arguments q and c 3. For j = 0 to c.[[Length]]-1 a. Let c[j] = parent[ToUint32(q)+j] iv. If c.[[Length]] == 0 1. For j = i + 1 to x.[[Length]] – 1, rename property j of x to ToString(j-1) v. Else 1. For j = x.[[Length]]-1 downto i + 1, rename property j of x to ToString(j + c.[[Length]] - 1) vi. For j = 0 to c.[[Length]]-1, let x[i + j] = c[j] vii. Let x.[[Length]] = x.[[Length]] + c.[[Length]] - 1 g. Else if (Type(V) is XML) or (x[i].[[Class]] ∈ {""text"", ""comment"", ""processing-instruction""}) i. Let parent = x[i].[[Parent]] ii. If parent is not null 1. Let q be the property of parent, such that parent[q] is the same object as x[i] 2. Call the [[Replace]] method of parent with arguments q and V 3. Let V = parent[q] iii. If Type(V) is String 1. Create a new XML object t with t.[[Class]] = ""text"", t.[[Parent]] = x and t.[[Value]] = V 2. Let x[i] = t iv. Else 1. Let x[i] = V h. Else i. Call the [[Put]] method of x[i] with arguments ""*"" and V 3. Else if x.[[Length]] is less than or equal to 1 a. If x.[[Length]] == 0 i. Let r be the result of calling the [[ResolveValue]] method of x ii. If (r == null) or (r.[[Length]] is not equal to 1), return iii. Call the [[Append]] method of x with argument r b. Call the [[Put]] method of x[0] with arguments P and V 4. Return */ private function addIndex(idx:int):void { var idxStr:String = """" + idx; Object.defineProperty(this,idxStr, { ""get"": function():* { return _xmlArray[idx]; }, ""set"": function(newValue:*):void { if(idx >= _xmlArray.length) append(newValue); else replaceChildAt(idx,newValue); }, enumerable: true, configurable: true } ); } /* [[Append]] from the e4x spec When the [[Append]] method of an XMLList object x is called with value V, the following steps are taken: 1. Let i = x.[[Length]] 2. Let n = 1 3. If Type(V) is XMLList, a. Let x.[[TargetObject]] = V.[[TargetObject]] b. Let x.[[TargetProperty]] = V.[[TargetProperty]] c. Let n = V.[[Length]] d. If n == 0, Return e. For j = 0 to V.[[Length]]-1, let x[i + j] = V[j] f. 4. Let x.[[Length]] = x.[[Length]] + n 5. Return */ /** * * @royaleignorecoercion XMLList * @royaleignorecoercion XML */ private function Append(content:Object):void{ var i:uint = _xmlArray.length; var n:uint = 1; if (content is XMLList) { var l:XMLList = content as XMLList; _targetObject = l._targetObject;//3.a _targetProperty = l._targetProperty;//3.b n = l.length();//3.c if (n == 0) return;//3.d for (var j:uint =0; j < n; j++){ //[[Put]] _xmlArray[i+j] = l._xmlArray[j]; //3.e addIndex(i+j); //setChild( i+j, l._xmlArray[j]); } } else { if (content is XML) { //[[Put]] //setChild( i, content as XML); //3.e _xmlArray[i] = content; //3.e addIndex(i); } } } public function append(child:XML):void { _xmlArray[_xmlArray.length] = child; addIndex(_xmlArray.length); do//while false { if(!_targetObject) break; if(!_targetProperty) { _targetObject.appendChild(child); break; } var objToAppend:XMLList = _targetObject.child(_targetProperty); if(!objToAppend.length()) { _targetObject.appendChild(child); break; } _targetObject.insertChildAfter(objToAppend[objToAppend.length()-1],child); }while(false); } public function appendChild(child:*):XML { if(isSingle()) return _xmlArray[0].appendChild(child); return null; } /** * Calls the attribute() method of each XML object and returns an XMLList object of the results. * * @param attributeName * @return * */ public function attribute(attributeName:*):XMLList { if(isSingle()) return _xmlArray[0].attribute(attributeName); var retVal:XMLList = new XMLList(); var len:int = _xmlArray.length; for (var i:int=0;i= 0 && propNum < _xmlArray.length) { retVal.append(_xmlArray[propNum]); retVal.targetObject = _xmlArray[propNum]; } return retVal; } if(isEmpty()) { retVal.targetObject = this; } if(isSingle()) return _xmlArray[0].child(propertyName); var len:int = _xmlArray.length; for (var i:int=0;i= 0; i--) { if(_xmlArray[i] == child) { _xmlArray.splice(i,1); if(child.hasAncestor(_targetObject)) child.parent().removeChild(child); } } } } public function removeChildAt(idx:int):void { if(idx >= 0 && idx < _xmlArray.length) { var child:XML = _xmlArray[idx]; _xmlArray.splice(idx,1); if(child.hasAncestor(_targetObject)) child.parent().removeChild(child); } } private function replaceChildAt(idx:int,child:*):void { var i:int; var childToReplace:XML = _xmlArray[idx]; if(childToReplace && _targetObject) { _targetObject.replaceChildAt(childToReplace.childIndex(),child); } if(child is XML) { _xmlArray[idx] = child; } else if(child is XMLList) { var len:int = child.length(); for(i=0;i""; } else { xmlStr += _targetProperty + ""/>""; } ret = new XML(xmlStr); } return ret; } public function setAttribute(attr:*,value:String):String { /*if(isEmpty() && targetObject)//walk up the tree and create nodes. _xmlArray[0] = targetObject.setChild(_targetProperty,xmlFromProperty(targetObject)); var len:int = _xmlArray.length; for (var i:int=0;i= _xmlArray.length) { //2.c var xmlR:XML = r as XML; if (!r && r is XMLList) { //2.c.i if (!(r as XMLList).isSingle()) return null; //2.c.i.1 xmlR = r[0]; //2.c.i.2 } if (xmlR && xmlR.nodeKind() != 'element') return null; //2.c.ii var y:XML = xmlFromProperty(xmlR); idx = _xmlArray.length; if (y.nodeKind() != 'attribute') {//2.c.vii if (xmlR) { //2.c.viii.1 if (idx > 0) { //2.c.viii.1.a var j:uint = 0; while (j < xmlR.getChildrenArray().length-1 && xmlR.getChildrenArray()[j] !== _xmlArray[idx-1]) { j++; } } else { j = xmlR.getChildrenArray().length -1; //2.c.viii.1.b } xmlR.insertChildAfter(xmlR.getChildrenArray()[j], y); //2.c.viii.1.c } if (elements is XML) y.setName((elements as XML).name());//2.c.viii.2 else if (elements is XMLList) y.setName(new QName((elements as XMLList)._targetProperty)); //2.c.viii.3 } //append(y); Append(y); } if ( !(elements is XML || elements is XMLList) || (elements is XML && ((elements as XML).nodeKind() == 'text' || (elements as XML).nodeKind() == 'attribute'))) { //2.d elements = elements + ''; } if ((_xmlArray[idx] as XML).nodeKind() == 'attribute') { var z:QName = (_xmlArray[idx] as XML).name(); (_xmlArray[idx] as XML).parent().setAttribute(z, elements); var attr:XMLList = (_xmlArray[idx] as XML).parent().attribute(z); _xmlArray[idx] = attr[0]; addIndex(idx); } else if (elements is XMLList) { var c:XMLList = new XMLList(elements); // 2.f.i (shallow copy) var parent:XML = (_xmlArray[idx] as XML).parent(); if (parent) { //1. Let q be the property of parent, such that parent[q] is the same object as x[i] @todo verify what this actually means var q:int = parent.getChildrenArray().indexOf(_xmlArray[idx]); //2. Call the [[Replace]] method of parent with arguments q and c parent.replaceChildAt(q, c); for (j =0; j idx; j--) { _xmlArray[j+cl] = _xmlArray[j]; addIndex(j+cl); } for (j = 0; j< cl; j++) { _xmlArray[idx+j] = c[j]; addIndex(idx+j); } } } else if (elements is XML || (_xmlArray[idx] as XML).nodeKind() == 'text' || (_xmlArray[idx] as XML).nodeKind() == 'comment' || (_xmlArray[idx] as XML).nodeKind() == 'processing-instruction') { parent = (_xmlArray[idx] as XML).parent(); if (parent) { //1. Let q be the property of parent, such that parent[q] is the same object as x[i] @todo verify what this actually means q = parent.getChildrenArray().indexOf(_xmlArray[idx]); //2. Call the [[Replace]] method of parent with arguments q and c parent.replaceChildAt(q, elements); elements = parent.getChildrenArray()[q]; } if (typeof elements == 'string') { var t:XML = new XML(); t.setParent(this as XML); //this is not XML... but we can cheat t.setValue(elements+''); _xmlArray[idx] = t; } else { _xmlArray[idx] = elements; } addIndex(idx); } else { (_xmlArray[idx] as XML).setChild('*', elements); } } else { //3 if (_xmlArray.length <= 1) { //3.a if (isEmpty()) { r = resolveValue(); if (r == null || r.length() != 1) return null; Append(r) } (_xmlArray[0] as XML).setChild(elementName, elements); } else { //match AVM, this is not covered in spec which says nothing, avm does this: throw new TypeError('Error #1089: Assignment to lists with more than one item is not supported.') } } return elements; } public function setParent(parent:XML):void { if(isSingle()) _xmlArray[0].setParent(parent); } public function setChildren(value:Object):XML { if(isSingle()) return _xmlArray[0].setChildren(value); return null; } public function setLocalName(name:String):void { if(isSingle()) _xmlArray[0].setLocalName(name); } public function setName(name:String):void { if(isSingle()) _xmlArray[0].setName(name); } public function setNamespace(ns:Namespace):void { if(isSingle()) _xmlArray[0].setNamespace(ns); } /** * Calls the text() method of each XML object and returns an XMLList object that contains the results. * * @return * */ public function text():XMLList { var retVal:XMLList = new XMLList(); var len:int = _xmlArray.length; for (var i:int=0;i * Sometimes it's hard to know what values to set, especially if you want gravity, jumping, sliding, etc.
* This class helps sort that - and adds some cool extra functionality too :) * * TODO * ---- * Allow to bind Fire Button to FlxWeapon * Allow to enable multiple key sets. So cursors and WASD together * Hot Keys * Binding of sound effects to keys (seperate from setSounds? as those are event based) * If moving diagonally compensate speed parameter (times x,y velocities by 0.707 or cos/sin(45)) * Specify animation frames to play based on velocity * Variable gravity (based on height, the higher the stronger the effect) */ public class FlxControlHandler { // Used by the FlxControl plugin public var enabled:Boolean = false; private var entity:FlxSprite = null; private var bounds:Rectangle; private var up:Boolean; private var down:Boolean; private var left:Boolean; private var right:Boolean; private var fire:Boolean; private var altFire:Boolean; private var jump:Boolean; private var altJump:Boolean; private var xFacing:Boolean; private var yFacing:Boolean; private var rotateAntiClockwise:Boolean; private var rotateClockwise:Boolean; private var upMoveSpeed:int; private var downMoveSpeed:int; private var leftMoveSpeed:int; private var rightMoveSpeed:int; private var thrustSpeed:int; private var reverseSpeed:int; // Rotation private var thrustEnabled:Boolean; private var reverseEnabled:Boolean; private var isRotating:Boolean; private var antiClockwiseRotationSpeed:Number; private var clockwiseRotationSpeed:Number; private var enforceAngleLimits:Boolean; private var minAngle:int; private var maxAngle:int; private var capAngularVelocity:Boolean; private var xSpeedAdjust:Number = 0; private var ySpeedAdjust:Number = 0; private var gravityX:int = 0; private var gravityY:int = 0; private var fireRate:int; // The ms delay between firing when the key is held down private var nextFireTime:int; // The internal time when they can next fire private var lastFiredTime:int; // The internal time of when when they last fired private var fireKeyMode:uint; // The fire key mode private var fireCallback:Function; // A function to call every time they fire private var jumpHeight:int; // The pixel height amount they jump (drag and gravity also both influence this) private var jumpRate:int; // The ms delay between jumping when the key is held down private var jumpKeyMode:uint; // The jump key mode private var nextJumpTime:int; // The internal time when they can next jump private var lastJumpTime:int; // The internal time of when when they last jumped private var jumpFromFallTime:int; // A short window of opportunity for them to jump having just fallen off the edge of a surface private var extraSurfaceTime:int; // Internal time of when they last collided with a valid jumpSurface private var jumpSurface:uint; // The surfaces from FlxObject they can jump from (i.e. FlxObject.FLOOR) private var jumpCallback:Function; // A function to call every time they jump private var movement:int; private var stopping:int; private var rotation:int; private var rotationStopping:int; private var capVelocity:Boolean; private var hotkeys:Array; // TODO private var upKey:String; private var downKey:String; private var leftKey:String; private var rightKey:String; private var fireKey:String; private var altFireKey:String; // TODO private var jumpKey:String; private var altJumpKey:String; // TODO private var antiClockwiseKey:String; private var clockwiseKey:String; private var thrustKey:String; private var reverseKey:String; // Sounds private var jumpSound:FlxSound = null; private var fireSound:FlxSound = null; private var walkSound:FlxSound = null; private var thrustSound:FlxSound = null; // Helpers public var isPressedUp:Boolean = false; public var isPressedDown:Boolean = false; public var isPressedLeft:Boolean = false; public var isPressedRight:Boolean = false; /** * The ""Instant"" Movement Type means the sprite will move at maximum speed instantly, and will not ""accelerate"" (or speed-up) before reaching that speed. */ public static const MOVEMENT_INSTANT:int = 0; /** * The ""Accelerates"" Movement Type means the sprite will accelerate until it reaches maximum speed. */ public static const MOVEMENT_ACCELERATES:int = 1; /** * The ""Instant"" Stopping Type means the sprite will stop immediately when no direction keys are being pressed, there will be no deceleration. */ public static const STOPPING_INSTANT:int = 0; /** * The ""Decelerates"" Stopping Type means the sprite will start decelerating when no direction keys are being pressed. Deceleration continues until the speed reaches zero. */ public static const STOPPING_DECELERATES:int = 1; /** * The ""Never"" Stopping Type means the sprite will never decelerate, any speed built up will be carried on and never reduce. */ public static const STOPPING_NEVER:int = 2; /** * The ""Instant"" Movement Type means the sprite will rotate at maximum speed instantly, and will not ""accelerate"" (or speed-up) before reaching that speed. */ public static const ROTATION_INSTANT:int = 0; /** * The ""Accelerates"" Rotaton Type means the sprite will accelerate until it reaches maximum rotation speed. */ public static const ROTATION_ACCELERATES:int = 1; /** * The ""Instant"" Stopping Type means the sprite will stop rotating immediately when no rotation keys are being pressed, there will be no deceleration. */ public static const ROTATION_STOPPING_INSTANT:int = 0; /** * The ""Decelerates"" Stopping Type means the sprite will start decelerating when no rotation keys are being pressed. Deceleration continues until rotation speed reaches zero. */ public static const ROTATION_STOPPING_DECELERATES:int = 1; /** * The ""Never"" Stopping Type means the sprite will never decelerate, any speed built up will be carried on and never reduce. */ public static const ROTATION_STOPPING_NEVER:int = 2; /** * This keymode fires for as long as the key is held down */ public static const KEYMODE_PRESSED:int = 0; /** * This keyboard fires when the key has just been pressed down, and not again until it is released and re-pressed */ public static const KEYMODE_JUST_DOWN:int = 1; /** * This keyboard fires only when the key has been pressed and then released again */ public static const KEYMODE_RELEASED:int = 2; /** * Sets the FlxSprite to be controlled by this class, and defines the initial movement and stopping types.
* After creating an instance of this class you should call setMovementSpeed, and one of the enableXControl functions if you need more than basic cursors. * * @param source The FlxSprite you want this class to control. It can only control one FlxSprite at once. * @param movementType Set to either MOVEMENT_INSTANT or MOVEMENT_ACCELERATES * @param stoppingType Set to STOPPING_INSTANT, STOPPING_DECELERATES or STOPPING_NEVER * @param updateFacing If true it sets the FlxSprite.facing value to the direction pressed (default false) * @param enableArrowKeys If true it will enable all arrow keys (default) - see setCursorControl for more fine-grained control * * @see setMovementSpeed */ public function FlxControlHandler(source:FlxSprite, movementType:int, stoppingType:int, updateFacing:Boolean = false, enableArrowKeys:Boolean = true) { entity = source; movement = movementType; stopping = stoppingType; xFacing = updateFacing; yFacing = updateFacing; up = false; down = false; left = false; right = false; thrustEnabled = false; isRotating = false; enforceAngleLimits = false; rotation = ROTATION_INSTANT; rotationStopping = ROTATION_STOPPING_INSTANT; if (enableArrowKeys) { setCursorControl(); } enabled = true; } /** * Set the speed at which the sprite will move when a direction key is pressed.
* All values are given in pixels per second. So an xSpeed of 100 would move the sprite 100 pixels in 1 second (1000ms)
* Due to the nature of the internal Flash timer this amount is not 100% accurate and will vary above/below the desired distance by a few pixels.
* * If you need different speed values for left/right or up/down then use setAdvancedMovementSpeed * * @param xSpeed The speed in pixels per second in which the sprite will move/accelerate horizontally * @param ySpeed The speed in pixels per second in which the sprite will move/accelerate vertically * @param xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally * @param ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically * @param xDeceleration A deceleration speed in pixels per second to apply to the sprites horizontal movement (default 0) * @param yDeceleration A deceleration speed in pixels per second to apply to the sprites vertical movement (default 0) */ public function setMovementSpeed(xSpeed:uint, ySpeed:uint, xSpeedMax:uint, ySpeedMax:uint, xDeceleration:uint = 0, yDeceleration:uint = 0):void { leftMoveSpeed = -xSpeed; rightMoveSpeed = xSpeed; upMoveSpeed = -ySpeed; downMoveSpeed = ySpeed; setMaximumSpeed(xSpeedMax, ySpeedMax); setDeceleration(xDeceleration, yDeceleration); } /** * If you know you need the same value for the acceleration, maximum speeds and (optionally) deceleration then this is a quick way to set them. * * @param speed The speed in pixels per second in which the sprite will move/accelerate/decelerate * @param acceleration If true it will set the speed value as the deceleration value (default) false will leave deceleration disabled */ public function setStandardSpeed(speed:uint, acceleration:Boolean = true):void { if (acceleration) { setMovementSpeed(speed, speed, speed, speed, speed, speed); } else { setMovementSpeed(speed, speed, speed, speed); } } /** * Set the speed at which the sprite will move when a direction key is pressed.
* All values are given in pixels per second. So an xSpeed of 100 would move the sprite 100 pixels in 1 second (1000ms)
* Due to the nature of the internal Flash timer this amount is not 100% accurate and will vary above/below the desired distance by a few pixels.
* * If you don't need different speed values for every direction on its own then use setMovementSpeed * * @param leftSpeed The speed in pixels per second in which the sprite will move/accelerate to the left * @param rightSpeed The speed in pixels per second in which the sprite will move/accelerate to the right * @param upSpeed The speed in pixels per second in which the sprite will move/accelerate up * @param downSpeed The speed in pixels per second in which the sprite will move/accelerate down * @param xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally * @param ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically * @param xDeceleration Deceleration speed in pixels per second to apply to the sprites horizontal movement (default 0) * @param yDeceleration Deceleration speed in pixels per second to apply to the sprites vertical movement (default 0) */ public function setAdvancedMovementSpeed(leftSpeed:uint, rightSpeed:uint, upSpeed:uint, downSpeed:uint, xSpeedMax:uint, ySpeedMax:uint, xDeceleration:uint = 0, yDeceleration:uint = 0):void { leftMoveSpeed = -leftSpeed; rightMoveSpeed = rightSpeed; upMoveSpeed = -upSpeed; downMoveSpeed = downSpeed; setMaximumSpeed(xSpeedMax, ySpeedMax); setDeceleration(xDeceleration, yDeceleration); } /** * Set the speed at which the sprite will rotate when a direction key is pressed.
* Use this in combination with setMovementSpeed to create a Thrust like movement system.
* All values are given in pixels per second. So an xSpeed of 100 would rotate the sprite 100 pixels in 1 second (1000ms)
* Due to the nature of the internal Flash timer this amount is not 100% accurate and will vary above/below the desired distance by a few pixels.
*/ public function setRotationSpeed(antiClockwiseSpeed:Number, clockwiseSpeed:Number, speedMax:Number, deceleration:Number):void { antiClockwiseRotationSpeed = -antiClockwiseSpeed; clockwiseRotationSpeed = clockwiseSpeed; setRotationKeys(); setMaximumRotationSpeed(speedMax); setRotationDeceleration(deceleration); } /** * * * @param rotationType * @param stoppingType */ public function setRotationType(rotationType:int, stoppingType:int):void { rotation = rotationType; rotationStopping = stoppingType; } /** * Sets the maximum speed (in pixels per second) that the FlxSprite can rotate.
* When the FlxSprite is accelerating (movement type MOVEMENT_ACCELERATES) its speed won't increase above this value.
* However Flixel allows the velocity of an FlxSprite to be set to anything. So if you'd like to check the value and restrain it, then enable ""limitVelocity"". * * @param speed The maximum speed in pixels per second in which the sprite can rotate * @param limitVelocity If true the angular velocity of the FlxSprite will be checked and kept within the limit. If false it can be set to anything. */ public function setMaximumRotationSpeed(speed:Number, limitVelocity:Boolean = true):void { entity.maxAngular = speed; capAngularVelocity = limitVelocity; } /** * Deceleration is a speed (in pixels per second) that is applied to the sprite if stopping type is ""DECELERATES"" and if no rotation is taking place.
* The velocity of the sprite will be reduced until it reaches zero. * * @param speed The speed in pixels per second at which the sprite will have its angular rotation speed decreased */ public function setRotationDeceleration(speed:Number):void { entity.angularDrag = speed; } /** * Set minimum and maximum angle limits that the Sprite won't be able to rotate beyond.
* Values must be between -180 and +180. 0 is pointing right, 90 down, 180 left, -90 up. * * @param minimumAngle Minimum angle below which the sprite cannot rotate (must be -180 or above) * @param maximumAngle Maximum angle above which the sprite cannot rotate (must be 180 or below) */ public function setRotationLimits(minimumAngle:int, maximumAngle:int):void { if (minimumAngle > maximumAngle || minimumAngle < -180 || maximumAngle > 180) { throw new Error(""FlxControlHandler setRotationLimits: Invalid Minimum / Maximum angle""); } else { enforceAngleLimits = true; minAngle = minimumAngle; maxAngle = maximumAngle; } } /** * Disables rotation limits set in place by setRotationLimits() */ public function disableRotationLimits():void { enforceAngleLimits = false; } /** * Set which keys will rotate the sprite. The speed of rotation is set in setRotationSpeed. * * @param leftRight Use the LEFT and RIGHT arrow keys for anti-clockwise and clockwise rotation respectively. * @param upDown Use the UP and DOWN arrow keys for anti-clockwise and clockwise rotation respectively. * @param customAntiClockwise The String value of your own key to use for anti-clockwise rotation (as taken from org.flixel.system.input.Keyboard) * @param customClockwise The String value of your own key to use for clockwise rotation (as taken from org.flixel.system.input.Keyboard) */ public function setRotationKeys(leftRight:Boolean = true, upDown:Boolean = false, customAntiClockwise:String = """", customClockwise:String = """"):void { isRotating = true; rotateAntiClockwise = true; rotateClockwise = true; antiClockwiseKey = ""LEFT""; clockwiseKey = ""RIGHT""; if (upDown == true) { antiClockwiseKey = ""UP""; clockwiseKey = ""DOWN""; } if (customAntiClockwise != """" && customClockwise != """") { antiClockwiseKey = customAntiClockwise; clockwiseKey = customClockwise; } } /** * If you want to enable a Thrust like motion for your sprite use this to set the speed and keys.
* This is usually used in conjunction with Rotation and it will over-ride anything already defined in setMovementSpeed. * * @param thrustKey Specify the key String (as taken from org.flixel.system.input.Keyboard) to use for the Thrust action * @param thrustSpeed The speed in pixels per second which the sprite will move. Acceleration or Instant movement is determined by the Movement Type. * @param reverseKey If you want to be able to reverse, set the key string as taken from org.flixel.system.input.Keyboard (defaults to null). * @param reverseSpeed The speed in pixels per second which the sprite will reverse. Acceleration or Instant movement is determined by the Movement Type. */ public function setThrust(thrustKey:String, thrustSpeed:Number, reverseKey:String = null, reverseSpeed:Number = 0):void { thrustEnabled = false; reverseEnabled = false; if (thrustKey) { this.thrustKey = thrustKey; this.thrustSpeed = thrustSpeed; thrustEnabled = true; } if (reverseKey) { this.reverseKey = reverseKey; this.reverseSpeed = reverseSpeed; reverseEnabled = true; } } /** * Sets the maximum speed (in pixels per second) that the FlxSprite can move. You can set the horizontal and vertical speeds independantly.
* When the FlxSprite is accelerating (movement type MOVEMENT_ACCELERATES) its speed won't increase above this value.
* However Flixel allows the velocity of an FlxSprite to be set to anything. So if you'd like to check the value and restrain it, then enable ""limitVelocity"". * * @param xSpeed The maximum speed in pixels per second in which the sprite can move horizontally * @param ySpeed The maximum speed in pixels per second in which the sprite can move vertically * @param limitVelocity If true the velocity of the FlxSprite will be checked and kept within the limit. If false it can be set to anything. */ public function setMaximumSpeed(xSpeed:uint, ySpeed:uint, limitVelocity:Boolean = true):void { entity.maxVelocity.x = xSpeed; entity.maxVelocity.y = ySpeed; capVelocity = limitVelocity; } /** * Deceleration is a speed (in pixels per second) that is applied to the sprite if stopping type is ""DECELERATES"" and if no acceleration is taking place.
* The velocity of the sprite will be reduced until it reaches zero, and can be configured separately per axis. * * @param xSpeed The speed in pixels per second at which the sprite will have its horizontal speed decreased * @param ySpeed The speed in pixels per second at which the sprite will have its vertical speed decreased */ public function setDeceleration(xSpeed:uint, ySpeed:uint):void { entity.drag.x = xSpeed; entity.drag.y = ySpeed; } /** * Gravity can be applied to the sprite, pulling it in any direction.
* Gravity is given in pixels per second and is applied as acceleration. The speed the sprite reaches under gravity will never exceed the Maximum Movement Speeds set.
* If you don't want gravity for a specific direction pass a value of zero. * * @param xForce A positive value applies gravity dragging the sprite to the right. A negative value drags the sprite to the left. Zero disables horizontal gravity. * @param yForce A positive value applies gravity dragging the sprite down. A negative value drags the sprite up. Zero disables vertical gravity. */ public function setGravity(xForce:int, yForce:int):void { gravityX = xForce; gravityY = yForce; entity.acceleration.x = gravityX; entity.acceleration.y = gravityY; } /** * Switches the gravity applied to the sprite. If gravity was +400 Y (pulling them down) this will swap it to -400 Y (pulling them up)
* To reset call flipGravity again */ public function flipGravity():void { if (gravityX && gravityX != 0) { gravityX = -gravityX; entity.acceleration.x = gravityX; } if (gravityY && gravityY != 0) { gravityY = -gravityY; entity.acceleration.y = gravityY; } } /** * TODO * * @param xFactor * @param yFactor */ public function speedUp(xFactor:Number, yFactor:Number):void { } /** * TODO * * @param xFactor * @param yFactor */ public function slowDown(xFactor:Number, yFactor:Number):void { } /** * TODO * * @param xFactor * @param yFactor */ public function resetSpeeds(resetX:Boolean = true, resetY:Boolean = true):void { if (resetX) { xSpeedAdjust = 0; } if (resetY) { ySpeedAdjust = 0; } } /** * Creates a new Hot Key, which can be bound to any function you specify (such as ""swap weapon"", ""quit"", etc) * * @param key The key to use as the hot key (String from org.flixel.system.input.Keyboard, i.e. ""SPACE"", ""CONTROL"", ""Q"", etc) * @param callback The function to call when the key is pressed * @param keymode The keymode that will trigger the callback, either KEYMODE_PRESSED, KEYMODE_JUST_DOWN or KEYMODE_RELEASED */ public function addHotKey(key:String, callback:Function, keymode:int):void { } /** * Removes a previously defined hot key * * @param key The key to use as the hot key (String from org.flixel.system.input.Keyboard, i.e. ""SPACE"", ""CONTROL"", ""Q"", etc) * @return true if the key was found and removed, false if the key couldn't be found */ public function removeHotKey(key:String):Boolean { return true; } /** * Set sound effects for the movement events jumping, firing, walking and thrust. * * @param jump The FlxSound to play when the user jumps * @param fire The FlxSound to play when the user fires * @param walk The FlxSound to play when the user walks * @param thrust The FlxSound to play when the user thrusts */ public function setSounds(jump:FlxSound = null, fire:FlxSound = null, walk:FlxSound = null, thrust:FlxSound = null):void { if (jump) { jumpSound = jump; } if (fire) { fireSound = fire; } if (walk) { walkSound = walk; } if (thrust) { thrustSound = thrust; } } /** * Enable a fire button * * @param key The key to use as the fire button (String from org.flixel.system.input.Keyboard, i.e. ""SPACE"", ""CONTROL"") * @param keymode The FlxControlHandler KEYMODE value (KEYMODE_PRESSED, KEYMODE_JUST_DOWN, KEYMODE_RELEASED) * @param repeatDelay Time delay in ms between which the fire action can repeat (0 means instant, 250 would allow it to fire approx. 4 times per second) * @param callback A user defined function to call when it fires * @param altKey Specify an alternative fire key that works AS WELL AS the primary fire key (TODO) */ public function setFireButton(key:String, keymode:uint, repeatDelay:uint, callback:Function, altKey:String = """"):void { fireKey = key; fireKeyMode = keymode; fireRate = repeatDelay; fireCallback = callback; if (altKey != """") { altFireKey = altKey; } fire = true; } /** * Enable a jump button * * @param key The key to use as the jump button (String from org.flixel.system.input.Keyboard, i.e. ""SPACE"", ""CONTROL"") * @param keymode The FlxControlHandler KEYMODE value (KEYMODE_PRESSED, KEYMODE_JUST_DOWN, KEYMODE_RELEASED) * @param height The height in pixels/sec that the Sprite will attempt to jump (gravity and acceleration can influence this actual height obtained) * @param surface A bitwise combination of all valid surfaces the Sprite can jump off (from FlxObject, such as FlxObject.FLOOR) * @param repeatDelay Time delay in ms between which the jumping can repeat (250 would be 4 times per second) * @param jumpFromFall A time in ms that allows the Sprite to still jump even if it's just fallen off a platform, if still within ths time limit * @param callback A user defined function to call when the Sprite jumps * @param altKey Specify an alternative jump key that works AS WELL AS the primary jump key (TODO) */ public function setJumpButton(key:String, keymode:uint, height:int, surface:int, repeatDelay:uint = 250, jumpFromFall:int = 0, callback:Function = null, altKey:String = """"):void { jumpKey = key; jumpKeyMode = keymode; jumpHeight = height; jumpSurface = surface; jumpRate = repeatDelay; jumpFromFallTime = jumpFromFall; jumpCallback = callback; if (altKey != """") { altJumpKey = altKey; } jump = true; } /** * Limits the sprite to only be allowed within this rectangle. If its x/y coordinates go outside it will be repositioned back inside.
* Coordinates should be given in GAME WORLD pixel values (not screen value, although often they are the two same things) * * @param x The x coordinate of the top left corner of the area (in game world pixels) * @param y The y coordinate of the top left corner of the area (in game world pixels) * @param width The width of the area (in pixels) * @param height The height of the area (in pixels) */ public function setBounds(x:int, y:int, width:uint, height:uint):void { bounds = new Rectangle(x, y, width, height); } /** * Clears any previously set sprite bounds */ public function removeBounds():void { bounds = null; } private function moveUp():Boolean { var move:Boolean = false; if (FlxG.keys.pressed(upKey)) { move = true; isPressedUp = true; if (yFacing) { entity.facing = FlxObject.UP; } if (movement == MOVEMENT_INSTANT) { entity.velocity.y = upMoveSpeed; } else if (movement == MOVEMENT_ACCELERATES) { entity.acceleration.y = upMoveSpeed; } if (bounds && entity.y < bounds.top) { entity.y = bounds.top; } } return move; } private function moveDown():Boolean { var move:Boolean = false; if (FlxG.keys.pressed(downKey)) { move = true; isPressedDown = true; if (yFacing) { entity.facing = FlxObject.DOWN; } if (movement == MOVEMENT_INSTANT) { entity.velocity.y = downMoveSpeed; } else if (movement == MOVEMENT_ACCELERATES) { entity.acceleration.y = downMoveSpeed; } if (bounds && entity.y > bounds.bottom) { entity.y = bounds.bottom; } } return move; } private function moveLeft():Boolean { var move:Boolean = false; if (FlxG.keys.pressed(leftKey)) { move = true; isPressedLeft = true; if (xFacing) { entity.facing = FlxObject.LEFT; } if (movement == MOVEMENT_INSTANT) { entity.velocity.x = leftMoveSpeed; } else if (movement == MOVEMENT_ACCELERATES) { entity.acceleration.x = leftMoveSpeed; } if (bounds && entity.x < bounds.x) { entity.x = bounds.x; } } return move; } private function moveRight():Boolean { var move:Boolean = false; if (FlxG.keys.pressed(rightKey)) { move = true; isPressedRight = true; if (xFacing) { entity.facing = FlxObject.RIGHT; } if (movement == MOVEMENT_INSTANT) { entity.velocity.x = rightMoveSpeed; } else if (movement == MOVEMENT_ACCELERATES) { entity.acceleration.x = rightMoveSpeed; } if (bounds && entity.x > bounds.right) { entity.x = bounds.right; } } return move; } private function moveAntiClockwise():Boolean { var move:Boolean = false; if (FlxG.keys.pressed(antiClockwiseKey)) { move = true; if (rotation == ROTATION_INSTANT) { entity.angularVelocity = antiClockwiseRotationSpeed; } else if (rotation == ROTATION_ACCELERATES) { entity.angularAcceleration = antiClockwiseRotationSpeed; } // TODO - Not quite there yet given the way Flixel can rotate to any valid int angle! if (enforceAngleLimits) { //entity.angle = FlxMath.angleLimit(entity.angle, minAngle, maxAngle); } } return move; } private function moveClockwise():Boolean { var move:Boolean = false; if (FlxG.keys.pressed(clockwiseKey)) { move = true; if (rotation == ROTATION_INSTANT) { entity.angularVelocity = clockwiseRotationSpeed; } else if (rotation == ROTATION_ACCELERATES) { entity.angularAcceleration = clockwiseRotationSpeed; } // TODO - Not quite there yet given the way Flixel can rotate to any valid int angle! if (enforceAngleLimits) { //entity.angle = FlxMath.angleLimit(entity.angle, minAngle, maxAngle); } } return move; } private function moveThrust():Boolean { var move:Boolean = false; if (FlxG.keys.pressed(thrustKey)) { move = true; var motion:FlxPoint = FlxVelocity.velocityFromAngle(entity.angle, thrustSpeed); if (movement == MOVEMENT_INSTANT) { entity.velocity.x = motion.x; entity.velocity.y = motion.y; } else if (movement == MOVEMENT_ACCELERATES) { entity.acceleration.x = motion.x; entity.acceleration.y = motion.y; } if (bounds && entity.x < bounds.x) { entity.x = bounds.x; } } if (move && thrustSound) { thrustSound.play(false); } return move; } private function moveReverse():Boolean { var move:Boolean = false; if (FlxG.keys.pressed(reverseKey)) { move = true; var motion:FlxPoint = FlxVelocity.velocityFromAngle(entity.angle, reverseSpeed); if (movement == MOVEMENT_INSTANT) { entity.velocity.x = -motion.x; entity.velocity.y = -motion.y; } else if (movement == MOVEMENT_ACCELERATES) { entity.acceleration.x = -motion.x; entity.acceleration.y = -motion.y; } if (bounds && entity.x < bounds.x) { entity.x = bounds.x; } } return move; } private function runFire():Boolean { var fired:Boolean = false; // 0 = Pressed // 1 = Just Down // 2 = Just Released if ((fireKeyMode == 0 && FlxG.keys.pressed(fireKey)) || (fireKeyMode == 1 && FlxG.keys.justPressed(fireKey)) || (fireKeyMode == 2 && FlxG.keys.justReleased(fireKey))) { if (fireRate > 0) { if (getTimer() > nextFireTime) { lastFiredTime = getTimer(); fireCallback.call(); fired = true; nextFireTime = lastFiredTime + fireRate; } } else { lastFiredTime = getTimer(); fireCallback.call(); fired = true; } } if (fired && fireSound) { fireSound.play(true); } return fired; } private function runJump():Boolean { var jumped:Boolean = false; // This should be called regardless if they've pressed jump or not if (entity.isTouching(jumpSurface)) { extraSurfaceTime = getTimer() + jumpFromFallTime; } if ((jumpKeyMode == KEYMODE_PRESSED && FlxG.keys.pressed(jumpKey)) || (jumpKeyMode == KEYMODE_JUST_DOWN && FlxG.keys.justPressed(jumpKey)) || (jumpKeyMode == KEYMODE_RELEASED && FlxG.keys.justReleased(jumpKey))) { // Sprite not touching a valid jump surface if (entity.isTouching(jumpSurface) == false) { // They've run out of time to jump if (getTimer() > extraSurfaceTime) { return jumped; } else { // Still within the fall-jump window of time, but have jumped recently if (lastJumpTime > (extraSurfaceTime - jumpFromFallTime)) { return jumped; } } // If there is a jump repeat rate set and we're still less than it then return if (getTimer() < nextJumpTime) { return jumped; } } else { // If there is a jump repeat rate set and we're still less than it then return if (getTimer() < nextJumpTime) { return jumped; } } if (gravityY > 0) { // Gravity is pulling them down to earth, so they are jumping up (negative) entity.velocity.y = -jumpHeight; } else { // Gravity is pulling them up, so they are jumping down (positive) entity.velocity.y = jumpHeight; } if (jumpCallback is Function) { jumpCallback.call(); } lastJumpTime = getTimer(); nextJumpTime = lastJumpTime + jumpRate; jumped = true; } if (jumped && jumpSound) { jumpSound.play(true); } return jumped; } /** * Called by the FlxControl plugin */ public function update():void { if (entity == null) { return; } // Reset the helper booleans isPressedUp = false; isPressedDown = false; isPressedLeft = false; isPressedRight = false; if (stopping == STOPPING_INSTANT) { if (movement == MOVEMENT_INSTANT) { entity.velocity.x = 0; entity.velocity.y = 0; } else if (movement == MOVEMENT_ACCELERATES) { entity.acceleration.x = 0; entity.acceleration.y = 0; } } else if (stopping == STOPPING_DECELERATES) { if (movement == MOVEMENT_INSTANT) { entity.velocity.x = 0; entity.velocity.y = 0; } else if (movement == MOVEMENT_ACCELERATES) { // By default these are zero anyway, so it's safe to set like this entity.acceleration.x = gravityX; entity.acceleration.y = gravityY; } } // Rotation if (isRotating) { if (rotationStopping == ROTATION_STOPPING_INSTANT) { if (rotation == ROTATION_INSTANT) { entity.angularVelocity = 0; } else if (rotation == ROTATION_ACCELERATES) { entity.angularAcceleration = 0; } } else if (rotationStopping == ROTATION_STOPPING_DECELERATES) { if (rotation == ROTATION_INSTANT) { entity.angularVelocity = 0; } } var hasRotatedAntiClockwise:Boolean = false; var hasRotatedClockwise:Boolean = false; hasRotatedAntiClockwise = moveAntiClockwise(); if (hasRotatedAntiClockwise == false) { hasRotatedClockwise = moveClockwise(); } if (rotationStopping == ROTATION_STOPPING_DECELERATES) { if (rotation == ROTATION_ACCELERATES && hasRotatedAntiClockwise == false && hasRotatedClockwise == false) { entity.angularAcceleration = 0; } } // If they have got instant stopping with acceleration and are NOT pressing a key, then stop the rotation. Otherwise we let it carry on if (rotationStopping == ROTATION_STOPPING_INSTANT && rotation == ROTATION_ACCELERATES && hasRotatedAntiClockwise == false && hasRotatedClockwise == false) { entity.angularVelocity = 0; entity.angularAcceleration = 0; } } // Thrust if (thrustEnabled || reverseEnabled) { var moved:Boolean = false; if (thrustEnabled) { moved = moveThrust(); } if (moved == false && reverseEnabled) { moved = moveReverse(); } } else { var movedX:Boolean = false; var movedY:Boolean = false; if (up) { movedY = moveUp(); } if (down && movedY == false) { movedY = moveDown(); } if (left) { movedX = moveLeft(); } if (right && movedX == false) { movedX = moveRight(); } } if (fire) { runFire(); } if (jump) { runJump(); } if (capVelocity) { if (entity.velocity.x > entity.maxVelocity.x) { entity.velocity.x = entity.maxVelocity.x; } if (entity.velocity.y > entity.maxVelocity.y) { entity.velocity.y = entity.maxVelocity.y; } } if (walkSound) { if ((movement == MOVEMENT_INSTANT && entity.velocity.x != 0) || (movement == MOVEMENT_ACCELERATES && entity.acceleration.x != 0)) { walkSound.play(false); } else { walkSound.stop(); } } } /** * Sets Custom Key controls. Useful if none of the pre-defined sets work. All String values should be taken from org.flixel.system.input.Keyboard * Pass a blank (empty) String to disable that key from being checked. * * @param customUpKey The String to use for the Up key. * @param customDownKey The String to use for the Down key. * @param customLeftKey The String to use for the Left key. * @param customRightKey The String to use for the Right key. */ public function setCustomKeys(customUpKey:String, customDownKey:String, customLeftKey:String, customRightKey:String):void { if (customUpKey != """") { up = true; upKey = customUpKey; } if (customDownKey != """") { down = true; downKey = customDownKey; } if (customLeftKey != """") { left = true; leftKey = customLeftKey; } if (customRightKey != """") { right = true; rightKey = customRightKey; } } /** * Enables Cursor/Arrow Key controls. Can be set on a per-key basis. Useful if you only want to allow a few keys.
* For example in a Space Invaders game you'd only enable LEFT and RIGHT. * * @param allowUp Enable the UP key * @param allowDown Enable the DOWN key * @param allowLeft Enable the LEFT key * @param allowRight Enable the RIGHT key */ public function setCursorControl(allowUp:Boolean = true, allowDown:Boolean = true, allowLeft:Boolean = true, allowRight:Boolean = true):void { up = allowUp; down = allowDown; left = allowLeft; right = allowRight; upKey = ""UP""; downKey = ""DOWN""; leftKey = ""LEFT""; rightKey = ""RIGHT""; } /** * Enables WASD controls. Can be set on a per-key basis. Useful if you only want to allow a few keys.
* For example in a Space Invaders game you'd only enable LEFT and RIGHT. * * @param allowUp Enable the up (W) key * @param allowDown Enable the down (S) key * @param allowLeft Enable the left (A) key * @param allowRight Enable the right (D) key */ public function setWASDControl(allowUp:Boolean = true, allowDown:Boolean = true, allowLeft:Boolean = true, allowRight:Boolean = true):void { up = allowUp; down = allowDown; left = allowLeft; right = allowRight; upKey = ""W""; downKey = ""S""; leftKey = ""A""; rightKey = ""D""; } /** * Enables ESDF (home row) controls. Can be set on a per-key basis. Useful if you only want to allow a few keys.
* For example in a Space Invaders game you'd only enable LEFT and RIGHT. * * @param allowUp Enable the up (E) key * @param allowDown Enable the down (D) key * @param allowLeft Enable the left (S) key * @param allowRight Enable the right (F) key */ public function setESDFControl(allowUp:Boolean = true, allowDown:Boolean = true, allowLeft:Boolean = true, allowRight:Boolean = true):void { up = allowUp; down = allowDown; left = allowLeft; right = allowRight; upKey = ""E""; downKey = ""D""; leftKey = ""S""; rightKey = ""F""; } /** * Enables IJKL (right-sided or secondary player) controls. Can be set on a per-key basis. Useful if you only want to allow a few keys.
* For example in a Space Invaders game you'd only enable LEFT and RIGHT. * * @param allowUp Enable the up (I) key * @param allowDown Enable the down (K) key * @param allowLeft Enable the left (J) key * @param allowRight Enable the right (L) key */ public function setIJKLControl(allowUp:Boolean = true, allowDown:Boolean = true, allowLeft:Boolean = true, allowRight:Boolean = true):void { up = allowUp; down = allowDown; left = allowLeft; right = allowRight; upKey = ""I""; downKey = ""K""; leftKey = ""J""; rightKey = ""L""; } /** * Enables HJKL (Rogue / Net-Hack) controls. Can be set on a per-key basis. Useful if you only want to allow a few keys.
* For example in a Space Invaders game you'd only enable LEFT and RIGHT. * * @param allowUp Enable the up (K) key * @param allowDown Enable the down (J) key * @param allowLeft Enable the left (H) key * @param allowRight Enable the right (L) key */ public function setHJKLControl(allowUp:Boolean = true, allowDown:Boolean = true, allowLeft:Boolean = true, allowRight:Boolean = true):void { up = allowUp; down = allowDown; left = allowLeft; right = allowRight; upKey = ""K""; downKey = ""J""; leftKey = ""H""; rightKey = ""L""; } /** * Enables ZQSD (Azerty keyboard) controls. Can be set on a per-key basis. Useful if you only want to allow a few keys.
* For example in a Space Invaders game you'd only enable LEFT and RIGHT. * * @param allowUp Enable the up (Z) key * @param allowDown Enable the down (Q) key * @param allowLeft Enable the left (S) key * @param allowRight Enable the right (D) key */ public function setZQSDControl(allowUp:Boolean = true, allowDown:Boolean = true, allowLeft:Boolean = true, allowRight:Boolean = true):void { up = allowUp; down = allowDown; left = allowLeft; right = allowRight; upKey = ""Z""; downKey = ""S""; leftKey = ""Q""; rightKey = ""D""; } /** * Enables Dvoark Simplified Controls. Can be set on a per-key basis. Useful if you only want to allow a few keys.
* For example in a Space Invaders game you'd only enable LEFT and RIGHT. * * @param allowUp Enable the up (COMMA) key * @param allowDown Enable the down (A) key * @param allowLeft Enable the left (O) key * @param allowRight Enable the right (E) key */ public function setDvorakSimplifiedControl(allowUp:Boolean = true, allowDown:Boolean = true, allowLeft:Boolean = true, allowRight:Boolean = true):void { up = allowUp; down = allowDown; left = allowLeft; right = allowRight; upKey = ""COMMA""; downKey = ""O""; leftKey = ""A""; rightKey = ""E""; } /** * Enables Numpad (left-handed) Controls. Can be set on a per-key basis. Useful if you only want to allow a few keys.
* For example in a Space Invaders game you'd only enable LEFT and RIGHT. * * @param allowUp Enable the up (NUMPADEIGHT) key * @param allowDown Enable the down (NUMPADTWO) key * @param allowLeft Enable the left (NUMPADFOUR) key * @param allowRight Enable the right (NUMPADSIX) key */ public function setNumpadControl(allowUp:Boolean = true, allowDown:Boolean = true, allowLeft:Boolean = true, allowRight:Boolean = true):void { up = allowUp; down = allowDown; left = allowLeft; right = allowRight; upKey = ""NUMPADEIGHT""; downKey = ""NUMPADTWO""; leftKey = ""NUMPADFOUR""; rightKey = ""NUMPADSIX""; } } }",12191,False,2434.4831318365605,median "/******************************************************* GraiNMaster système de contrôle de température de la cuve Débuté le 24/11/2015 par Nicolas Morival Testé et compilé sur Arduino IDE v1.6.8 *******************************************************/ #define version "" --V1.005-- "" /* v1.000 le 14/05/2016 V1.002 le 08/10/2016 nettoyage du code, suppression des morceaux de code inutiles (relatifs à la SD) suppression du paramètre sur SD detect : cette broche est une interruption fixée par le hardware ajout de la possibilité d'utiliser une sonde DS18B20 v1.003 le 09/11/2017 correction de bugs sur l'initialisation de l'eeprom (bug relevé par artiche) mise en fonction du buzzer (suggestion artiche) v1.004 le 15/04/2019 - DaOurZ Ajout de la possibilité de deux sondes de température ""Simplification"" du code Désactivation possible de l'EEPROM, mode Debug, du buzzer, du défilement Changement de la température et du temps restant à la volée pour chaque palier en cours Sortie propre du programme en fin de brassage Création d'un fichier de log différent à chaque brassage Redéfinition des informations affichées à l'écran (avec témoin d'atteinte du palier) */ //bibliothèques #include #include #include //gestion de l'algo PID #include #include ""Timer.h"" // gestion des timers #include //gestion du LCD #include #include //gestion des interruptions #define DEBUG // Décommenter pour afficher les informations de deboguage (PID sur le LCD) //#define ADS1015 // Décommenter pour utilisation du DAC (Version Originale) //#define DS18B20 // DS18B20 #define MAX31865 //#define BIPPEUR // Commenter pour ne pas utiliser de buzzer //#define EEPROMRW // Décommenter pour enregistrement sur l'EEPROM si pas de carte SD #define DEFIL // Commenter pour ne pas faire alterner le texte sur la deuxième ligne pour afficher le temps restant total avant la fin de l'ébullition #define PIDDEBUG // Commenter pour enlever l'information du PID sur l'écran lors de la chauffe #ifdef PIDDEBUG #define PID_DEBUG(x) + String(x) #else #define PID_DEBUG(x) #endif #ifdef DEBUG #define DEBUGPRINTLN(x) Serial.println(x) #else #define DEBUGPRINTLN(x) #endif #ifdef EEPROMRW #include #include // gestion des enregistrements en EEPROM #endif #define BLINK() ledState = !ledState; digitalWrite(ledPin, ledState); #ifdef DEFIL bool defilement = 0; // Position du défilement / 1 = température et température à atteindre / 0 = température et temps restant / s'échange à chaque écriture sur la carte SD, donc toutes les 10 s environ #endif byte DETECT = 2 , GATE = 3; //Broches utilisées pour le pilotage du triac -> detect : impulsion du passage au point zéro, gate : gachette du triac byte PULSE = 4 ; //triac gate pulse : largeur de l'impulsion pour activer le triac, en nombre de cycles d'horloge int HALF_WAVE = 560;// //nombre de ""tics"" d'horloge à chaque demi onde 50Hz . 625 théoriques, mais 560 réels . #if defined(DS18B20) // Déclaration de la sonde de température DS18B20 si l'on n'utilise pas de DAC #include #include #include byte ONE_WIRE_BUS = 30; // DS18B20 pin OneWire oneWire(ONE_WIRE_BUS); DallasTemperature DS18(&oneWire); #endif #if defined(MAX31865) #include // Use software SPI: CS, DI, DO, CLK Adafruit_MAX31865 thermo = Adafruit_MAX31865(42, 40, 38, 36); // use hardware SPI, just pass in the CS pin //Adafruit_MAX31865 thermo = Adafruit_MAX31865(10); // The value of the Rref resistor. Use 430.0 for PT100 and 4300.0 for PT1000 #define RREF 430.0 // The 'nominal' 0-degrees-C resistance of the sensor // 100.0 for PT100, 1000.0 for PT1000 #define RNOMINAL 100.0 #endif // constantes pour les touches reliées au module LCD #define btnRIGHT 0 #define btnUP 1 #define btnDOWN 2 #define btnLEFT 3 #define btnSELECT 4 #define btnNONE 5 #if defined(ADS1015) #include // gestion du CAN 16 bits // pour la lecture de la sonde via le DAC (Version Originale) byte THERM_PIN2 = 1 ;// entrée n°1 du dac 16bits byte THERM_PIN = 3 ; // entrée n°3 du dac 16bits //on lit sur deux entrées dont les filtres passe bas sont légèrement différents, afin de faire une moyenne et augmenter la précision int OFFSET_PROBE = 138; // correction constante de la température int COEF_PROBE = 260 ; // correction proportionelle // Température calculée = (mesure du DAC - OFFSET_PROBE) / COEF_PROBE // déclaration de l'ADC 16 bits - DAC pour température (Version Originale) Adafruit_ADS1115 ads1115(0x48); // ADC16 bits addresse 0x48 /* String variables_SD_DAC[] = { ""THERMPIN2"", ""THERMPIN1"", ""OFSETPRBE"", ""COEFPROBE"" }; */ #endif //valeurs de l'hysteresis pour passage en PID fin ou grossier byte hysteresis_Pos = 1; byte hysteresis_Neg = 1; // pins utilisées par le LCD LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // valeurs utilisées pour configurer le LCD byte backLight = 10; // LCD Panel Backlight LED connected to digital pin 10 int lcd_key = 0; int adc_key_in = 0; byte ledPin = 13; byte ledState = LOW; // variables du programme volatile unsigned int menu = 0; byte submenu = 0; byte startprog = 0; //marqueur pour indiquer que le programme s'éxécute byte jump = 0; //pour indiquer qu'on va sauter un menu byte annuler = 0; //pour annuler les opérations 0 = fonctionnement normal / -1 on recule d'une étape / 1 on avance d'une étape byte secondes = 0; unsigned long secondes_reel = 0; //temps écoulé depuis le début du programme, utilisé pour le data log unsigned int minutes = 0; //minutes écoulées unsigned long total_time = 0; //cumul des temps programme unsigned long temps_pause = 0; //si le programme est en pause, compte le temps écoulé bool palier_atteint = false; int logRecord_ID; // Timer ID pour la fonction logRecord, pour un arrêt propre du programme (on veut le stopper avant d'arrêter le programme pour éviter toute écriture quand on ddébranche l'Arduino) String myPaliers[2][7] = { {""Prechauffe"", ""Palier 1 "", ""Palier 2 "", ""Palier 3 "", ""Palier 4 "", ""Mash-out "", ""Ebullition""}, // Nom des paliers en version longue (10 caractères) {""PREC"", ""PAL1"", ""PAL2"", ""PAL3"", ""PAL4"", ""MOUT"", ""EBUL"" } // Nom des paliers en version courte (4 caractères) }; float myTemperatures[] = { 40, // = thetastart, température de préchauffe de la cuve 40.25, // = theta1, température empâtage céréales non maltées 52.5, // = theta2, température protéines 62.0, // = theta3, température de sacharification B amylase 68.75, // = theta4, température de sacharification A amylase 75.75, // = thetaMO, température de mash out 103.0 // = theta5, température d'ébullition }; // Températures pour chaque myPaliers byte myTempo[] { 0, // tempo_A, pour l'affichage temporaire 0, // tempo1, palier empâtage céréales non maltées 15, // tempo2, palier protéinique 35, // tempo3, palier de sacharification B amylase 30, // tempo4, palier de sacharification A amylase 5, // palier de Mash Out 70 // tempo5, ébullition }; // Temporisation pour chaque myPaliers unsigned int cooling = 0; // compteur du temps de refroidissement float last_temp = 0; // dernière température positive //int therm; //variable pour le relevé de température // double chauffe_reel = 0, tx_chauffe, theta_mesure, theta_PID, theta_objectif = 20; float tx_chauffe; float theta_PID, theta_mesure, theta_objectif = 20; // Règlages par défaut du PID // Ces constantes sont correctes pour une cuve de 27L 2500W non isolée type kitchen chef byte P_strong = 100; float I_strong = 0.0; byte D_strong = 16; byte P_weak = 80; float I_weak = 0.02; byte D_weak = 8; double Kp = P_strong; // multiplicateur de l'erreur différentielle de température. double Ki = I_strong; //coef de correction inverse double Kd = D_strong; //coef de dérivée byte PID_OFFSET = 1; // on ruse le PID pour lui faire décaller la température cible d'une valeur constante par exemple +1° donc si l'utilisateur vise 62° et que la température mesurée est de 61° le PID croit qu'il a atteint les 62° et coupe la chauffe. Ainsi l'overshoot est limité. // en théorie, avec les paramètres réglés au top, ce paramètre peut être remis à zéro. PID myPID((double*)&theta_PID, (double*)&tx_chauffe, (double*)&theta_objectif, Kp, Ki, Kd, DIRECT); //déclaration du PID #ifdef BIPPEUR //pin du bipeur byte Beep_PIN = 40; // variables utilisées pour faire marcher le bippeur #define BeepONState LOW #define BeepOFFState HIGH #define BeepON(s) BeepON(s) byte beep_duration = 0; // temps du bip : s / 128, 128 ms étant le temps entre chaque appel de sel_menu, la plus rapide des périodes pour vérifier que le bip est en route ou non void BeepON(unsigned int s) { digitalWrite(Beep_PIN, BeepONState); beep_duration = (byte) ceil(s / 128); // la durée du bip est comptée par période de 128 ms (arrondies à l'entier supérieur) - sel_menu, qui va vérifier si le bip est en route ou non, est appelée toutes les 128 ms } void BeepOFF() { digitalWrite(Beep_PIN, BeepOFFState); } #else #define BeepON(s) #endif //réglages des timers Timer T; //déclaratioon du fichier pour la SD File myFile; String datalogFile; // Fichier de log, à chaque brassage différent int check_data = 0; char degre = (char)223; // char 223 = ° (signe degré) void setup() { #if defined(DEBUG) Serial.begin(9600); DEBUGPRINTLN (""Startup ok\\n""); #endif #if defined(ADS1015) // démarrage du DAC 16 bits ads1115.begin(); // (Version Originale) #endif #if defined(MAX31865) DEBUGPRINTLN(""Adafruit MAX31865 PT100 Sensor Test!""); thermo.begin(MAX31865_2WIRE); // set to 3WIRE or 4WIRE as necessary #endif //config pour SD String inString = """"; pinMode(53, OUTPUT); //la pin 53 est normalement attribuée à la fonction SPI Slave Select (SS)Permet d'activer ou désactiver le périphérique // Suivant les modules SD, il peut être nécessaire de commenter cette ligne (c'est le cas de mon module même si c'est pas logique) // ECRAN DE PRESENTATION ---------------------------- lcd.begin(16, 2); // déclaration de la bibliothèque LCD avec 16 caractères, 2 lignes // création des caractères spéciaux byte beer1[8] = { B10001, B11111, B10001, B10001, B10001, B10001, B11111, }; byte beer2[8] = { B00000, B11100, B00100, B00100, B00100, B00100, B11000, }; lcd.createChar(0, beer1); lcd.createChar(1, beer2); CLS(); // fonction qui efface le LCD et met le curseur au début lcd.print(""- GraiN.Master -""); lcd.setCursor(0, 1); lcd.write(byte(0)); lcd.write(byte(1)); lcd.print(version); lcd.write(byte(0)); lcd.write(byte(1)); delay(2000); // set up des pins pinMode(DETECT, INPUT); //détection du passage au pont zéro / zero cross detect digitalWrite(DETECT, HIGH); // enable pull-up resistor pinMode(GATE, OUTPUT); //triac gate control #if (defined(BIPPEUR)) pinMode(Beep_PIN, OUTPUT); // Déclaration du bipper BeepOFF(); #endif pinMode(backLight, INPUT); //set backlight pin to input to avoid MCU overcurent on pin 10 // pinMode(11, OUTPUT); // pin11 = MOSI sur uno pinMode(ledPin, OUTPUT); // set up Timer1 //(see ATMEGA 328 data sheet pg 134 for more details) OCR1A = 25; //initialize the comparator TIMSK1 = 0x03; //enable comparator A and overflow interrupts TCCR1A = 0x00; //timer control registers set for TCCR1B = 0x00; //normal operation, timer disabled myPID.SetOutputLimits(0, 255); #if (defined(EEPROMRW)) EEPROM.setMaxAllowedWrites(48); #endif // pinMode(10, OUTPUT); CLS(); // move cursor to beginning of line ""0"" lcd.print(""initialise SD ""); // print a simple message delay(600); if (!SD.begin(4)) { lcd.home(); // move cursor to beginning of line ""0"" lcd.print(""ERREUR SD CARD ""); // print a simple message delay(6000); } CLS(); // move cursor to beginning of line ""0"" lcd.print("" Lecture param ""); // print a simple message if (SD.exists(""setup.grm"")) { lcd.setCursor(0, 1); lcd.print("" sur carte SD ""); delay(1500); myFile = SD.open(""setup.grm""); while (myFile.available()) { int inChar = myFile.read(); if ((inChar != ',')) { inString += (char)inChar; } //fin if alphanum else { //on a récupéré la première ligne sous forme ""variable=000.00"" // Serial.print(""Input string: \\n""); // Serial.print(inString); if (inString.startsWith(""THERMPIN2"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 #if defined(ADS1015) THERM_PIN2 = inString.toInt(); #endif check_data++; } if (inString.startsWith(""THERMPIN1"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 #if defined(ADS1015) THERM_PIN = inString.toInt(); #endif check_data++; } if (inString.startsWith(""OFSETPRBE"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 #if defined(ADS1015) OFFSET_PROBE = inString.toInt(); #endif check_data++; } if (inString.startsWith(""COEFPROBE"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 #if defined(ADS1015) COEF_PROBE = inString.toInt(); #endif check_data++; } if (inString.startsWith(""hysterPos"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 hysteresis_Pos = inString.toInt(); check_data++; } if (inString.startsWith(""hysterNeg"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 hysteresis_Neg = inString.toInt(); check_data++; } for (int i = 0; i < 7; i++) { if (inString.startsWith(myPaliers[0][i])) { // Température (de préchauffage ou de palier) DEBUGPRINTLN(""Reading "" + myPaliers[0][i] + "" temperature:""); inString.remove(0, 10); // Remove 10 characters starting at index=0 DEBUGPRINTLN(inString.toFloat()); myTemperatures[i] = inString.toFloat(); check_data++; } if (inString.startsWith(myPaliers[1][i] + ""TEMPO"")) { // Temporisation pour chaque palier DEBUGPRINTLN(""Reading "" + myPaliers[0][i] + "" timing:""); inString.remove(0, 10); // Remove 10 characters starting at index=0 DEBUGPRINTLN(inString.toInt()); myTempo[i] = inString.toInt(); check_data++; } } if (inString.startsWith(""Pstrong00"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 P_strong = inString.toFloat(); check_data++; } if (inString.startsWith(""Istrong00"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 I_strong = inString.toFloat(); check_data++; } if (inString.startsWith(""Dstrong00"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 D_strong = inString.toFloat(); check_data++; } if (inString.startsWith(""Pweak0000"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 P_weak = inString.toFloat(); check_data++; } if (inString.startsWith(""Iweak0000"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 I_weak = inString.toFloat(); check_data++; } if (inString.startsWith(""Dweak0000"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 D_weak = inString.toFloat(); check_data++; } if (inString.startsWith(""LEDPIN000"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 ledPin = inString.toInt(); check_data++; } if (inString.startsWith(""GATE00000"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 GATE = inString.toInt(); check_data++; } if (inString.startsWith(""PULSE0000"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 PULSE = inString.toInt(); check_data++; } if (inString.startsWith(""HALFWAVE0"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 HALF_WAVE = inString.toInt(); check_data++; } if (inString.startsWith(""BEEPPIN00"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 #if (defined(BIPPEUR)) Beep_PIN = inString.toInt(); #endif check_data++; } if (inString.startsWith(""PIDOFFSET"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 PID_OFFSET = inString.toInt(); check_data++; } if (inString.startsWith(""ONEWIRE00"")) { inString.remove(0, 10); // Remove 10 characters starting at index=0 #if defined(DS18B20) ONE_WIRE_BUS = inString.toInt(); #endif check_data++; } inString = """"; } //fin else } //fin while CLS(); lcd.print(check_data); lcd.setCursor(0, 1); lcd.print(""parametres lus ""); myFile.close(); delay(1500); } else { // Pas possible de lire sur la carte SD --> on lit sur l'EEPROM si c'est défini... #if (defined(EEPROMRW)) lcd.setCursor(0, 1); lcd.print("" sur EEPROM ""); delay(1500); myTempo[1] = EEPROM.readLong(0); myTempo[2] = EEPROM.readLong(7); myTempo[3] = EEPROM.readLong(15); myTempo[4] = EEPROM.readLong(23); myTempo[6] = EEPROM.readLong(31); myTemperatures[1] = EEPROM.readFloat(39); myTemperatures[2] = EEPROM.readFloat(47); myTemperatures[3] = EEPROM.readFloat(55); myTemperatures[4] = EEPROM.readFloat(63); myTemperatures[6] = EEPROM.readFloat(71); myTemperatures[5] = EEPROM.readFloat(79); myTemperatures[0] = EEPROM.readFloat(87); #else // sinon on reste sur les valeurs par défaut définies en dur dans le programme lcd.setCursor(0, 1); lcd.print("" par defaut ""); delay(1500); #endif } datalogFile = ""log"" + String(random(0, 99999)) + "".txt""; // Le nom du fichier, avec un numéro pseudo-aléatoire pour éviter de réécrire sur le même à chaque brassin DEBUGPRINTLN(""Datalogfile = "" + datalogFile); digitalWrite(ledPin, 1); File dataFile = SD.open(datalogFile, FILE_WRITE); if (dataFile) { dataFile.print(""Temps (secondes)""); dataFile.print("";""); dataFile.print(""Palier en cours""); dataFile.print("";""); dataFile.print(""Objectif de temperature (°C)""); dataFile.print("";""); dataFile.print(""Temperature mesuree (°C)""); dataFile.print("";""); dataFile.print(""PID - taux de chauffe (0-255)""); dataFile.print('\\n'); dataFile.close(); } digitalWrite(ledPin, 0); T.every(2205, lecture); // constante de temps pour le timer 1 - lecture de la sonde T.every(128, sel_menu); // constante de temps pour le timer 2 - lecture des touches T.every(1024, LCD_upd); // timer 3 - mise à jour écran T.every(1000, horloge); // timer 4 - compte les secondes et minutes T.every(350, regle_chauffe); //timer 5 - fréquence de mise à jour de la chauffe logRecord_ID = T.every(10002, logRecord); //enregiste sur la carte SD OCR1A = 500; CLS(); LCD_upd(); // set up zero crossing interrupt attachInterrupt(digitalPinToInterrupt(2), zeroCrossingInterrupt, CHANGE); //IRQ0 is pin 2. Call zeroCrossingInterrupt //on rising signal menu = 0; } //Boucle principale ======================================== void loop() { T.update(); //gestion des sauts d'étapes manuels if (annuler == -1) { menu--; //on était au menu X on retourne au X-1 annuler = 0; logRecord(); } else { if (annuler == 1) { menu++; jump = 0; //par sécurité on ne veut pas de double saut au cas où le passage au palier suivant était prévu au même moment annuler = 0; logRecord(); palier_atteint = false; // le palier n'est pas encore atteint, il vient de commencer } } //gestion des sauts d'étapes automatiques if (jump == 1) { menu++; jump = 0; logRecord(); BeepON(1500); palier_atteint = false; // le palier n'est pas encore atteint, il vient de commencer } } //fin Boucle principale =================================== // Sélection de la température et du temps du palier void paliers_temp(int numpalier, String *line1, String *line2) { *line1 = myPaliers[0][numpalier] + "" ?""; if (submenu == 0) { *line2 = "">T:"" + String(myTemperatures[numpalier]) + degre + "" "" + String(myTempo[numpalier]) + "" min""; } else { *line2 = "" T:"" + String(myTemperatures[numpalier]) + degre + "" >"" + String(myTempo[numpalier]) + "" min""; } } // Sauter le palier en cours void pass_palier(int numpalier, String *line1, String *line2) { *line1 = ""SAUTER "" + myPaliers[0][numpalier] + "" ?""; *line2 = ""SEL=OUI autre=NO""; } // Annuler le palier en cours void restart_palier(int numpalier, String *line1, String *line2) { *line1 = ""RESTART "" + myPaliers[0][numpalier] + "" ?""; *line2 = ""SEL=OUI autre=NO""; } void display_palier(int numpalier, String *line1, String *line2) { unsigned int t = 0; // L'objectif de température est celui du palier en cours theta_objectif = myTemperatures[numpalier]; // On ajoute tous les temps des paliers pour connaître le temps restant for (int i = 1; i <= numpalier; i++) { t += myTempo[i]; } DEBUGPRINTLN(""t : "" + String(t) + "" / minutes : "" + String(minutes)); // Si le temps n'est pas dépassé (t = temps total qu'il faut atteindre depuis le premier palier jusqu'à celui en cours) if (t > minutes) { myTempo[0] = t - minutes; } else { // le palier est fini : on saute au palier suivant automatiquement jump = 1; BeepON(200); palier_atteint = false; return; } *line1 = myPaliers[1][numpalier] + ""("" + String(myTempo[numpalier]) + "")""; // on affiche un caractère différent s'il y a chauffe ("">"") ou si le palier a déjà été atteint ("":"") if (palier_atteint) { *line1 = *line1 + "":"" + String(myTempo[0]) + "" min""; } else { *line1 = *line1 + "">"" + String(myTempo[0]) + "" min""; } *line2 = String((int)theta_mesure) + ""/"" + String((int)myTemperatures[numpalier]); #ifdef DEFIL if (defilement) { // on affiche alternativement la température en cours et la température à atteindre, ou... #endif *line2 = *line2 + degre + ""C ""; *line2 = *line2 PID_DEBUG(""PID:"" + String((int)ceil(tx_chauffe)) + "" ""); // Ne va s'ajouter que si on active la fonction de debug (désactivation : enlever #define PIDDEBUG) #ifdef DEFIL } else { // ... la température en cours et le temps total restant estimé avant la fin de l'ébullition, sans le temps inter-palier néanmoins t = 0; for (int i = numpalier + 1; i <= 6; i++) { t += myTempo[i]; } t += myTempo[0]; *line2 = *line2 + "" REST:"" + String(t) + ""min""; } #endif } // Fin Display_palier void LCD_upd() // affiche les infos à l'écran ********************************************************* { String Ligne1; String Ligne2; // CLS(); // on efface l'écran et on place le curseur au début de la première ligne switch (menu) { case 0: // Sélection de température de préchauffage { Ligne1 = myPaliers[0][menu] + "" ?""; Ligne2 = "">T"" + String(myTemperatures[0]) + degre + ""C""; break; } case 1: // Sélection de températures des paliers 1 à 6 - inclus Mash-out et ébullition case 2: case 3: case 4: case 5: case 6: { paliers_temp(menu, &Ligne1, &Ligne2); //fin sous menu break; } case 7: { // Possibilité de ne pas sauvegarder sur carte SD nos règlages (pour quelque raison que ce soit) Ligne1 = ""Sauvegarder ? ""; Ligne2 = ""SEL=oui DROIT=no""; break; } case 8: // préchauffage { theta_objectif = myTemperatures[0]; Ligne1 = myPaliers[1][0]; Ligne2 = String((int)theta_mesure) + ""/"" + String((int)myTemperatures[0]) + degre + ""C ""; Ligne2 = Ligne2 PID_DEBUG(""PID:"" + String(tx_chauffe)); // Ne va s'ajouter que si on active la fonction de debug (désactivation : commenter #define DEBUG) break; } case 9: // palier 1 case 10: // palier 2 case 11: // palier 3 case 12: // palier 4 case 13: // Mash-out case 14: // Ebullition { display_palier(menu - 8, &Ligne1, &Ligne2); break; } case 15: // refroidissement { Ligne1 = ""Refroidissement""; theta_objectif = 0; myTempo[0] = (minutes - cooling); Ligne2 = ""T:"" + String(((int)theta_mesure)) + degre + "" / "" + String(myTempo[0]) + "" min""; break; } case 109: // Demander si on veut recommencer le palier en cours case 110: case 111: case 112: case 113: case 114: { restart_palier(menu - 108, &Ligne1, &Ligne2); break; } case 115: // Recommencer le refroidissement { Ligne1 = ""RESTART REFROID?""; Ligne2 = ""SEL=OUI autre=NO""; break; } case 209: // Demander si on veut passer le palier en cours case 210: case 211: case 212: case 213: case 214: { pass_palier(menu - 208, &Ligne1, &Ligne2); break; } case 215: // On a demander à passer le refroidissement : fin du brassage { Ligne1 = ""FIN DU BRASSAGE ?""; Ligne2 = ""SEL=OUI autre=NO""; break; } default : { Ligne1 = ""Erreur de menu""; Ligne2 = ""menu "" + String(menu); break; } } lcd.setCursor(0, 0); lcd.print(Ligne1); lcd.setCursor(0, 1); lcd.print(Ligne2); } //************************************************************************************************************************************************************************FIN LCD // read the buttons int read_LCD_buttons() //cette fonction renvoie la touche appuyée { adc_key_in = analogRead(0); // read the value from the sensor // my [Mark Bramwell's] buttons when read are centered at these valies: 0, 144, 329, 504, 741 // we add approx 50 to those values and check to see if we are close // DEBUGPRINTLN(String(adc_key_in)); if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result if (adc_key_in < 50) return btnRIGHT; if (adc_key_in < 195) return btnUP; if (adc_key_in < 380) return btnDOWN; if (adc_key_in < 555) return btnLEFT; if (adc_key_in < 790) return btnSELECT; return btnNONE; // when all others fail, return this... } // fin read the buttons float gettemp() { myPID.Compute(); //on Lance un calcul du PID. le calcul se fait en même temps que le rafraichissement des variables de température float ttt; // Version Originale avec DAC #if defined(ADS1015) int16_t therm, therm2; float ttt2; // Le DAC à 2 entrées reliées à la même sonde. Pour déparasiter, on fait une moyenne des deux lectures therm = ads1115.readADC_SingleEnded(THERM_PIN); therm2 = ads1115.readADC_SingleEnded(THERM_PIN2); therm -= OFFSET_PROBE; therm2 -= OFFSET_PROBE; ttt = float(therm); ttt2 = float(therm2); ttt = ttt / COEF_PROBE; ttt2 = ttt2 / COEF_PROBE; ttt = (ttt + ttt2) / 2; #endif #if defined(DS18B20) DS18.requestTemperatures(); ttt = DS18.getTempCByIndex(0); // La sonde est dans les choux (on lit 0° ou -127°) if (ttt < 1) { ttt = last_temp; // on prend la dernière valeur qui était cohérente } #endif #if defined(MAX31865) uint16_t rtd = thermo.readRTD(); float ratio = rtd; ratio /= 32768; // Check and print any faults uint8_t fault = thermo.readFault(); if (fault) { Serial.print(""Fault 0x""); Serial.println(fault, HEX); if (fault & MAX31865_FAULT_HIGHTHRESH) { DEBUGPRINTLN(""RTD High Threshold""); } if (fault & MAX31865_FAULT_LOWTHRESH) { DEBUGPRINTLN(""RTD Low Threshold""); } if (fault & MAX31865_FAULT_REFINLOW) { DEBUGPRINTLN(""REFIN- > 0.85 x Bias""); } if (fault & MAX31865_FAULT_REFINHIGH) { DEBUGPRINTLN(""REFIN- < 0.85 x Bias - FORCE- open""); } if (fault & MAX31865_FAULT_RTDINLOW) { DEBUGPRINTLN(""RTDIN- < 0.85 x Bias - FORCE- open""); } if (fault & MAX31865_FAULT_OVUV) { DEBUGPRINTLN(""Under/Over voltage""); } thermo.clearFault(); } ttt = thermo.temperature(RNOMINAL, RREF); #endif last_temp = ttt; return ttt; } void CLS() // efface l'écran et place le curseur au début de la première ligne { lcd.clear(); lcd.setCursor(0, 0); } void horloge() //fonction appelée une fois par seconde . On profite de cette fonction pour certaines fonctionalités actualisées une fois par seconde { secondes_reel++; if (palier_atteint) { // on incrémente le compteur minutes toutes les 60s, mais seulement si on a atteint le palier - permet d'éviter les erreurs de mesure de la sonde qui parfois affiche des valeurs farfelues : // si la lecture de la sonde de température donne quelque chose de négatif au moment où on rentre dans ce sous-programme, on pourrait ne pas incrémenter les minutes, et donc faire durer trop longtemps le palier secondes++; //on compte le temps écoulé pendant que le palier est en cours BLINK(); //on fait clignoter une fois par seconde pour montrer que le palier est lancé } if (theta_objectif == 0) //cas uniquement présent lors du refroidissement { secondes++; } if (secondes >= 60) { secondes = 0; // Si le menu correpsond à un palier en cours (sauf préchauffage), on incrémente les minutes if (menu >= 9) { minutes++; DEBUGPRINTLN(""Minutes écoulées : : "" + String(minutes)); } } if (theta_mesure > (theta_objectif - hysteresis_Neg) && theta_mesure < (theta_objectif + hysteresis_Pos)) // si on est compris entre les deux valeurs d'hysteresis, on est dans la bonne plage de température. on réduit la force du PID { Kp = P_weak; // multiplicateur de l'erreur différentielle de température. Ki = I_weak; //coef de correction intégrale Kd = D_weak; //coef de dérivée } else { Kp = P_strong; // multiplicateur de l'erreur différentielle de température. 1° d'écart = Kp% de chauffe Ki = I_strong; //coef de correction intégrale Kd = D_strong; //coef de dérivée } myPID.SetTunings(Kp, Ki, Kd); } void lecture() { theta_mesure = gettemp(); if (theta_mesure > (theta_objectif - hysteresis_Neg) && theta_mesure < (theta_objectif + hysteresis_Pos)) { theta_PID = theta_mesure; // si on est proche de la température de consigne, on supprime l'offset de sécurité palier_atteint = true; // on annonce que le palier est atteint : c'est lui qui va déterminer si on va incrémenter les minutes pour le palier en cours, pour éviter les erreurs de mesure de la sonde } else { // Si on n'est pas à l'ébullition... if (menu != 14) { theta_PID = theta_mesure + PID_OFFSET; } else { theta_PID = theta_mesure; } } } void start_brew() { digitalWrite(ledPin, LOW); myPID.SetMode(AUTOMATIC); ////////////////////////////////// // on compte le temps que va prendre le programme startprog = 1; total_time = 0; for (int i = 1; i < 7; i++) { total_time += myTempo[i]; DEBUGPRINTLN(""Temps palier["" + String(i) + ""] : "" + String(myTempo[i])); } DEBUGPRINTLN(""Temps total prévu : "" + String(total_time)); CLS(); // move to position 0 on the first line lcd.print("" BRASSAGE ""); lcd.setCursor(0, 1); // move to position 0 on the second line lcd.print("" IMMINENT ! ""); delay(800); CLS(); lcd.print(""Duree prevue : ""); lcd.setCursor(0, 1); // move to position 0 on the second line lcd.print(total_time); lcd.print("" min""); delay(1000); digitalWrite(ledPin, LOW); menu = 8; //saute au menu suivant (départ programme) CLS(); LCD_upd(); return; } // +++++++++++++++++++++++++++++++++++++++++ GESTION DES MENUS ++++++++++++++++++++++++++++++++++++++++++++++ void sel_menu() { #ifdef BIPPEUR if (beep_duration > 0) { beep_duration--; } else { BeepOFF(); } #endif byte m; lcd_key = read_LCD_buttons(); // read the buttons if (menu >= 100) { // gestion des sauts de programme en cas d'annulation la valeur est >100 en cas de saut menu > 200 switch (lcd_key) { case btnNONE: { break; } case btnSELECT: { switch (menu) { case 108: { CLS(); lcd.print(""saut erreur 108""); menu = 8; delay(150); break; } case 109: //on a demandé à recommencer l'étape palier 1 case 110: //on a demandé à recommencer l'étape palier 2 case 111: //on a demandé à recommencer l'étape palier 3 case 112: //on a demandé à recommencer l'étape palier 4 case 113: //on a demandé à recommencer l'étape rincage mash out case 114: //on a demandé à recommencer l'étape ébu case 115: //on a demandé à recommencer l'étape refroidissement/whirlpool { m = menu - 108; CLS(); annuler = -1; // on était au menu X (menu - 109) on retourne au X-1 (menu - 110) minutes = 0; //avant le palier 1 (donc l'étape de préchauffage) le temps écoulé était à 0, et //avant le palier 2 (donc le palier 1) le temps écoulé était aussi égal à 0 myTempo[0] = 0; for (int i = m; i >= 2; i--) { // on ne réinitialise les minutes que pour les paliers > 1 minutes += myTempo[(i - 1)]; // on rajoute les durées des paliers précédents uniquement, car on recommence au début du palier m } cooling = minutes; delay(150); palier_atteint = false; // on ne sait jamais, on va prétendre que la température du palier n'a pas été atteinte break; } case 208: //on a demandé à sauter l'étape préchauffage (ne devrait pas arriver) { CLS(); lcd.print(""saut erreur 208""); menu = 8; delay(1000); BeepON(50); LCD_upd(); break; } case 209: //on a demandé à sauter l'étape palier 1 case 210: //on a demandé à sauter l'étape palier 2 case 211: //on a demandé à sauter l'étape palier 3 case 212: //on a demandé à sauter l'étape palier 4 case 213: //on a demandé à sauter l'étape mash out case 214: //on a demandé à sauter l'étape ebullition { m = menu - 208; minutes = 0; for (int i = m; i >= 1; i--) { // on ne réinitialise les minutes que pour les paliers > 1 minutes += myTempo[i]; // on rajoute les durées des paliers précédents et du palier en cours, car on va recommencer au début du palier m + 1 } myTempo[0] = 0; jump = 0; annuler = 1; cooling = minutes; // sauter l'étape ébullition (cooling sera mis à jour de toute façon quand on sera à la fin de l'ébullition, pas de problème à l'écraser maintenant) delay(150); palier_atteint = false; // on ne sait jamais, on va prétendre que la température du palier n'a pas été atteinte break; } case 215: // on a fini le brassage : on demande à ""sauter"" le refroidissement/whirlpool pour finir dans un état permettant d'arrêter proprement l'automate { T.stop(logRecord_ID); // On arrête le timer lié à l'écriture sur la carte SD, pour éviter qu'une écriture impromptue ne soit en cours quand on débranche l'Arduino logRecord(); // On appelle pour la dernière fois l'écriture sur la carte SD, pour logger la fin du brassage (dernier événement du log) CLS(); lcd.print(""Fin de BRASSAGE""); lcd.setCursor(0, 1); lcd.print(""!!! HAVE FUN !!!""); delay(800); while(1); // Arrêt propre : plus aucune action ne sera réalisée par la suite (donc pas d'erreur d'écriture sur carte SD par exemple) break; } break; } //fin switch menu }//fin bouton select case btnUP: // on annule le saut case btnDOWN: // on annule le saut case btnLEFT: // on annule le saut case btnRIGHT: // on annule le saut { CLS(); jump = 0; delay(500); if (menu > 199) { menu -= 200; } else { menu -= 100; } break; } break; }// fin switch lcd key } else { //Si on n'a pas demandé de saut // gestion des menus switch (lcd_key) // depending on which button was pushed, we perform an action { case btnNONE: { break; } case btnUP: { if (startprog == 0) //si on est encore en phase de programation, on peut naviguer du menu 0 à 7 { if (menu < 7) { menu++; delay(150); LCD_upd(); } } else { //le programme est lancé if (menu > 7) // On demande à sauter l'étape en cours { if (menu >= 9 && menu < 16) //si on est au menu 9 ou + on considère que c'est un saut de programme (y inclus pour le refroidissement, pour la fin du programme) { // small_Beep = 1; BeepON(200); menu += 200; } if (menu == 8) menu ++; //si on est dans le menu 8 (préchauffe) , le saut est autorisé sans condition delay(150); LCD_upd(); } }//fin else break; } case btnDOWN: { if (startprog == 0) //si on est encore en phase de programation, on peut naviguer du 7 à 0 { if (menu > 0) { menu--; delay(150); LCD_upd(); } } else { if (menu > 8) { //si on est en phase brassage (a partir de menu 9) // DEMANDER SI ON SOUHAITE RECOMMENCER L'ETAPE EN COURS // small_Beep = 1; BeepON(200); menu += 100; delay(150); LCD_upd(); } } break; } case btnLEFT: { //faire un switch menu switch (menu) { case 0: //menu température de préchauffe case 1: //menu réglage palier 1 case 2: //menu réglage palier 2 case 3: //menu réglage palier 3 case 4: //menu réglage palier 4 case 5: //menu réglage Mash out - rinçage case 6: // ébullition { if (submenu == 0) { if (myTemperatures[menu] > 20) myTemperatures[menu] -= 0.5; } else { if (myTempo[menu] > 0) myTempo[menu]--; } LCD_upd(); break; } case 7: //sauvegarde { break; } case 8: //préchauffe case 9: //palier 1 case 10://palier 2 case 11://palier 3 case 12://palier 4 case 13://rinçage - mash-out case 14://ébullition { m = menu - 8; DEBUGPRINTLN(""Valeur submenu pour le menu "" + String(m) + "" : "" + String(submenu)); if (submenu == 0) { if (myTemperatures[m] > 20) myTemperatures[m] -= 0.5; } else { if (myTempo[m] > 2) myTempo[m]--; } LCD_upd(); break; } case 15://mode manuel case 16://mode erreur { break; } } break; } case btnRIGHT: { //faire un switch menu switch (menu) { case 0: //menu température de préchauffe case 1: //menu réglage palier 1 case 2: //menu réglage palier 2 case 3: //menu réglage palier 3 case 4: //menu réglage palier 4 case 5: //menu réglage Mash out - rinçage case 6: // ébullition { if (submenu == 0) { if (myTemperatures[menu] <= 110) myTemperatures[menu] += 0.5; } else { myTempo[menu]++; } LCD_upd(); break; } case 7: // On a demandé à ne pas faire la sauvegarde { start_brew(); break; } case 8: //préchauffe case 9: //palier 1 case 10://palier 2 case 11://palier 3 case 12://palier 4 case 13://rinçage mash out case 14://ébullition { m = menu - 8; DEBUGPRINTLN(""Valeur submenu pour le menu "" + String(m) + "" : "" + String(submenu)); if (submenu == 0) { if (myTemperatures[m] < 110) myTemperatures[m] += 0.5; } else { myTempo[m]++; } LCD_upd(); break; } case 15://mode manuel case 16://mode erreur { break; } default: { CLS(); lcd.print(""Erreur de menu""); lcd.setCursor(0, 1); // move to position 0 on the second line lcd.print(""menu ""); lcd.print(menu); break; } } break; } case btnSELECT: { switch (menu) { case 1: // menu paliers 1 à 4 case 2: case 3: case 4: case 6: // ébullition { submenu = !submenu; LCD_upd(); break; } case 0: //menu température de préchauffe case 5: //menu rinçage { LCD_upd(); break; } case 7: // sauvegarde { digitalWrite(ledPin, HIGH); // sauvegarde des variables dans l'EEPROM si défini : #if (defined(EEPROMRW)) EEPROM.updateLong(0, myTempo[1]); EEPROM.updateLong(7, myTempo[2]); EEPROM.updateLong(15, myTempo[3]); EEPROM.updateLong(23, myTempo[4]); EEPROM.updateLong(31, myTempo[6]); EEPROM.updateFloat(39, myTemperatures[1]); EEPROM.updateFloat(47, myTemperatures[2]); EEPROM.updateFloat(55, myTemperatures[3]); EEPROM.updateFloat(63, myTemperatures[4]); EEPROM.updateFloat(71, myTemperatures[6]); EEPROM.updateFloat(79, myTemperatures[5]); EEPROM.updateFloat(87, myTemperatures[0]); #endif sauve_param(); myFile = SD.open(datalogFile, FILE_WRITE); DEBUGPRINTLN(""Write on "" + datalogFile); if (myFile) { myFile.print(""----GraiN.Master----\\n""); myFile.print(version); myFile.print(""\\nTempérature de départ : ""); myFile.print(myTemperatures[0]); myFile.print(""°C\\n""); for (int i = 1; i < 7; i++) { myFile.print(myPaliers[0][i]); myFile.print(myTempo[i]); myFile.print("" min - ""); myFile.print(myTemperatures[i]); myFile.print(""°C\\n""); } myFile.print(""\\n\\n""); myFile.print(""Temps (s),Température cible °C,Température °C,PID (0-255)\\n""); myFile.close(); } DEBUGPRINTLN(""----GraiN.Master----\\n""); DEBUGPRINTLN(version); DEBUGPRINTLN(""\\nTempérature de départ : ""); DEBUGPRINTLN(myTemperatures[0]); DEBUGPRINTLN(""°C\\n""); #ifdef DEBUG for (int i = 1; i < 7; i++) { DEBUGPRINTLN(myPaliers[0][i]); DEBUGPRINTLN(String(myTempo[i]) + "" min - "" + String(myTemperatures[i]) + ""°C""); } #endif lcd.home(); // move to position 0 on the first line lcd.print("" PROGRAMME ""); lcd.setCursor(0, 1); // move to position 0 on the second line lcd.print("" SAUVEGARDE ! ""); delay(600); start_brew(); break; } case 8: //palier 1 case 9: //palier 2 case 10: //palier 3 case 11://palier 3 case 12://palier 4 case 13://rinçage - mash-out case 14://ébullition { submenu = !submenu; // Permet de modifier la durée ou la température du palier en cours break; } default: { CLS(); lcd.print(""Erreur de menu""); lcd.setCursor(0, 1); // move to position 0 on the second line lcd.print(""menu ""); lcd.print(menu); break; } break; } //fin switch menu break; } //fin buton select default: { CLS(); lcd.print(""Erreur de menu""); lcd.setCursor(0, 1); // move to position 0 on the second line lcd.print(""menu ""); lcd.print(menu); break; } break; } //fin switch lcd key } //fin du else (pas de saut) } void regle_chauffe() { if (tx_chauffe >= 250) { // Si on est dans un des paliers de chauffe, on veut une courbe de température douce, qui gagne environ 1° toutes les minutes (pour éviter de violenter notre moût), le TRIAC à fond va beaucoup plus fort // On ne modifie pas tx_chauffe pour éviter tout effet de bord // Ce n'est valide que si le palier n'a pas été atteint. Si ce n'est pas le cas, c'est qu'on a eu une brusque chute de température lors du palier et qu'il faut au plus vite revenir à notre température ! if (menu >= 9 && menu <= 13 && !palier_atteint) { // menu 8 = préchauffage, menu 9 = palier 1, menu 13 = mash-out, menu 14 = ébullition PROPORTIONNAL(); Triac_pilot(Power_out(220)); } // Si on est autre part (préchauffage ou ébullition), on y va à fond else { FULL_ON(); } } else { if (tx_chauffe <= 5) { FULL_OFF(); } else { PROPORTIONNAL(); Triac_pilot(Power_out(tx_chauffe)); } } } //Interrupt Service Routines void zeroCrossingInterrupt() { //zero cross detect TCCR1B = 0x04; //start timer with divide by 256 input TCNT1 = 0; //reset timer - count from zero } ISR(TIMER1_COMPA_vect) { //comparator match digitalWrite(GATE, HIGH); //set triac gate to high TCNT1 = 65536 - PULSE; //trigger pulse width } ISR(TIMER1_OVF_vect) { //timer1 overflow digitalWrite(GATE, LOW); //turn off triac gate TCCR1B = 0x00; //disable timer stopd unintended triggers } void Triac_pilot(int conduction_time) { // pilote le triac if (conduction_time > HALF_WAVE) conduction_time = HALF_WAVE; OCR1A = conduction_time; //set the compare register brightness desired. } int Power_out(int Power) //calcule le temps de conduction nécessaire pour obtenir la puissance demandée. Power va de 0 à 255 { int CT; CT = 540 - (Power * 2); return CT; } void FULL_ON() { // set up zero crossing interrupt detachInterrupt(digitalPinToInterrupt(2)); // équivalent à 0 digitalWrite(GATE, HIGH); //IRQ0 is pin 2 } void FULL_OFF() { // set up zero crossing interrupt detachInterrupt(digitalPinToInterrupt(2)); // équivalent à 0 digitalWrite(GATE, LOW); //IRQ0 is pin 2 } void PROPORTIONNAL() { attachInterrupt(digitalPinToInterrupt(2), zeroCrossingInterrupt, CHANGE); } void logRecord() { byte numpalier = 0; #ifdef DEFIL defilement = !defilement; // Position du défilement / 1 = température et température à atteindre / 0 = température et temps restant / s'échange à chaque écriture sur la carte SD, donc toutes les 10 s environ #endif if (menu > 200) numpalier = menu - 208; else if (menu > 100) numpalier = menu - 108; else if (menu <= 7) numpalier = 0; else numpalier = menu - 8; digitalWrite(ledPin, 1); File dataFile = SD.open(datalogFile, FILE_WRITE); if (dataFile) { dataFile.print(secondes_reel); dataFile.print("";""); if (numpalier != 7) dataFile.print(myPaliers[0][numpalier]); else dataFile.print(""Refroidissement""); dataFile.print("";""); dataFile.print(theta_objectif); dataFile.print("";""); dataFile.print(theta_mesure); dataFile.print("";""); dataFile.print(tx_chauffe); dataFile.print('\\n'); dataFile.close(); } digitalWrite(ledPin, 0); DEBUGPRINTLN(""Secondes réelles depuis le début : "" + String(secondes_reel)); DEBUGPRINTLN(""Theta_Objectif : "" + String(theta_objectif)); DEBUGPRINTLN(""Theta_mesure : "" + String(theta_mesure)); DEBUGPRINTLN(""Taux chauffe (PID) : "" + String(tx_chauffe)); CLS(); // On ne refresh l'écran que toutes les 10 secondes, pour éviter l'effet stroboscopique } void sauve_param() { digitalWrite(ledPin, 1); if (SD.exists(""setup.grm"")) { SD.remove(""setup.grm""); } File dataFile = SD.open(""setup.grm"", FILE_WRITE); if (dataFile) { // Certaines informations ne sont présentes que pour le DAC #if defined(ADS1015) dataFile.print(""THERMPIN2""); dataFile.print(""=""); dataFile.print(THERM_PIN2); dataFile.print("",""); dataFile.print(""THERMPIN1""); dataFile.print(""=""); dataFile.print(THERM_PIN); dataFile.print("",""); dataFile.print(""OFSETPRBE""); dataFile.print(""=""); dataFile.print(OFFSET_PROBE); dataFile.print("",""); dataFile.print(""COEFPROBE""); dataFile.print(""=""); dataFile.print(COEF_PROBE); dataFile.print("",""); #endif dataFile.print(""hysterPos""); dataFile.print(""=""); dataFile.print(hysteresis_Pos); dataFile.print("",""); dataFile.print(""hysterNeg""); dataFile.print(""=""); dataFile.print(hysteresis_Neg); dataFile.print("",""); dataFile.print(myPaliers[0][0]); dataFile.print(myTemperatures[0]); dataFile.print("",""); for (int i = 1; i < 7; i++) { dataFile.print(myPaliers[0][i]); dataFile.print(myTemperatures[i]); dataFile.print("",""); dataFile.print(myPaliers[1][i] + ""TEMPO""); dataFile.print(""=""); dataFile.print(myTempo[i]); dataFile.print("",""); } dataFile.print(""Pstrong00""); dataFile.print(""=""); dataFile.print(P_strong); dataFile.print("",""); dataFile.print(""Istrong00""); dataFile.print(""=""); dataFile.print(I_strong); dataFile.print("",""); dataFile.print(""Dstrong00""); dataFile.print(""=""); dataFile.print(D_strong); dataFile.print("",""); dataFile.print(""Pweak0000""); dataFile.print(""=""); dataFile.print(P_weak); dataFile.print("",""); dataFile.print(""Iweak0000""); dataFile.print(""=""); dataFile.print(I_weak); dataFile.print("",""); dataFile.print(""Dweak0000""); dataFile.print(""=""); dataFile.print(D_weak); dataFile.print("",""); dataFile.print(""LEDPIN000""); dataFile.print(""=""); dataFile.print(ledPin); dataFile.print("",""); dataFile.print(""GATE00000""); dataFile.print(""=""); dataFile.print(GATE); dataFile.print("",""); dataFile.print(""PULSE0000""); dataFile.print(""=""); dataFile.print(PULSE); dataFile.print("",""); dataFile.print(""HALFWAVE0""); dataFile.print(""=""); dataFile.print(HALF_WAVE); dataFile.print("",""); #if (defined(BIPPEUR)) dataFile.print(""BEEPPIN00""); dataFile.print(""=""); dataFile.print(Beep_PIN); dataFile.print("",""); #endif dataFile.print(""PIDOFFSET""); dataFile.print(""=""); dataFile.print(PID_OFFSET); dataFile.print("",""); #if defined(DS18B20) dataFile.print(""ONEWIRE00""); dataFile.print(""=""); dataFile.print(ONE_WIRE_BUS); dataFile.print("",""); #endif dataFile.close(); } digitalWrite(ledPin, 0); } ",16184,True,3126.7952655282725,median "/** * Distributed under Apache License v2.0. For more information * see LICENSE. */ package com.traffic.util.debugging { import com.traffic.util.logging.StringLogTarget; import flash.events.Event; import mx.logging.Log; import org.flexunit.assertThat; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertFalse; import org.flexunit.asserts.assertTrue; public class tdtTest { private static const STACK_TRACE_LIMIT:int = 64; [Before] public function setUp():void { tdt.setUp(true, true, tdt.PRINT_MANUAL); } [After] public function tearDown():void { tdt.clearActivities(); } [Test] public function test_clearActivities():void { //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); //then assertEquals(0, logTarget.log.length); //when tdt.debug(); tdt.printActivityStreams(false); //then assertTrue(atLeastOneActivityInXML(new XML(logTarget.log))); //given logTarget = new StringLogTarget(); Log.addTarget(logTarget); //then assertEquals(0, logTarget.log.length); //when tdt.debug(); tdt.printActivityStreams(false); //then assertTrue(atLeastOneActivityInXML(new XML(logTarget.log))); //given logTarget = new StringLogTarget(); Log.addTarget(logTarget); //when tdt.clearActivities(); tdt.printActivityStreams(true); //then assertActualAndExpectedXMLsMatch(new XML(logTarget.log), ); assertFalse(atLeastOneActivityInXML(new XML(logTarget.log))); } [Test] public function test_getFunctionsFromStackTrace_with_simple_stack_trace():void { //given const testStack:String = ( ).toString(); const expected:Array = [ ""ADG.mouseUpHandler"", ""ADGBE.mouseUpHandler"", ""UIC.dispatchEvent"", ""ED.dispatchEvent"", "".dispatchEventFunction"", ""HCVC.collectionChangeHandler"", "".findFirst"" ]; //when var allStackFunctionsExceptLast:Array = tdt.getFunctionsFromStackTrace(testStack, true, true, 1); //then assertTrue(arraysEqual(expected, allStackFunctionsExceptLast)); } [Test] public function test_getFunctionsFromStackTrace_with_complex_and_repetitive_stack_trace():void { //given const complexStackWithRepetitions:String = ( ).toString(); const expected:Array = [ ""StatementSequencer.evaluate"", "".handleChildExecuteComplete"", "".executeStep"", "".evaluate"", "".handleChildExecuteComplete"", ""SequencerWithDecoration.executeStep"", ""InvokeMethod.evaluate"", ""AsyncTestToken.sendResult"", ""StatementSequencer.handleChildExecuteComplete"", "".sendComplete"", ""AsyncStatementBase.sendComplete"", ""AsyncTestToken.sendResult"", ""StatementSequencer.handleChildExecuteComplete"", "".executeStep"", "".evaluate"", "".handleChildExecuteComplete"", ""ChildRunnerSequencer.executeStep"", ""BlockFlexUnit4ClassRunner.runChild"", ""StackAndFrameManagement.evaluate"", ""InvokeMethod.evaluate"", ""AsyncTestToken.sendResult"", ""StackAndFrameManagement.handleNextExecuteComplete"", ""AsyncTestToken.sendResult"", ""BlockFlexUnit4ClassRunner.handleBlockComplete"", ""AsyncTestToken.sendResult"", ""StatementSequencer.handleChildExecuteComplete"", ""ChildRunnerSequencer.executeStep"", ""BlockFlexUnit4ClassRunner.runChild"", ""StackAndFrameManagement.evaluate"", ""InvokeMethod.evaluate"", ""AsyncTestToken.sendResult"", ""StackAndFrameManagement.handleNextExecuteComplete"", ""AsyncTestToken.sendResult"", ""BlockFlexUnit4ClassRunner.handleBlockComplete"", ""AsyncTestToken.sendResult"", ""StatementSequencer.handleChildExecuteComplete"", ""ChildRunnerSequencer.executeStep"", ""BlockFlexUnit4ClassRunner.runChild"", ""StackAndFrameManagement.evaluate"", ""InvokeMethod.evaluate"", ""AsyncTestToken.sendResult"", ""StackAndFrameManagement.handleNextExecuteComplete"", ""AsyncTestToken.sendResult"", ""BlockFlexUnit4ClassRunner.handleBlockComplete"", ""AsyncTestToken.sendResult"", ""StatementSequencer.handleChildExecuteComplete"", ""ChildRunnerSequencer.executeStep"", ""BlockFlexUnit4ClassRunner.runChild"", ""StackAndFrameManagement.evaluate"", ""InvokeMethod.evaluate"", ""AsyncTestToken.sendResult"", ""StackAndFrameManagement.handleNextExecuteComplete"", ""AsyncTestToken.sendResult"", ""BlockFlexUnit4ClassRunner.handleBlockComplete"", ""AsyncTestToken.sendResult"", ""StatementSequencer.handleChildExecuteComplete"", ""ChildRunnerSequencer.executeStep"", ""BlockFlexUnit4ClassRunner.runChild"", ""StackAndFrameManagement.evaluate"", ""InvokeMethod.evaluate"", ""FrameworkMethod.invokeExplosively"", ""Method.apply"", ""Function.apply"", ""tdtTest.test_log_output_includes_stack_functions_in_correct_order"" ]; //when var stackFunctions:Array = tdt.getFunctionsFromStackTrace(complexStackWithRepetitions, false, true, 0); //then assertTrue(arraysEqual(expected, stackFunctions)); } [Test] public function test_getFunctionsFromStackTrace_with_complex_stack_trace():void { //given const testUnrealisticButComplexStack:String = ( ).toString(); const expected:Array = [ ""LM.doPhasedInstantiationCallback"", "".doPhasedInstantiation"", "".validateDisplayList"", ""DTM.()"", ""UIC.validateDisplayList"", ""RET.updateDisplayList"", ""TCM.convertToTextFlowWithComposer"", ""SFC.addController"", "".attachAllContainers"", ""CC.setRootElement"" ]; //when var stackFunctions:Array = tdt.getFunctionsFromStackTrace(testUnrealisticButComplexStack, true, true, 0); //then assertTrue(arraysEqual(stackFunctions, expected)); } [Test] public function test_getFunctionsFromStackTrace_with_complex_stack_trace_including_inner_function_and_getter_and_inner_class():void { //given const testUnrealisticButComplexStack:String = ( ).toString(); const expected:Array = [ ""LM.doPhasedInstantiationCallback"", "".doPhasedInstantiation"", "".validateDisplayList"", ""DTM.()"", ""UIC.validateDisplayList"", ""RET.updateDisplayList"", ""TCM.convertToTextFlowWithComposer"", ""SFC.addController"", "".attachAllContainers"", ""CC.setRootElement"", ""STP.set testSetter.debugit"", ""STP.STL.get functionName.accessorAndFunctionToFunction"", "".set testSetter.debugit"" ]; //when var actual:Array = tdt.getFunctionsFromStackTrace(testUnrealisticButComplexStack, true, true, 0); //then assertTrue(arraysEqual(actual, expected)); } [Test] public function test_xml_log_for_two_identical_stack_traces_should_include_functions_only_once():void { //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const stack:String = ( ).toString(); const expectedXML:XML = hello hello ; //when tdt.debug(""hello"", stack, false); tdt.debug(""hello"", stack, false); tdt.printActivityStreams(true); //then assertActualAndExpectedXMLsMatch(new XML(logTarget.log), expectedXML); } [Test] public function test_xml_log_for_stack_traces_which_share_root():void { //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const stack1:String = ( ).toString(); const stack2:String = ( ).toString(); const expectedXML:XML = hello measuring ; //when tdt.debug(""hello"", stack1, false); tdt.debug(""measuring"", stack2, false); tdt.printActivityStreams(true); //then assertActualAndExpectedXMLsMatch(new XML(logTarget.log), expectedXML); } [Test] public function test_xml_log_for_more_stack_traces_which_share_root():void { //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const stack1:String = ( ).toString(); const stack2:String = ( ).toString(); const stack3:String = ( ).toString(); const stack4:String = ( ).toString(); const expectedXML:XML = hello measuring measuring2 UIComp phased ; const expected:XMLList = expectedXML.descendants(); //when tdt.debug(""hello"", stack1, false); tdt.debug(""measuring"", stack2, false); tdt.debug(""measuring2"", stack2, false); tdt.debug(""UIComp"", stack3, false); tdt.debug(""phased"", stack4, false); tdt.printActivityStreams(true); //then assertActualAndExpectedXMLsMatch(new XML(logTarget.log), expectedXML); } [Test] public function test_xml_log_for_stack_traces_which_do_not_share_root():void { //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const stack1:String = ( ).toString(); const stack2:String = ( ).toString(); const expectedXML:XML = hello measuring ; const expected:XMLList = expectedXML.descendants(); //when tdt.debug(""hello"", stack1, false); tdt.debug(""measuring"", stack2, false); tdt.printActivityStreams(true); //then assertActualAndExpectedXMLsMatch(new XML(logTarget.log), expectedXML); } [Test] public function test_location_tracing():void { //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const expectedXMLFragment:XML = T.test_location_tracing(); //when tdt.debugLocation(arguments); tdt.printActivityStreams(true); //then assertFirstActivitiesInIdenticalSubTrees(new XML(logTarget.log), expectedXMLFragment); } [Test] public function test_location_tracing_with_arguments():void { function locationTracingWithTwoArguments(a:int = 1, b:int = 2):void { tdt.debugLocation(arguments); } //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const expectedXMLFragment:XML = tdtTest.test_location_tracing_with_arguments.locationTracingWithTwoArguments(3,4); //when tdt.setUp(false, false); locationTracingWithTwoArguments(3, 4); tdt.printActivityStreams(true); //then assertFirstActivitiesInIdenticalSubTrees(new XML(logTarget.log), expectedXMLFragment); } [Test] public function test_location_tracing_with_arguments_in_inner_function_of_inner_function():void { function locationTracingWithTwoArguments(a:int = 1, b:int = 2):void { function sum(a:int, b:int):int { tdt.debugLocation(arguments); return a + b; } sum(a, b); } //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const expectedXMLFragment:XML = tdtTest.test_location_tracing_with_arguments_in_inner_function_of_inner_function.locationTracingWithTwoArguments.sum(9,11); //when tdt.setUp(false, false); locationTracingWithTwoArguments(9, 11); tdt.printActivityStreams(true); //then assertFirstActivitiesInIdenticalSubTrees(new XML(logTarget.log), expectedXMLFragment); } [Test] public function test_unique_instance_tracking():void { //given const obj1:Object = {}; const obj2:Object = {}; //when var idObj1:String = tdt.getId(obj1); var idObj2:String = tdt.getId(obj2); //then assertFalse(idObj1 == idObj2); assertEquals(idObj1, tdt.getId(obj1)); } [Test] public function test_event_dispatching():void { //given var eventDispatched:Boolean = false; const eventListener:Function = function(event:Event):void { eventDispatched = true; }; //when tdt.addEventListener(Event.ACTIVATE, eventListener); tdt.dispatchEvent(new Event(Event.ACTIVATE)); //then assertThat(eventDispatched); //when 2 eventDispatched = false; tdt.removeEventListener(Event.ACTIVATE, eventListener); tdt.dispatchEvent(new Event(Event.ACTIVATE)); //then 2 assertFalse(eventDispatched); } [Test] public function test_log_output_includes_activity():void { //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const activity:String = ""hello world!""; //when tdt.setUp(false, true, tdt.PRINT_IMMEDIATELY); tdt.debug(activity); //then assertThat(logTarget.log.indexOf(activity) != -1); } [Test] public function test_log_output_includes_stack_functions_in_correct_order():void { //given var logTarget:StringLogTarget = new StringLogTarget(); Log.addTarget(logTarget); const activity:String = ""hello world!""; const currentStackTrace:String = new Error().getStackTrace(); var stackFunctions:Array = tdt.getFunctionsFromStackTrace(currentStackTrace, false, true, 0); //when tdt.setUp(false, true, tdt.PRINT_IMMEDIATELY); tdt.debug(activity); //then var logCopy:String = logTarget.log; for(var i:int = stackFunctions.length >= STACK_TRACE_LIMIT ? 1 : 0; i < stackFunctions.length; i++) { var stackFunction:String = stackFunctions[i]; var positionOfFunctionInTrace:int = logCopy.indexOf(stackFunction); assertThat(""The function "" + stackFunction + "" doesn't exist in the log!\\nLOG: "" + logTarget.log + ""CURRENT STACK TRACE: "" + currentStackTrace, positionOfFunctionInTrace != -1); logCopy = logCopy.substr(positionOfFunctionInTrace + stackFunction.length); } } [Test] public function test_the_limit_of_stack_traces():void { //when const errorWithLongStackTrace:Error = getErrorWithLongStackTrace(); const stackTraceLines:Array = errorWithLongStackTrace.getStackTrace().split(""\\n""); const actualLimit:int = stackTraceLines.length - 1; //minus the first line, which is the error description //then assertEquals(STACK_TRACE_LIMIT, actualLimit); } [Test] public function test_setting_and_retrieving_string_value():void { //when tdt.setValue(""hello"", ""world""); //then assertEquals(""world"", tdt.getValue(""hello"")); } [Test] public function test_setting_and_retrieving_object():void { //given var world:Object = {universe:2345, galaxy:198324}; //when tdt.setValue(""hello"", world); //then assertEquals(world, tdt.getValue(""hello"")); } [Test] public function test_retrieving_nonexistent_value_returns_undefined():void { //given var world:Object = {universe:2345, galaxy:198324}; //when tdt.setValue(""hello"", world); //then assertThat(undefined === tdt.getValue(""nonexistent"")); } //returns true if the first activity of the actual fragment, is identical to (except for the time attribute) //and also surrounded by exactly the same parents, siblings and children as the first one in the expected fragment private static function assertFirstActivitiesInIdenticalSubTrees(actual:XML, expectedFragment:XML):void { const expectedXMLString:String = removeWhiteSpaceBetweenTags(removeActivityTimesFromTraceXML(expectedFragment.toString())); const actualXMLString:String = removeWhiteSpaceBetweenTags(removeActivityTimesFromTraceXML(actual.toString())); assertThat(""Expected XML not found in actual XML. Expected: \\n"" + expectedXMLString + ""\\n.\\n.\\n. Actual: \\n"" + actualXMLString, actualXMLString.indexOf(expectedXMLString) != -1); } private static function removeActivityTimesFromTraceXML(traceXML:String):String { return traceXML.replace(/[\\s]+\\<""); } private static function atLeastOneActivityInXML(actual:XML):Boolean { return actual..activity.length() > 0; } private static function assertActualAndExpectedXMLsMatch(actual:XML, expected:XML):void { const actualDescendants:XMLList = actual.descendants(); const expectedDescendants:XMLList = expected.descendants(); assertEquals(expectedDescendants.length(), actualDescendants.length()); for(var i:int = 0; i < expectedDescendants.length(); i++) { var expectedNode:XML = expectedDescendants[i]; var actualNode:XML = actualDescendants[i]; if(expectedNode.name() == ""call"") { assertEquals(expectedNode.attribute(""name""), actualNode.attribute(""name"")); assertEquals(expectedNode.descendants().length(), actualNode.descendants().length()); } else if(expectedNode.name() == ""activity"") assertThat(actualNode.attribute(""time"").toString().length > 0); else assertEquals(expectedNode.toString(), actualNode.toString()); } } private function getErrorWithLongStackTrace():Error { function generateErrorAfterManyRecursions():void { if(++counter < 100) generateErrorAfterManyRecursions(); else error = new Error(); } var counter:int = 0; var error:Error = null; generateErrorAfterManyRecursions(); return error; } private static function arraysEqual(a1:Array, a2:Array):Boolean { assertEquals(""array lengths are different!"", a1.length, a2.length); for (var i:int=0; i < a1.length; i++) { if (a1[i] != a2[i]) return false; } return true; } } }",12453,True,2608.174871413002,median "/** * VERSION: 1.67 * DATE: 2011-04-20 * AS3 (AS2 version is also available) * UPDATES AND DOCS AT: http://www.greensock.com/timelinemax/ **/ package com.greensock { import com.greensock.core.*; import com.greensock.OverwriteManager; import com.greensock.events.TweenEvent; import flash.events.*; /** * TimelineMax extends TimelineLite, offering exactly the same functionality plus useful * (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, * currentLabel, addCallback(), removeCallback(), tweenTo(), tweenFromTo(), getLabelAfter(), getLabelBefore(), * and getActive() (and probably more in the future). It is the ultimate sequencing tool. * Think of a TimelineMax instance like a virtual MovieClip timeline or a container where * you place tweens (or other timelines) over the course of time. You can: * *
    *
  • build sequences easily by adding tweens with the append(), prepend(), insert(), appendMultiple(), * prependMultiple(), and insertMultiple() methods. Tweens can overlap as much as you want and you have * complete control over where they get placed on the timeline.
  • * *
  • add labels, play(), stop(), gotoAndPlay(), gotoAndStop(), restart(), tweenTo() and even reverse()!
  • * *
  • nest timelines within timelines as deeply as you want.
  • * *
  • set the progress of the timeline using its currentProgress property. For example, to skip to * the halfway point, set myTimeline.currentProgress = 0.5.
  • * *
  • tween the currentTime, totalTime, currentProgress, or totalProgress * property to fastforward/rewind the timeline. You could * even attach a slider to one of these properties to give the user the ability to drag * forwards/backwards through the whole timeline.
  • * *
  • add onStart, onUpdate, onComplete, onReverseComplete, and/or onRepeat callbacks using the * constructor's vars object.
  • * *
  • speed up or slow down the entire timeline with its timeScale property. You can even tween * this property to gradually speed up or slow down the timeline.
  • * *
  • use the insertMultiple(), appendMultiple(), or prependMultiple() methods to create * complex sequences including various alignment modes and staggering capabilities. * Works great in conjunction with TweenMax.allTo() too.
  • * *
  • base the timing on frames instead of seconds if you prefer. Please note, however, that * the timeline's timing mode dictates its childrens' timing mode as well.
  • * *
  • kill the tweens of a particular object inside the timeline with killTweensOf() or get the tweens of an object * with getTweensOf() or get all the tweens/timelines in the timeline with getChildren()
  • * *
  • set the timeline to repeat any number of times or indefinitely. You can even set a delay * between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse * every other cycle.
  • * *
  • listen for START, UPDATE, REPEAT, REVERSE_COMPLETE, and COMPLETE events.
  • * *
  • get the active tweens in the timeline with getActive().
  • * *
  • add callbacks (function calls) anywhere in the timeline that call a function of your choosing when * the ""virtual playhead"" passes a particular spot.
  • * *
  • Get the currentLabel or find labels at various positions in the timeline * using getLabelAfter() and getLabelBefore()
  • *
* * EXAMPLE:

* * import com.greensock.~~;

* * //create the timeline and add an onComplete call to myFunction when the timeline completes
* var myTimeline:TimelineMax = new TimelineMax({onComplete:myFunction});

* * //add a tween
* myTimeline.append(new TweenLite(mc, 1, {x:200, y:100}));

* * //add another tween at the end of the timeline (makes sequencing easy)
* myTimeline.append(new TweenLite(mc, 0.5, {alpha:0}));

* * //repeat the entire timeline twice
* myTimeline.repeat = 2;

* * //delay the repeat by 0.5 seconds each time.
* myTimeline.repeatDelay = 0.5;

* * //pause the timeline (stop() works too)
* myTimeline.pause();

* * //reverse it anytime...
* myTimeline.reverse();

* * //Add a ""spin"" label 3-seconds into the timeline.
* myTimeline.addLabel(""spin"", 3);

* * //insert a rotation tween at the ""spin"" label (you could also define the insert point as the time instead of a label)
* myTimeline.insert(new TweenLite(mc, 2, {rotation:""360""}), ""spin"");

* * //go to the ""spin"" label and play the timeline from there...
* myTimeline.gotoAndPlay(""spin"");

* * //call myCallbackwhen the ""virtual playhead"" travels past the 1.5-second point. * myTimeline.addCallback(myCallback, 1.5); * * //add a tween to the beginning of the timeline, pushing all the other existing tweens back in time
* myTimeline.prepend(new TweenMax(mc, 1, {tint:0xFF0000}));

* * //nest another TimelineMax inside your timeline...
* var nestedTimeline:TimelineMax = new TimelineMax();
* nestedTimeline.append(new TweenLite(mc2, 1, {x:200}));
* myTimeline.append(nestedTimeline);

* * * insertMultiple() and appendMultiple() provide some very powerful sequencing tools as well, * allowing you to add an Array of tweens/timelines and optionally align them with SEQUENCE or START * modes, and even stagger them if you want. For example, to insert 3 tweens into the timeline, aligning their start times but * staggering them by 0.2 seconds,

* * myTimeline.insertMultiple([new TweenLite(mc, 1, {y:""100""}), * new TweenLite(mc2, 1, {x:120}), * new TweenLite(mc3, 1, {alpha:0.5})], * 0, * TweenAlign.START, * 0.2);

* * You can use the constructor's vars object to do all the setup too, like:

* * var myTimeline:TimelineMax = new TimelineMax({tweens:[new TweenLite(mc1, 1, {y:""100""}), TweenMax.to(mc2, 1, {tint:0xFF0000})], align:TweenAlign.SEQUENCE, onComplete:myFunction, repeat:2, repeatDelay:1});

* * If that confuses you, don't worry. Just use the append(), insert(), and prepend() methods to build your * sequence. But power users will likely appreciate the quick, compact way they can set up sequences now.

* * * NOTES: *
    *
  • TimelineMax automatically inits the OverwriteManager class to prevent unexpected overwriting behavior in sequences. * The default mode is AUTO, but you can set it to whatever you want with OverwriteManager.init() * (see http://www.greensock.com/overwritemanager/)
  • *
  • TimelineMax adds about 4.9k to your SWF (not including OverwriteManager).
  • *
* * Copyright 2011, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com **/ public class TimelineMax extends TimelineLite implements IEventDispatcher { /** @private **/ public static const version:Number = 1.67; /** @private **/ protected var _repeat:int; /** @private **/ protected var _repeatDelay:Number; /** @private **/ protected var _cyclesComplete:int; /** @private **/ protected var _dispatcher:EventDispatcher; /** @private **/ protected var _hasUpdateListener:Boolean; /** * Works in conjunction with the repeat property, determining the behavior of each cycle; when yoyo is true, * the timeline will go back and forth, appearing to reverse every other cycle (this has no affect on the reversed property though). * So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. * But if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. **/ public var yoyo:Boolean; /** * Constructor.

* * SPECIAL PROPERTIES
* The following special properties may be passed in via the constructor's vars parameter, like * new TimelineMax({paused:true, onComplete:myFunction, repeat:2, yoyo:true}) * *
    *
  • delay : Number Amount of delay in seconds (or frames for frames-based timelines) before the timeline should begin.
  • * *
  • useFrames : Boolean If useFrames is set to true, the timeline's timing mode will be based on frames. * Otherwise, it will be based on seconds/time. NOTE: a TimelineLite's timing mode is * always determined by its parent timeline.
  • * *
  • paused : Boolean Sets the initial paused state of the timeline (by default, timelines automatically begin playing immediately)
  • * *
  • reversed : Boolean If true, the timeline will be reversed initially. This does NOT force it to the very end and start * playing backwards. It simply affects the orientation of the timeline, so if reversed is set to * true initially, it will appear not to play because it is already at the beginning. To cause it to * play backwards from the end, set reversed to true and then set the currentProgress property to 1 immediately * after creating the timeline.
  • * *
  • tweens : Array To immediately insert several tweens into the timeline, use the tweens special property * to pass in an Array of TweenLite/TweenMax/TimelineLite/TimelineMax instances. You can use this in conjunction * with the align and stagger special properties to set up complex sequences with minimal code. * These values simply get passed to the insertMultiple() method.
  • * *
  • align : String Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately through the constructor. The value simply gets passed to the * insertMultiple() method. The default is TweenAlign.NORMAL. Options are: *
      *
    • TweenAlign.SEQUENCE: aligns the tweens one-after-the-other in a sequence
    • *
    • TweenAlign.START: aligns the start times of all of the tweens (ignores delays)
    • *
    • TweenAlign.NORMAL: aligns the start times of all the tweens (honors delays)
    • *
    The align special property does not force all child tweens/timelines to maintain * relative positioning, so for example, if you use TweenAlign.SEQUENCE and then later change the duration * of one of the nested tweens, it does not force all subsequent timelines to change their position * on the timeline. The align special property only affects the alignment of the tweens that are * initially placed into the timeline through the tweens special property of the vars object.
  • * *
  • stagger : Number Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately. It staggers the tweens by a set amount of time (in seconds) (or * in frames if useFrames is true). For example, if the stagger value is 0.5 and the align * property is set to TweenAlign.START, the second tween will start 0.5 seconds after the first one * starts, then 0.5 seconds later the third one will start, etc. If the align property is * TweenAlign.SEQUENCE, there would be 0.5 seconds added between each tween. This value simply gets * passed to the insertMultiple() method. Default is 0.
  • * *
  • onStart : Function A function that should be called when the timeline begins (the currentProgress won't necessarily * be zero when onStart is called. For example, if the timeline is created and then its currentProgress * property is immediately set to 0.5 or if its currentTime property is set to something other than zero, * onStart will still get fired because it is the first time the timeline is getting rendered.)
  • * *
  • onStartParams : Array An Array of parameters to pass the onStart function.
  • * *
  • onUpdate : Function A function that should be called every time the timeline's time/position is updated * (on every frame while the timeline is active)
  • * *
  • onUpdateParams : Array An Array of parameters to pass the onUpdate function
  • * *
  • onComplete : Function A function that should be called when the timeline has finished
  • * *
  • onCompleteParams : Array An Array of parameters to pass the onComplete function
  • * *
  • onReverseComplete : Function A function that should be called when the timeline has reached its starting point again after having been reversed
  • * *
  • onReverseCompleteParams : Array An Array of parameters to pass the onReverseComplete functions
  • * *
  • onRepeat : Function A function that should be called every time the timeline repeats
  • * *
  • onRepeatParams : Array An Array of parameters to pass the onRepeat function
  • * *
  • autoRemoveChildren : Boolean If autoRemoveChildren is set to true, as soon as child tweens/timelines complete, * they will automatically get killed/removed. This is normally undesireable because * it prevents going backwards in time (like if you want to reverse() or set the * currentProgress value to a lower value, etc.). It can, however, improve speed and memory * management. TweenLite's root timelines use autoRemoveChildren:true.
  • * *
  • repeat : int Number of times that the timeline should repeat. To repeat indefinitely, use -1.
  • * *
  • repeatDelay : Number Amount of time in seconds (or frames for frames-based timelines) between repeats.
  • * *
  • yoyo : Boolean Works in conjunction with the repeat property, determining the behavior of each * cycle. When yoyo is true, the timeline will go back and forth, appearing to reverse * every other cycle (this has no affect on the reversed property though). So if repeat is * 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But * if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
  • * *
  • onStartListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it begins. * This is the same as doing myTimeline.addEventListener(TweenEvent.START, myFunction);
  • * *
  • onUpdateListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent every time it * updates values. This is the same as doing myTimeline.addEventListener(TweenEvent.UPDATE, myFunction);
  • * *
  • onCompleteListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it completes. * This is the same as doing myTimeline.addEventListener(TweenEvent.COMPLETE, myFunction);
  • *
* * @param vars optionally pass in special properties like useFrames, onComplete, onCompleteParams, onUpdate, onUpdateParams, onStart, onStartParams, tweens, align, stagger, delay, autoRemoveChildren, onCompleteListener, onStartListener, onUpdateListener, repeat, repeatDelay, and/or yoyo. */ public function TimelineMax(vars:Object=null) { super(vars); _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; _cyclesComplete = 0; this.yoyo = Boolean(this.vars.yoyo == true); this.cacheIsDirty = true; if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } } /** * If you want a function to be called at a particular time or label, use addCallback. When you add * a callback, it is technically considered a zero-duration tween, so if you getChildren() there will be * a tween returned for each callback. You can discern a callback from other tweens by the fact that * their target is a function and the duration is zero. * * @param function the function to be called * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label at which the callback should be inserted. For example, myTimeline.addCallback(myFunction, 3) would call myFunction() 3-seconds into the timeline, and myTimeline.addCallback(myFunction, ""myLabel"") would call it at the ""myLabel"" label. * @param params an Array of parameters to pass the callback * @return TweenLite instance */ public function addCallback(callback:Function, timeOrLabel:*, params:Array=null):TweenLite { var cb:TweenLite = new TweenLite(callback, 0, {onComplete:callback, onCompleteParams:params, overwrite:0, immediateRender:false}); insert(cb, timeOrLabel); return cb; } /** * Removes a callback from a particular time or label. If timeOrLabel is null, all callbacks of that * particular function are removed from the timeline. * * @param function callback function to be removed * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label from which the callback should be removed. For example, myTimeline.removeCallback(myFunction, 3) would remove the callback from 3-seconds into the timeline, and myTimeline.removeCallback(myFunction, ""myLabel"") would remove it from the ""myLabel"" label, and myTimeline.removeCallback(myFunction, null) would remove ALL callbacks of that function regardless of where they are on the timeline. * @return true if any callbacks were successfully found and removed. false otherwise. */ public function removeCallback(callback:Function, timeOrLabel:*=null):Boolean { if (timeOrLabel == null) { return killTweensOf(callback, false); } else { if (typeof(timeOrLabel) == ""string"") { if (!(timeOrLabel in _labels)) { return false; } timeOrLabel = _labels[timeOrLabel]; } var a:Array = getTweensOf(callback, false), success:Boolean; var i:int = a.length; while (--i > -1) { if (a[i].cachedStartTime == timeOrLabel) { remove(a[i] as TweenCore); success = true; } } return success; } } /** * Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops. For * example, to make the TimelineMax play to the ""myLabel2"" label, simply do:

* * myTimeline.tweenTo(""myLabel2"");

* * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween to the 5-second point on the * timeline and then call a function named myFunction and pass in a parameter that's references this * TimelineMax and use a Strong.easeOut ease, you'd do:

* * myTimeline.tweenTo(5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

* * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method.

* * If you plan to sequence multiple playhead tweens one-after-the-other, it is typically better to use * tweenFromTo() so that you can define the starting point and ending point, allowing the * duration to be accurately determined immediately. * * @see #tweenFromTo() * @param timeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(5) would play from wherever the timeline is currently to the 5-second point whereas myTimeline.tweenTo(""myLabel"") would play to wherever ""myLabel"" is on the timeline. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenTo() sets it internally) * @return TweenLite instance that handles tweening the timeline to the desired time/label. */ public function tweenTo(timeOrLabel:*, vars:Object=null):TweenLite { var varsCopy:Object = {ease:easeNone, overwrite:2, useFrames:this.useFrames, immediateRender:false}; for (var p:String in vars) { varsCopy[p] = vars[p]; } varsCopy.onInit = onInitTweenTo; varsCopy.onInitParams = [null, this, NaN]; varsCopy.currentTime = parseTimeOrLabel(timeOrLabel); var tl:TweenLite = new TweenLite(this, (Math.abs(Number(varsCopy.currentTime) - this.cachedTime) / this.cachedTimeScale) || 0.001, varsCopy); tl.vars.onInitParams[0] = tl; return tl; } /** * Creates a linear tween that essentially scrubs the playhead from a particular time or label to another * time or label and then stops. If you plan to sequence multiple playhead tweens one-after-the-other, * tweenFromTo() is better to use than tweenTo() because it allows the duration * to be determined immediately, ensuring that subsequent tweens that are appended to a sequence are * positioned appropriately. For example, to make the TimelineMax play from the label ""myLabel1"" to the ""myLabel2"" * label, and then from ""myLabel2"" back to the beginning (a time of 0), simply do:

* * var playheadTweens:TimelineMax = new TimelineMax();
* playheadTweens.append( myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") );
* playheadTweens.append( myTimeline.tweenFromTo(""myLabel2"", 0);

* * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween from the start (0) to the * 5-second point on the timeline and then call a function named myFunction and pass in a parameter * that's references this TimelineMax and use a Strong.easeOut ease, you'd do:

* * myTimeline.tweenFromTo(0, 5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

* * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenFromTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenFromTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method. * * @see #tweenTo() * @param fromTimeOrLabel The beginning time in seconds (or frame if the timeline is frames-based) or label from which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param toTimeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenFromTo() sets it internally) * @return TweenLite instance that handles tweening the timeline between the desired times/labels. */ public function tweenFromTo(fromTimeOrLabel:*, toTimeOrLabel:*, vars:Object=null):TweenLite { var tl:TweenLite = tweenTo(toTimeOrLabel, vars); tl.vars.onInitParams[2] = parseTimeOrLabel(fromTimeOrLabel); tl.duration = Math.abs(Number(tl.vars.currentTime) - tl.vars.onInitParams[2]) / this.cachedTimeScale; return tl; } /** @private **/ private static function onInitTweenTo(tween:TweenLite, timeline:TimelineMax, fromTime:Number):void { timeline.paused = true; if (!isNaN(fromTime)) { timeline.currentTime = fromTime; } if (tween.vars.currentTime != timeline.currentTime) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. tween.duration = Math.abs(Number(tween.vars.currentTime) - timeline.currentTime) / timeline.cachedTimeScale; } } /** @private **/ private static function easeNone(t:Number, b:Number, c:Number, d:Number):Number { return t / d; } /** @private **/ override public function renderTime(time:Number, suppressEvents:Boolean=false, force:Boolean=false):void { if (this.gc) { this.setEnabled(true, false); } else if (!this.active && !this.cachedPaused) { this.active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. } var totalDur:Number = (this.cacheIsDirty) ? this.totalDuration : this.cachedTotalDuration, prevTime:Number = this.cachedTime, prevTotalTime:Number = this.cachedTotalTime, prevStart:Number = this.cachedStartTime, prevTimeScale:Number = this.cachedTimeScale, tween:TweenCore, isComplete:Boolean, rendered:Boolean, repeated:Boolean, next:TweenCore, dur:Number, prevPaused:Boolean = this.cachedPaused; if (time >= totalDur) { if (_rawPrevTime <= totalDur && _rawPrevTime != time) { this.cachedTotalTime = totalDur; if (!this.cachedReversed && this.yoyo && _repeat % 2 != 0) { this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); } else { this.cachedTime = this.cachedDuration; forceChildrenToEnd(this.cachedDuration, suppressEvents); } isComplete = !this.hasPausedChild(); rendered = true; if (this.cachedDuration == 0 && isComplete && (time == 0 || _rawPrevTime < 0)) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; } } } else if (time <= 0) { if (time < 0) { this.active = false; if (this.cachedDuration == 0 && _rawPrevTime >= 0) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; isComplete = true; } } else if (time == 0 && !this.initted) { force = true; } if (_rawPrevTime >= 0 && _rawPrevTime != time) { this.cachedTotalTime = 0; this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); rendered = true; if (this.cachedReversed) { isComplete = true; } } } else { this.cachedTotalTime = this.cachedTime = time; } _rawPrevTime = time; if (_repeat != 0) { var cycleDuration:Number = this.cachedDuration + _repeatDelay; var prevCycles:int = _cyclesComplete; _cyclesComplete = (this.cachedTotalTime / cycleDuration) >> 0; //rounds result, like int() if (_cyclesComplete == this.cachedTotalTime / cycleDuration) { _cyclesComplete--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } if (prevCycles != _cyclesComplete) { repeated = true; } if (isComplete) { if (this.yoyo && _repeat % 2) { this.cachedTime = 0; } } else if (time > 0) { this.cachedTime = ((this.cachedTotalTime / cycleDuration) - _cyclesComplete) * cycleDuration; //originally this.cachedTotalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!) if (this.yoyo && _cyclesComplete % 2) { this.cachedTime = this.cachedDuration - this.cachedTime; } else if (this.cachedTime >= this.cachedDuration) { this.cachedTime = this.cachedDuration; } if (this.cachedTime < 0) { this.cachedTime = 0; } } else { _cyclesComplete = 0; } if (repeated && !isComplete && (this.cachedTime != prevTime || force)) { /* make sure children at the end/beginning of the timeline are rendered properly. If, for example, a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So we need to push the timeline to the end (and/or beginning depending on its yoyo value). */ var forward:Boolean = Boolean(!this.yoyo || (_cyclesComplete % 2 == 0)); var prevForward:Boolean = Boolean(!this.yoyo || (prevCycles % 2 == 0)); var wrap:Boolean = Boolean(forward == prevForward); if (prevCycles > _cyclesComplete) { prevForward = !prevForward; } if (prevForward) { prevTime = forceChildrenToEnd(this.cachedDuration, suppressEvents); if (wrap) { prevTime = forceChildrenToBeginning(0, true); } } else { prevTime = forceChildrenToBeginning(0, suppressEvents); if (wrap) { prevTime = forceChildrenToEnd(this.cachedDuration, true); } } rendered = false; } } if (this.cachedTotalTime == prevTotalTime && !force) { return; } else if (!this.initted) { this.initted = true; } if (prevTotalTime == 0 && this.cachedTotalTime != 0 && !suppressEvents) { if (this.vars.onStart) { this.vars.onStart.apply(null, this.vars.onStartParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START)); } } if (rendered) { //already rendered, so ignore } else if (this.cachedTime - prevTime > 0) { tween = _firstChild; while (tween) { next = tween.nextNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= this.cachedTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } else { tween = _lastChild; while (tween) { next = tween.prevNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= prevTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } if (_hasUpdate && !suppressEvents) { this.vars.onUpdate.apply(null, this.vars.onUpdateParams); } if (_hasUpdateListener && !suppressEvents) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE)); } if (repeated && !suppressEvents) { if (this.vars.onRepeat) { this.vars.onRepeat.apply(null, this.vars.onRepeatParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REPEAT)); } } if (isComplete && (prevStart == this.cachedStartTime || prevTimeScale != this.cachedTimeScale) && (totalDur >= this.totalDuration || this.cachedTime == 0)) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline) or if it added more tweens to the timeline, we shouldn't run complete() because it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would have called complete() if it was necessary at the new time. The only exception is the timeScale property. complete(true, suppressEvents); } } /** * Forces the timeline to completion. * * @param skipRender to skip rendering the final state of the timeline, set skipRender to true. * @param suppressEvents If true, no events or callbacks will be triggered for this render (like onComplete, onUpdate, onReverseComplete, etc.) */ override public function complete(skipRender:Boolean=false, suppressEvents:Boolean=false):void { super.complete(skipRender, suppressEvents); if (_dispatcher && !suppressEvents) { if (this.cachedReversed && this.cachedTotalTime == 0 && this.cachedDuration != 0) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REVERSE_COMPLETE)); } else { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE)); } } } /** * Returns the tweens/timelines that are currently active in the timeline. * * @param nested determines whether or not tweens and/or timelines that are inside nested timelines should be returned. If you only want the ""top level"" tweens/timelines, set this to false. * @param tweens determines whether or not tweens (TweenLite and TweenMax instances) should be included in the results * @param timelines determines whether or not timelines (TimelineLite and TimelineMax instances) should be included in the results * @return an Array of active tweens/timelines */ public function getActive(nested:Boolean=true, tweens:Boolean=true, timelines:Boolean=false):Array { var a:Array = [], all:Array = getChildren(nested, tweens, timelines), i:int, tween:TweenCore; var l:int = all.length; var cnt:int = 0; for (i = 0; i < l; i += 1) { tween = all[i]; //note: we cannot just check tween.active because timelines that contain paused children will continue to have ""active"" set to true even after the playhead passes their end point (technically a timeline can only be considered complete after all of its children have completed too, but paused tweens are...well...just waiting and until they're unpaused we don't know where their end point will be). if (!tween.cachedPaused && tween.timeline.cachedTotalTime >= tween.cachedStartTime && tween.timeline.cachedTotalTime < tween.cachedStartTime + tween.cachedTotalDuration / tween.cachedTimeScale && !OverwriteManager.getGlobalPaused(tween.timeline)) { a[cnt++] = all[i]; } } return a; } /** @inheritDoc **/ override public function invalidate():void { _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; this.yoyo = Boolean(this.vars.yoyo == true); if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } setDirtyCache(true); super.invalidate(); } /** * Returns the next label (if any) that occurs AFTER the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time after which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is after the time passed to getLabelAfter() */ public function getLabelAfter(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var l:int = labels.length; for (var i:int = 0; i < l; i += 1) { if (labels[i].time > time) { return labels[i].name; } } return null; } /** * Returns the previous label (if any) that occurs BEFORE the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time before which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is before the time passed to getLabelBefore() */ public function getLabelBefore(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var i:int = labels.length; while (--i > -1) { if (labels[i].time < time) { return labels[i].name; } } return null; } /** @private Returns an Array of label objects, each with a ""time"" and ""name"" property, in the order that they occur in the timeline. **/ protected function getLabelsArray():Array { var a:Array = []; for (var p:String in _labels) { a[a.length] = {time:_labels[p], name:p}; } a.sortOn(""time"", Array.NUMERIC); return a; } //---- EVENT DISPATCHING ---------------------------------------------------------------------------------------------------------- /** @private **/ protected function initDispatcher():void { if (_dispatcher == null) { _dispatcher = new EventDispatcher(this); } if (this.vars.onStartListener is Function) { _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true); } if (this.vars.onUpdateListener is Function) { _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true); _hasUpdateListener = true; } if (this.vars.onCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true); } if (this.vars.onRepeatListener is Function) { _dispatcher.addEventListener(TweenEvent.REPEAT, this.vars.onRepeatListener, false, 0, true); } if (this.vars.onReverseCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.REVERSE_COMPLETE, this.vars.onReverseCompleteListener, false, 0, true); } } /** @private **/ public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { if (_dispatcher == null) { initDispatcher(); } if (type == TweenEvent.UPDATE) { _hasUpdateListener = true; } _dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** @private **/ public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { if (_dispatcher != null) { _dispatcher.removeEventListener(type, listener, useCapture); } } /** @private **/ public function hasEventListener(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.hasEventListener(type); } /** @private **/ public function willTrigger(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.willTrigger(type); } /** @private **/ public function dispatchEvent(e:Event):Boolean { return (_dispatcher == null) ? false : _dispatcher.dispatchEvent(e); } //---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- /** * Value between 0 and 1 indicating the overall progress of the timeline according to its totalDuration * where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished. currentProgress, * by contrast, describes the progress according to the timeline's duration which does not * include repeats and repeatDelays. For example, if a TimelineMax instance is set * to repeat once, at the end of the first cycle totalProgress would only be 0.5 * whereas currentProgress would be 1. If you tracked both properties over the course of the * tween, you'd see currentProgress go from 0 to 1 twice (once for each cycle) in the same * time it takes the totalProgress property to go from 0 to 1 once. **/ public function get totalProgress():Number { return this.cachedTotalTime / this.totalDuration; } public function set totalProgress(n:Number):void { setTotalTime(this.totalDuration * n, false); } /** * Duration of the timeline in seconds (or frames for frames-based timelines) including any repeats * or repeatDelays. ""duration"", by contrast, does NOT include repeats and repeatDelays. **/ override public function get totalDuration():Number { if (this.cacheIsDirty) { var temp:Number = super.totalDuration; //just forces refresh //Instead of Infinity, we use 999999999999 so that we can accommodate reverses. this.cachedTotalDuration = (_repeat == -1) ? 999999999999 : this.cachedDuration * (_repeat + 1) + (_repeatDelay * _repeat); } return this.cachedTotalDuration; } /** @private **/ override public function set currentTime(n:Number):void { if (_cyclesComplete == 0) { setTotalTime(n, false); } else if (this.yoyo && (_cyclesComplete % 2 == 1)) { setTotalTime((this.duration - n) + (_cyclesComplete * (this.cachedDuration + _repeatDelay)), false); } else { setTotalTime(n + (_cyclesComplete * (this.duration + _repeatDelay)), false); } } /** Number of times that the timeline should repeat; -1 repeats indefinitely. **/ public function get repeat():int { return _repeat; } public function set repeat(n:int):void { _repeat = n; setDirtyCache(true); } /** Amount of time in seconds (or frames for frames-based timelines) between repeats **/ public function get repeatDelay():Number { return _repeatDelay; } public function set repeatDelay(n:Number):void { _repeatDelay = n; setDirtyCache(true); } /** The closest label that is at or before the current time. **/ public function get currentLabel():String { return getLabelBefore(this.cachedTime + 0.00000001); } } }",12270,False,2079.664735215009,median "/* * HazeL * Benjamin Y. Brown */ #include #include #include ""HM3301.h"" // Make sure you have these five libraries installed in Documents/Arduino/libraries #include #include #include #include #include ""SdFat.h"" #include #include #include #include ""Seeed_BMP280.h"" #define SAMP_TIME 2500 // number of ms between sensor readings #define BLINK_TIME 30 // time in ms between LED blinks on successful write to SD #define GPS_TIME 10000 // time between GPS reads #define GPS_TIMEOUT 5000 // number of ms before GPS read times out #define GPS_FIRST_TIMEOUT 600000 // number of ms before first GPS read times out #define BLINK_CNT 3 // number of times to blink LED on successful write #define SD_CS_PIN 4 // CS pin of SD card, 4 on SD MKR proto shield #define CUR_YEAR 2022 // for GPS first fix error checking #define OLED_RESET -1 #define SCREEN_ADDRESS 0x3D #define SCREEN_WIDTH 128 #define SCREEN_HEIGHT 128 #define ENC_RIGHT_BUTTON A1 #define ENC_RIGHT_A 0 #define ENC_RIGHT_B 1 #define ENC_LEFT_BUTTON A2 #define ENC_LEFT_A 5 #define ENC_LEFT_B 7 #define MENU_UPDATE_TIME 100 // milliseconds between menu updates // #define DEBUG_PRINT HM3301 dustSensor; BMP280 TPSensor; SdFat SD; File dataFile; File metaFile; char dataFileName[23]; // YYMMDD_HHMMSS_data.txt char metaFileName[23]; // YYMMDD_HHMMSS_meta.txt char * fileList; // list of files on SD card uint32_t fileCount = 0; // number of files on SD card char fileToUpload[30]; TinyGPSPlus gps; bool timestampFlag = false; bool gpsAwake = true; bool gpsDisplayFail = false; int utcYear; int utcMonth; int utcDay; int utcHour; int utcMinute; int utcSecond; double latitude; double longitude; double altitude; time_t prevTimeStamp = 0; uint8_t manualMonth = 1; uint8_t manualDay = 1; uint16_t manualYear = CUR_YEAR; uint8_t manualHour = 0; uint8_t manualMinute = 0; bool manualTimeEntry = false; // false means use GPS bool rtcSet = false; // flag to indicate if RTC is set or not RTCZero rtc; Adafruit_SSD1327 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); Encoder encRight(ENC_RIGHT_B, ENC_RIGHT_A); Encoder encLeft(ENC_LEFT_B, ENC_LEFT_A); long encRightOldPosition = 0; long encLeftOldPosition = 0; unsigned long prevSampMillis = 0; unsigned long prevLedMillis = 0; unsigned long prevGpsMillis = 0; unsigned long prevMenuMillis = 0; unsigned long dataStartMillis = 0; // millis() when data collection began unsigned long curMillis; volatile bool encRightButtonFlag = false; volatile bool encRightButtonISREn = false; volatile bool encLeftButtonFlag = false; volatile bool encLeftButtonISREn = false; bool ledFlag = false; uint8_t ledCount = 0; bool firstMeasurementFlag = false; // state = 0 navigating menu // state = 2 collecting data // state = 3 uploading data uint8_t state = 0; uint8_t prevState = 0; // page = 0 two choice menu, collect data and upload data // page = 1 time entry choice menu -> two choices enter timestamp or get from GPS // page = 2 entering date // page = 3 entering time // page = 4 viewing SD card files // page = 5 data collection screen uint8_t page = 0; uint8_t prevPage = 0; int16_t currentVertMenuSelection = 0; int16_t currentHoriMenuSelection = 0; int16_t prevVertMenuSelection = 0; uint8_t scroll = 0; // count number of times SD page has been scrolled void setup() { // initialize Serial port Serial.begin(115200); // intialize comms with GPS module Serial1.begin(9600); // Initialize I2C bus Wire.begin(); // Initialize comms with OLED display display.begin(SCREEN_ADDRESS); display.clearDisplay(); updateDisplay(""Initializing..."", 40, false); display.display(); delay(2500); #ifdef DEBUG_PRINT Serial.println(""Initializing...""); #endif // Set relevant pin modes pinMode(LED_BUILTIN, OUTPUT); pinMode(SD_CS_PIN, OUTPUT); pinMode(ENC_RIGHT_BUTTON, INPUT_PULLUP); pinMode(ENC_LEFT_BUTTON, INPUT_PULLUP); #ifdef DEBUG_PRINT Serial.println(""Initialize SD""); #endif display.clearDisplay(); updateDisplay(""Checking SD"", 40, false); display.display(); delay(2500); // Initialize SD card communication if(!SD.begin(SD_CS_PIN)) { #ifdef DEBUG_PRINT Serial.println(""Card failed""); #endif display.clearDisplay(); updateDisplay(""SD card failed"", 32, false); updateDisplay(""Reset device"", 48, false); display.display(); while(true); } else { #ifdef DEBUG_PRINT Serial.println(""Card initialized successfully""); #endif display.clearDisplay(); updateDisplay(""SD card detected"", 40, false); display.display(); } delay(2500); // Initialize dust sensor if(!dustSensor.begin()) { #ifdef DEBUG_PRINT Serial.println(""Failed to initialize dust sensor""); #endif display.clearDisplay(); updateDisplay(""Dust sensor init failed"", 32, false); updateDisplay(""Reset device"", 48, false); display.display(); while(true); } TPSensor.init(); // Put GPS to sleep to start if(gpsAwake) { toggleGps(); } // Begin RTC rtc.begin(); // Attach ISR for flipping buttonFlag when button is pressed attachInterrupt(digitalPinToInterrupt(ENC_RIGHT_BUTTON), encRightButtonISR, FALLING); attachInterrupt(digitalPinToInterrupt(ENC_LEFT_BUTTON), encLeftButtonISR, FALLING); // enable button ISR encRightButtonISREn = true; encLeftButtonISREn = true; // set initial state to menu navigation state = 0; } void loop() { // check number of milliseconds since Arduino was turned on curMillis = millis(); // display the current page displayPage(page); if(state == 0) // Navigating menus { // update the current menu selection updateMenuSelection(); if(encRightButtonFlag) // select button has been pressed { if(page == 0) // initial menu { if(currentVertMenuSelection == 0) { page = 1; // go to time entry choice page } else if(currentVertMenuSelection == 1) // upload data { prevState = state; page = 4; // go to page for viewing SD card files scroll = 0; // start at the beginning of the file list #ifdef DEBUG_PRINT Serial.println(""\\nSD card contents from SD.ls():""); SD.ls(LS_R); Serial.println(); #endif // First count files on SD card #ifdef DEBUG_PRINT Serial.println(""\\nCounting files on SD card""); #endif File file; File root; fileCount = 0; if(!root.open(""/"")) { #ifdef DEBUG_PRINT Serial.println(""Error opening root""); #endif // TODO: figure out how to handle this error } while(file.openNext(&root, O_RDONLY)) { if(!file.isHidden()) { fileCount++; #ifdef DEBUG_PRINT file.printName(&Serial); Serial.print('\\t'); Serial.println(fileCount); #endif } file.close(); } root.rewind(); #ifdef DEBUG_PRINT Serial.print(""\\nFile count: ""); Serial.println(fileCount); #endif // now create an array of file names char filesOnSd[fileCount][30]; // Each file name should be at most 22 characters long uint32_t curFile = 0; while(file.openNext(&root, O_RDONLY)) { if(!file.isHidden()) { char fileName[30] = {0}; file.getName(fileName, sizeof(fileName)); char shortenedFileName[30] = {0}; memcpy(shortenedFileName, fileName, strlen(fileName) - 4); // everything but the file extension "".txt"" (to fit on screen) strcpy(filesOnSd[curFile], shortenedFileName); curFile++; } file.close(); } root.rewind(); #ifdef DEBUG_PRINT Serial.println(""\\nList of files created (pre-sort):""); for(int i = 0; i < fileCount; ++i) { Serial.println(filesOnSd[i]); } #endif // Sort filesOnSd alphabetically qsort(filesOnSd, fileCount, 30, cmpstr); #ifdef DEBUG_PRINT Serial.println(""\\nList of files created:""); for(int i = 0; i < fileCount; ++i) { Serial.println(filesOnSd[i]); } #endif root.close(); // copy contents fo fileList memory location // free()'d when the upload menu is left with the back button fileList = (char *)malloc(sizeof(filesOnSd)); memcpy(fileList, filesOnSd, sizeof(filesOnSd)); } } else if (page == 1) // time entry method { if(currentVertMenuSelection == 0) // Use GPS for time stamp { manualTimeEntry = false; createDataFiles(); // create the names for the data and gps files for data collection // State and page are set from within createDataFiles() so that I can set it to different things on success and failure } else if(currentVertMenuSelection == 1) // Use manual entry + RTC { page = 2; // enter date if(rtcSet) { manualDay = rtc.getDay(); manualHour = rtc.getHours(); manualMinute = rtc.getMinutes(); manualMonth = rtc.getMonth(); manualYear = rtc.getYear(); } } } else if (page == 2) { page = 3; // enter time } else if (page == 3) { #ifdef DEBUG_PRINT Serial.print(""Timestamp set as: ""); Serial.print(manualMonth); Serial.print('/'); Serial.print(manualDay); Serial.print('/'); Serial.print(manualYear); Serial.print(' '); if(manualHour < 10) Serial.print('0'); Serial.print(manualHour); Serial.print(':'); if(manualMinute < 10) Serial.print('0'); Serial.println(manualMinute); #endif // set RTC rtc.setDate(manualDay, manualMonth, manualYear % 100); // year is saved as an offset from 2000 rtc.setTime(manualHour, manualMinute, 0); if(!rtcSet) rtcSet = true; manualTimeEntry = true; // flag to indicate that RTC is being used for time stamps, not GPS createDataFiles(); // State and page are set from within createDataFiles() so that I can set it to different things on success and failure } else if(page == 4) { // save fileToUpload before uploadSerial is called on it memcpy(fileToUpload, fileList + currentVertMenuSelection*30, sizeof(fileToUpload)); prevState = state; state = 3; } // reset menus for next page if(page == 2) currentVertMenuSelection = manualMonth - 1; else if(page == 3) currentVertMenuSelection = manualHour; else if(page == 4) currentVertMenuSelection = currentVertMenuSelection; // known minor bug here where upon first entering this page the cursor will be on the second selection else currentVertMenuSelection = 0; currentHoriMenuSelection = 0; encRightButtonFlag = false; encRightButtonISREn = true; } } else if(state == 2) // Collecting data { // Blink LED upon successful SD write if(ledFlag) { if(curMillis - prevLedMillis >= BLINK_TIME) { prevLedMillis = curMillis; blinkLed(); } } // Read sensor and update SD card every SAMP_TIME milliseconds if(curMillis - prevSampMillis >= SAMP_TIME) { prevSampMillis = curMillis; if(curMillis - prevGpsMillis >= GPS_TIME) { timestampFlag = true; prevGpsMillis = curMillis; } updateSampleSD(); } } else if(state == 3) // uploading data { uploadSerial(fileToUpload); state = prevState; prevState = 3; page = 4; // go back to file list } if(encLeftButtonFlag) // back button has been pressed { switch(page) { case 1: // time entry choice menu page = 0; // go back to initial menu prevState = state; state = 0; break; case 2: // date entry page page = 1; // go back to time entry choice menu prevState = state; state = 0; break; case 3: // time entry page page = 2; // go back to date entry page prevState = state; state = 0; break; case 4: // SD card file list menu page = 0; // go back to initial menu prevState = state; state = 0; #ifdef DEBUG_PRINT Serial.println(""free()'ing fileList""); #endif free(fileList); // deallocate memory for list of SD card files scroll = 0; break; case 5: // data collection screen page = 1; // go back to time entry choice menu prevState = state; state = 0; break; } // reset menus for next page if(page == 2) currentVertMenuSelection = manualMonth - 1; else if(page == 3) currentVertMenuSelection = manualHour; else currentVertMenuSelection = 0; encLeftButtonFlag = false; encLeftButtonISREn = true; #ifdef DEBUG_PRINT Serial.println(""Back button pressed""); Serial.print(""Going to page: ""); Serial.println(page); #endif } } // ISR for button being pressed void encRightButtonISR() { if(encRightButtonISREn == true) { encRightButtonFlag = true; encRightButtonISREn = false; } } void encLeftButtonISR() { if(encLeftButtonISREn == true) { encLeftButtonFlag = true; encLeftButtonISREn = false; } } // update samples in SD card void updateSampleSD() { bool timeoutFlag = false; time_t utcTime; unsigned long msTimer; if(firstMeasurementFlag) { firstMeasurementFlag = false; msTimer = 0; dataStartMillis = millis(); } else { msTimer = millis() - dataStartMillis; } BMP280_temp_t temp; BMP280_press_t press; if(timestampFlag) // if it is time to get a time stamp { // read temperature and pressure temp = TPSensor.getTemperature(); press = TPSensor.getPressure(); // If you chose to use GPS, keep getting time, lat, long, and alt fom GPS if(!manualTimeEntry) { display.clearDisplay(); display.drawLine(0, display.height()-10, display.width()-1, display.height()-10, SSD1327_WHITE); display.drawLine(display.width()/2 - 1, display.height()-10, display.width()/2 - 1, display.height()-1, SSD1327_WHITE); display.setTextColor(SSD1327_WHITE); display.setCursor(10, display.height()-8); display.print(""Back ""); updateDisplay(""Reading GPS..."", 40, false); display.display(); // wake up GPS module if (!gpsAwake) { toggleGps(); } unsigned long gpsReadCurMillis; unsigned long gpsReadStartMillis = millis(); unsigned long gpsTimeoutMillis = GPS_TIMEOUT; #ifdef DEBUG_PRINT unsigned long preRead = millis(); #endif // Read GPS data until it's valid // 5 second timeout while (true) { gpsReadCurMillis = millis(); readGps(); if (gpsReadCurMillis - gpsReadStartMillis >= gpsTimeoutMillis) { timeoutFlag = true; gpsDisplayFail = true; #ifdef DEBUG_PRINT Serial.println(""GPS timeout""); #endif break; } if (gps.date.isValid() && gps.time.isValid() && gps.location.isValid() && gps.altitude.isValid() && gps.date.year() == CUR_YEAR) { #ifdef DEBUG_PRINT Serial.println(""GPS data valid""); #endif // set time for now() setTime(gps.time.hour(), gps.time.minute(), gps.time.second(), gps.date.day(), gps.date.month(), gps.date.year()); // check for stale GPS timestamps if (now() > prevTimeStamp) { prevTimeStamp = now(); gpsDisplayFail = false; // resync RTC every successful GPS read rtc.setDate(gps.date.day(), gps.date.month(), gps.date.year() % 100); rtc.setTime(gps.time.hour(), gps.time.minute(), gps.time.second()); if(!rtcSet) rtcSet = true; break; } #ifdef DEBUG_PRINT else { Serial.println(""Stale timestamp, continuing GPS read""); } #endif } // make GPS reads interruptible by the button being pressed if (encLeftButtonFlag) { // Put GPS to sleep if (gpsAwake) { toggleGps(); } // TODO: test if this returns to the proper page return; } } #ifdef DEBUG_PRINT unsigned long postRead = millis(); Serial.print(""GPS read took: ""); Serial.print(postRead - preRead); Serial.println("" ms""); #endif // store UTC time utcTime = now(); latitude = gps.location.lat(); longitude = gps.location.lng(); altitude = gps.altitude.meters(); // put GPS to sleep if (gpsAwake) { toggleGps(); if (timeoutFlag) { delay(500); // add extra delay after timeout to make sure sleep command is properly interpreted before next read } } // store time from GPS utcYear = year(utcTime); utcMonth = month(utcTime); utcDay = day(utcTime); utcHour = hour(utcTime); utcMinute = minute(utcTime); utcSecond = second(utcTime); } if(manualTimeEntry || timeoutFlag) // if manual time entry or GPS timed out, overwrite timestamp with RTC values { utcYear = rtc.getYear() + 2000; // RTC year is stored as an offset from 2000 utcMonth = rtc.getMonth(); utcDay = rtc.getDay(); utcHour = rtc.getHours(); utcMinute = rtc.getMinutes(); utcSecond = rtc.getSeconds(); } metaFile = SD.open(metaFileName, FILE_WRITE); if(metaFile) { Serial.print(""# ""); Serial.print(msTimer); Serial.print(','); Serial.print(utcYear); Serial.print('-'); Serial.print(utcMonth); Serial.print('-'); Serial.print(utcDay); Serial.print('T'); if(utcHour < 10) Serial.print('0'); Serial.print(utcHour); Serial.print(':') ; if(utcMinute < 10) Serial.print('0'); Serial.print(utcMinute); Serial.print(':'); if(utcSecond < 10) Serial.print('0'); Serial.print(utcSecond); Serial.print(""+00:00""); metaFile.print(msTimer); metaFile.print(','); metaFile.print(utcYear); metaFile.print('-'); metaFile.print(utcMonth); metaFile.print('-'); metaFile.print(utcDay); metaFile.print('T'); if(utcHour < 10) metaFile.print('0'); metaFile.print(utcHour); metaFile.print(':') ; if(utcMinute < 10) metaFile.print('0'); metaFile.print(utcMinute); metaFile.print(':'); if(utcSecond < 10) metaFile.print('0'); metaFile.print(utcSecond); metaFile.print(""+00:00""); // do not report lat, long, alt if(manualTimeEntry || timeoutFlag) { Serial.print("",,,""); metaFile.print("",,,""); } else { Serial.print(','); Serial.print(latitude); Serial.print(','); Serial.print(longitude); Serial.print(','); Serial.print(altitude); metaFile.print(','); metaFile.print(latitude); metaFile.print(','); metaFile.print(longitude); metaFile.print(','); metaFile.print(altitude); } Serial.print(','); Serial.print(temp.integral); Serial.print('.'); Serial.print(temp.fractional); Serial.print(','); Serial.print(press.integral); Serial.print('.'); Serial.println(press.fractional); metaFile.print(','); metaFile.print(temp.integral); metaFile.print('.'); metaFile.print(temp.fractional); metaFile.print(','); metaFile.print(press.integral); metaFile.print('.'); metaFile.print(press.fractional); metaFile.print('\\n'); metaFile.close(); } else { #ifdef DEBUG_PRINT Serial.println(""Couldn't open gps file""); #endif display.clearDisplay(); updateDisplay(""Couldn't open GPS file"", 40, false); display.display(); delay(500); } } // Read dust sensor while(!dustSensor.read()) { #ifdef DEBUG_PRINT Serial.println(""Sensor reading didn't work, trying again""); #endif } uint16_t PM1p0_std = dustSensor.data.PM1p0_std; uint16_t PM2p5_std = dustSensor.data.PM2p5_std; uint16_t PM10p0_std = dustSensor.data.PM10p0_std; uint16_t PM1p0_atm = dustSensor.data.PM1p0_atm; uint16_t PM2p5_atm = dustSensor.data.PM2p5_atm; uint16_t PM10p0_atm = dustSensor.data.PM10p0_atm; uint16_t count_0p3um = dustSensor.data.count_0p3um; uint16_t count_0p5um = dustSensor.data.count_0p5um; uint16_t count_1p0um = dustSensor.data.count_1p0um; uint16_t count_2p5um = dustSensor.data.count_2p5um; uint16_t count_5p0um = dustSensor.data.count_5p0um; uint16_t count_10p0um = dustSensor.data.count_10p0um; // Display data to serial monitor and OLED display // Store data on SD card dataFile = SD.open(dataFileName, FILE_WRITE); if(dataFile) { // Get timestamp from RTC utcYear = rtc.getYear() + 2000; // RTC year is stored as an offset from 2000 utcMonth = rtc.getMonth(); utcDay = rtc.getDay(); utcHour = rtc.getHours(); utcMinute = rtc.getMinutes(); utcSecond = rtc.getSeconds(); // Display data in the serial monitor Serial.print(msTimer); Serial.print(','); Serial.print(utcYear); Serial.print('-'); Serial.print(utcMonth); Serial.print('-'); Serial.print(utcDay); Serial.print('T'); if(utcHour < 10) Serial.print('0'); Serial.print(utcHour); Serial.print(':') ; if(utcMinute < 10) Serial.print('0'); Serial.print(utcMinute); Serial.print(':'); if(utcSecond < 10) Serial.print('0'); Serial.print(utcSecond); Serial.print(""+00:00""); Serial.print(','); Serial.print(PM1p0_atm); Serial.print(','); Serial.print(PM2p5_atm); Serial.print(','); Serial.print(PM10p0_atm); Serial.print(','); Serial.print(count_0p3um); Serial.print(','); Serial.print(count_0p5um); Serial.print(','); Serial.print(count_1p0um); Serial.print(','); Serial.print(count_2p5um); Serial.print(','); Serial.print(count_5p0um); Serial.print(','); Serial.println(count_10p0um); dataFile.print(msTimer); dataFile.print(','); dataFile.print(utcYear); dataFile.print('-'); dataFile.print(utcMonth); dataFile.print('-'); dataFile.print(utcDay); dataFile.print('T'); if(utcHour < 10) dataFile.print('0'); dataFile.print(utcHour); dataFile.print(':') ; if(utcMinute < 10) dataFile.print('0'); dataFile.print(utcMinute); dataFile.print(':'); if(utcSecond < 10) dataFile.print('0'); dataFile.print(utcSecond); dataFile.print(""+00:00""); dataFile.print("",""); dataFile.print(PM1p0_atm); // PM1.0 (atmo) dataFile.print("",""); dataFile.print(PM2p5_atm); // PM2.5 (atmo) dataFile.print("",""); dataFile.print(PM10p0_atm); // PM10.0 (atmo) dataFile.print("",""); dataFile.print(count_0p3um); // >0.3um dataFile.print("",""); dataFile.print(count_0p5um); // >0.5um dataFile.print("",""); dataFile.print(count_1p0um); // >1.0um dataFile.print("",""); dataFile.print(count_2p5um); // >2.5um dataFile.print("",""); dataFile.print(count_5p0um); // >5.0um dataFile.print("",""); dataFile.print(count_10p0um); // >10.0um dataFile.print('\\n'); dataFile.close(); ledFlag = true; } else { #ifdef DEBUG_PRINT Serial.println(""Couldn't open file""); #endif display.clearDisplay(); updateDisplay(""Couldn't open data file"", 40, false); display.display(); delay(500); } if(timestampFlag) { timestampFlag = false; } } // upload SD card data over serial port void uploadSerial(char * fileName) { // disable button ISRs encRightButtonISREn = false; encLeftButtonISREn = false; uint8_t buffer[512] = {0}; // buffer to read/write data 512 bytes at a time uint16_t writeLen = sizeof(buffer); display.clearDisplay(); updateDisplay(""Uploading "", 40, false); updateDisplay(fileName, 48, false); updateDisplay(""via serial port"", 56, false); display.display(); char fileNameExtension[30]; strcpy(fileNameExtension, fileName); strcat(fileNameExtension, "".txt""); #ifdef DEBUG_PRINT Serial.println(""Serial upload initiated""); Serial.print(""Uploading: ""); #endif // Send file name as first line to be captured, download scripts will use this to name the file Serial.print(fileNameExtension); Serial.print('\\n'); File file = SD.open(fileNameExtension, FILE_READ); while(file.available()) { if (file.available() > sizeof(buffer)) { writeLen = sizeof(buffer); file.read(buffer, sizeof(buffer)); } else { writeLen = file.available(); file.read(buffer, file.available()); } Serial.write(buffer, writeLen); memset(buffer, 0, sizeof(buffer)); } file.close(); delay(2500); encRightButtonISREn = true; encLeftButtonISREn = true; } // blink LED void blinkLed() { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); if(++ledCount >= BLINK_CNT*2) { ledFlag = false; ledCount = 0; } } // read GPS module and encode data void readGps() { while(Serial1.available() > 0) { if(gps.encode(Serial1.read())) { #ifdef DEBUG_PRINT // Serial.println(""GPS data successfully encoded""); #endif } } } // toggle GPS between sleep and wake void toggleGps() { sendGpsCommand(""051,0""); delay(100); gpsAwake = !gpsAwake; #ifdef DEBUG_PRINT if (gpsAwake) { Serial.println(""GPS awake""); } else { Serial.println(""GPS asleep""); } #endif } // send GPS command void sendGpsCommand(const char* cmd) { char cmdBase[] = ""PGKC""; char* finalCmd = strcat(cmdBase, cmd); // data between the $ and * - on which checksum is based char checksum = createChecksum(finalCmd); Serial1.write('$'); Serial1.write(finalCmd); Serial1.write('*'); Serial1.print(checksum, HEX); Serial1.write(""\\r\\n""); #ifdef DEBUG_PRINT Serial.print(""Command sent to GPS: ""); Serial.write('$'); Serial.write(finalCmd); Serial.write('*'); Serial.print(checksum, HEX); Serial.write(""\\r\\n""); #endif } // create a checksum for GPS command char createChecksum(char* cmd) { char checksum = 0; for(int i = 0; i < strlen(cmd); i++) { checksum = checksum ^ cmd[i]; } return checksum; } // Create two data files, one for GPS and one for dust data void createDataFiles() { // reset current file names memset(dataFileName, 0, sizeof(dataFileName)); memset(metaFileName, 0, sizeof(metaFileName)); int year; int month; int day; int hour; int minutes; int seconds; // strings to concatenate into file names char yearStr[3]; char monthStr[3]; char dayStr[3]; char hourStr[3]; char minutesStr[3]; char secondsStr[3]; char baseString[15]; // YYMMDD_HHMMSS_ if(!manualTimeEntry) { // get time stamp from GPS, set RTC unsigned long gpsReadCurMillis; unsigned long gpsReadStartMillis = millis(); unsigned long gpsTimeoutMillis = GPS_FIRST_TIMEOUT; display.clearDisplay(); display.drawLine(0, display.height()-10, display.width()-1, display.height()-10, SSD1327_WHITE); display.drawLine(display.width()/2 - 1, display.height()-10, display.width()/2 - 1, display.height()-1, SSD1327_WHITE); display.setTextColor(SSD1327_WHITE); display.setCursor(10, display.height()-8); display.print(""Back ""); updateDisplay(""Reading GPS..."", 40, false); updateDisplay(""(First GPS read"", 56, false); updateDisplay(""may take a"", 64, false); updateDisplay(""few minutes)"", 72, false); display.display(); if(!gpsAwake) { toggleGps(); } while (true) { gpsReadCurMillis = millis(); readGps(); if (gpsReadCurMillis - gpsReadStartMillis >= gpsTimeoutMillis) { // timeoutFlag = true; gpsDisplayFail = true; #ifdef DEBUG_PRINT Serial.println(""GPS timeout""); #endif display.clearDisplay(); display.drawLine(0, display.height()-10, display.width()-1, display.height()-10, SSD1327_WHITE); display.drawLine(display.width()/2 - 1, display.height()-10, display.width()/2 - 1, display.height()-1, SSD1327_WHITE); display.setTextColor(SSD1327_WHITE); display.setCursor(10, display.height()-8); display.print(""Back ""); updateDisplay(""GPS read failed"", 40, false); updateDisplay(""Please enter time"", 56, false); updateDisplay(""manually"", 64, false); display.display(); // turn off GPS if(gpsAwake) { toggleGps(); } while(!encLeftButtonFlag); // wait for back button to be pressed encLeftButtonFlag = false; encLeftButtonISREn = true; prevState = state; state = 0; page = 1; return; } if (gps.date.isValid() && gps.time.isValid() && gps.location.isValid() && gps.altitude.isValid() && gps.date.year() == CUR_YEAR) { #ifdef DEBUG_PRINT Serial.println(""GPS data valid""); #endif // set time for now() // setTime(gps.time.hour(), gps.time.minute(), gps.time.second(), gps.date.day(), gps.date.month(), gps.date.year()); // prevTimeStamp = now(); // GPS data is valid, set RTC rtc.setDay(gps.date.day()); rtc.setMonth(gps.date.month()); rtc.setYear(gps.date.year() % 100); rtc.setHours(gps.time.hour()); rtc.setMinutes(gps.time.minute()); rtc.setSeconds(gps.time.second()); if(!rtcSet) rtcSet = true; break; } // make GPS reads interruptible by the button being pressed if (encLeftButtonFlag) { // Put GPS to sleep if (gpsAwake) { toggleGps(); } page = 1; // go back to time entry choice menu prevState = state; state = 0; encLeftButtonFlag = false; encLeftButtonISREn = true; return; } } } // put GPS to sleep if it's woken up if(gpsAwake) { toggleGps(); } // RTC clock should be set (whether manually or with GPS) year = rtc.getYear(); month = rtc.getMonth(); day = rtc.getDay(); hour = rtc.getHours(); minutes = rtc.getMinutes(); seconds = rtc.getSeconds(); itoa(year, yearStr, 10); itoa(month, monthStr, 10); itoa(day, dayStr, 10); itoa(hour, hourStr, 10); itoa(minutes, minutesStr, 10); itoa(seconds, secondsStr, 10); #ifdef DEBUG_PRINT Serial.print(monthStr); Serial.print('/'); Serial.print(dayStr); Serial.print('/'); Serial.print(yearStr); Serial.print(' '); Serial.print(hourStr); Serial.print(':'); Serial.print(minutesStr); Serial.print(':'); Serial.println(secondsStr); #endif strcpy(baseString, yearStr); if(month < 10) strcat(baseString, ""0""); strcat(baseString, monthStr); if(day < 10) strcat(baseString, ""0""); strcat(baseString, dayStr); strcat(baseString, ""_""); if(hour < 10) strcat(baseString, ""0""); strcat(baseString, hourStr); if(minutes < 10) strcat(baseString, ""0""); strcat(baseString, minutesStr); if(seconds < 10) strcat(baseString, ""0""); strcat(baseString, secondsStr); strcpy(dataFileName, baseString); strcpy(metaFileName, baseString); strcat(dataFileName, ""_data.txt""); strcat(metaFileName, ""_meta.txt""); #ifdef DEBUG_PRINT Serial.print(""dataFileName: ""); Serial.println(dataFileName); Serial.print(""metaFileName: ""); Serial.println(metaFileName); #endif File newFile; // Create column headers for new data file if(!SD.exists(dataFileName)) { #ifdef DEBUG_PRINT Serial.println(""Writing column headers for new data file""); #endif newFile = SD.open(dataFileName, FILE_WRITE); if(newFile) { #ifdef DEBUG_PRINT Serial.print(""ms,UTC_timestamp,PM1.0,PM2.5,PM10.0,0.3um,0.5um,1.0um,2.5um,5.0um,10.0um""); #endif newFile.print(""ms,UTC_timestamp,PM1.0,PM2.5,PM10.0,0.3um,0.5um,1.0um,2.5um,5.0um,10.0um\\n""); } else { #ifdef DEBUG_PRINT Serial.println(""Couldn't open data file""); #endif } newFile.close(); } // Create column headers for new data file if(!SD.exists(metaFileName)) { #ifdef DEBUG_PRINT Serial.println(""Writing column headers for new data file""); #endif newFile = SD.open(metaFileName, FILE_WRITE); if(newFile) { #ifdef DEBUG_PRINT Serial.print(""ms,UTC_timestamp,PM1.0,PM2.5,PM10.0,0.3um,0.5um,1.0um,2.5um,5.0um,10.0um""); #endif newFile.print(""ms,UTC_timestamp,latitude,longitude,altitude,temperature,pressure\\n""); } else { #ifdef DEBUG_PRINT Serial.println(""Couldn't open data file""); #endif } newFile.close(); } // collect data and go to data collection screen prevState = state; state = 2; page = 5; firstMeasurementFlag = true; } // Update current menu selection based on encoders void updateMenuSelection() { long encRightPosition = encRight.read(); long encLeftPosition = encLeft.read(); #ifdef DEBUG_PRINT // Serial.print(""Right encoder position: ""); // Serial.println(encRightPosition); #endif if (encRightPosition > encRightOldPosition + 2) // clockwise, go down { #ifdef DEBUG_PRINT Serial.println(""Right knob turned cw""); #endif encRightOldPosition = encRightPosition; if(curMillis >= prevMenuMillis + MENU_UPDATE_TIME) // only update menu selection every 100ms { prevMenuMillis = curMillis; prevVertMenuSelection = currentVertMenuSelection; currentVertMenuSelection++; switch (page) { case 0: case 1: // initial two menus if(currentVertMenuSelection > 1) currentVertMenuSelection = 1; // only two choices on these pages break; case 2: // entering date if(currentHoriMenuSelection == 0) // month { if(currentVertMenuSelection > 11) currentVertMenuSelection = 0; manualMonth = currentVertMenuSelection + 1; } else if(currentHoriMenuSelection == 1) // day { switch(manualMonth) { case 4: case 6: case 9: case 11: // Apr, Jun, Sept, Nov if(currentVertMenuSelection > 29) currentVertMenuSelection = 0; break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: // Jan, Mar, May, Jul, Aug, Oct, Dec if(currentVertMenuSelection > 30) currentVertMenuSelection = 0; break; case 2: // February if(manualYear % 4 == 0) { if(currentVertMenuSelection > 28) currentVertMenuSelection = 0; } else { if(currentVertMenuSelection > 27) currentVertMenuSelection = 0; } break; } manualDay = currentVertMenuSelection + 1; } else if(currentHoriMenuSelection == 2) // year { if(currentVertMenuSelection > 2099) { currentVertMenuSelection = CUR_YEAR; } else if(currentVertMenuSelection < CUR_YEAR) { currentVertMenuSelection = CUR_YEAR; } manualYear = currentVertMenuSelection; } break; case 3: // entering time if(currentHoriMenuSelection == 0) // hour { if(currentVertMenuSelection > 23) currentVertMenuSelection = 0; manualHour = currentVertMenuSelection; } else if(currentHoriMenuSelection == 1) // minute { if(currentVertMenuSelection > 59) { currentVertMenuSelection = 0; manualHour++; if(manualHour > 23) manualHour = 0; } manualMinute = currentVertMenuSelection; } break; case 4: // selecting file from SD card if(currentVertMenuSelection > fileCount - 1) currentVertMenuSelection = fileCount - 1; if(currentVertMenuSelection % 12 == 0 && currentVertMenuSelection != 0 && currentVertMenuSelection != prevVertMenuSelection) { scroll++; } break; } #ifdef DEBUG_PRINT Serial.print(""Current vert menu selection: ""); Serial.println(currentVertMenuSelection); #endif } } else if (encRightPosition < encRightOldPosition - 2) // counterclockwise, go up { #ifdef DEBUG_PRINT Serial.println(""Right knob turned ccw""); #endif encRightOldPosition = encRightPosition; if(curMillis >= prevMenuMillis + MENU_UPDATE_TIME) // only update menu selection every 100ms { prevMenuMillis = curMillis; prevVertMenuSelection = currentVertMenuSelection; currentVertMenuSelection--; switch(page) { case 0: case 1: if (currentVertMenuSelection < 0) currentVertMenuSelection = 0; // stay at top of menu break; case 2: // entering date if(currentHoriMenuSelection == 0) // entering month { if(currentVertMenuSelection < 0) currentVertMenuSelection = 11; // wrap around manualMonth = currentVertMenuSelection + 1; } else if(currentHoriMenuSelection == 1) // entering day { if(currentVertMenuSelection < 0) { switch(manualMonth) { case 4: case 6: case 9: case 11: // April, June, September, November currentVertMenuSelection = 29; break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: // Jan, Mar, May, Jul, Aug, Oct, Dec currentVertMenuSelection = 30; break; case 2: if(manualYear % 4 == 0) // leap year { currentVertMenuSelection = 28; } else { currentVertMenuSelection = 27; } } } manualDay = currentVertMenuSelection + 1; } else if(currentHoriMenuSelection == 2) // entering year { if(currentVertMenuSelection > 2099) { currentVertMenuSelection = CUR_YEAR; } else if(currentVertMenuSelection < CUR_YEAR) { currentVertMenuSelection = CUR_YEAR; } manualYear = currentVertMenuSelection; } break; case 3: // entering time if(currentHoriMenuSelection == 0) // hour { if(currentVertMenuSelection < 0) currentVertMenuSelection = 23; manualHour = currentVertMenuSelection; } else if(currentHoriMenuSelection == 1) // minute { if(currentVertMenuSelection < 0) { currentVertMenuSelection = 59; manualHour--; if(manualHour > 200) manualHour = 23; } manualMinute = currentVertMenuSelection; } break; case 4: if (currentVertMenuSelection < 0) currentVertMenuSelection = 0; // stay at top of menu if(currentVertMenuSelection % 12 == 11) { scroll--; if(scroll < 0) scroll = 0; } } #ifdef DEBUG_PRINT Serial.print(""Current vert menu selection: ""); Serial.println(currentVertMenuSelection); #endif } } if(encLeftPosition > encLeftOldPosition + 2) { #ifdef DEBUG_PRINT Serial.println(""Left knob turned cw""); Serial.println(encLeftPosition); #endif encLeftOldPosition = encLeftPosition; if(curMillis >= prevMenuMillis + MENU_UPDATE_TIME) { prevMenuMillis = curMillis; if(page == 2 || page == 3) // date or time entry { currentHoriMenuSelection++; if(page == 2) // date entry { if(currentHoriMenuSelection > 2) currentHoriMenuSelection = 2; if(currentHoriMenuSelection == 0) // month { currentVertMenuSelection = manualMonth - 1; } else if(currentHoriMenuSelection == 1) // day { currentVertMenuSelection = manualDay - 1; } else if(currentHoriMenuSelection == 2) // year { currentVertMenuSelection = manualYear; } } else if(page == 3) { if(currentHoriMenuSelection > 1) currentHoriMenuSelection = 1; if(currentHoriMenuSelection == 0) // hour { currentVertMenuSelection = manualHour; } else if(currentHoriMenuSelection == 1) // minute { currentVertMenuSelection = manualMinute; } } } #ifdef DEBUG_PRINT Serial.print(""Current hori menu selection: ""); Serial.println(currentHoriMenuSelection); #endif } } else if(encLeftPosition < encLeftOldPosition - 2) { #ifdef DEBUG_PRINT Serial.println(""Left knob turned ccw""); Serial.println(encLeftPosition); #endif encLeftOldPosition = encLeftPosition; if(curMillis >= prevMenuMillis + MENU_UPDATE_TIME) { currentHoriMenuSelection--; if(page == 2) // date entry { if(currentHoriMenuSelection < 0) currentHoriMenuSelection = 0; if(currentHoriMenuSelection == 0) // month { currentVertMenuSelection = manualMonth - 1; } else if(currentHoriMenuSelection == 1) // day { currentVertMenuSelection = manualDay - 1; } else if(currentHoriMenuSelection == 2) // year { currentVertMenuSelection = manualYear; } } else if(page == 3) // time entry { if(currentHoriMenuSelection < 0) currentHoriMenuSelection = 0; if(currentHoriMenuSelection == 0) // hour { currentVertMenuSelection = manualHour; } else if(currentHoriMenuSelection == 1) // minute { currentVertMenuSelection = manualMinute; } } #ifdef DEBUG_PRINT Serial.print(""Current hori menu selection: ""); Serial.println(currentHoriMenuSelection); #endif } } } // function for displaying various pages/menus void displayPage(uint8_t page) { // On all pages add ""select"" and ""back"" indicators on the bottom of the screen // On data collection page, only show ""back"" display.clearDisplay(); display.drawLine(0, display.height()-10, display.width()-1, display.height()-10, SSD1327_WHITE); display.drawLine(display.width()/2 - 1, display.height()-10, display.width()/2 - 1, display.height()-1, SSD1327_WHITE); // display.drawLine((2*display.width()/3)-1, display.height()-10, (2*display.width()/3)-1, display.height()-1, SSD1327_WHITE); display.setTextColor(SSD1327_WHITE); display.setCursor(10, display.height()-8); display.print(""Back ""); if(page == 2 || page == 3) // only the date and time page uses the left knob for left-right { display.cp437(true); display.print(""\\x11\\x10""); display.cp437(false); } if (page != 5) // no select button on data collection screen { display.setCursor((display.width()/2) + 5, display.height()-8); display.cp437(true); display.print(""\\x1e\\x1f""); display.cp437(false); display.print("" Select""); } switch(page) { case(0): // Initial menu { if (currentVertMenuSelection == 0) { updateDisplay(""Start data collection\\n"", 0, true); updateDisplay(""Upload data"", 8, false); } else if (currentVertMenuSelection == 1) { updateDisplay(""Start data collection\\n"", 0, false); updateDisplay(""Upload data"", 8, true); } break; } case(1): // Time entry method menu { display.drawLine(0, 10, display.width()-1, 10, SSD1327_WHITE); updateDisplay(""Timestamp method?"", 0, false); if (currentVertMenuSelection == 0) { updateDisplay(""Auto (GPS)\\n"", 12, true); updateDisplay(""Manual"", 20, false); } else if (currentVertMenuSelection == 1) { updateDisplay(""Auto (GPS)\\n"", 12, false); updateDisplay(""Manual"", 20, true); } break; } case(2): // Date entry { display.drawLine(0, 10, display.width()-1, 10, SSD1327_WHITE); updateDisplay(""Enter date"", 0, false); char displayMonth[3]; char displayDay[3]; char displayYear[5]; itoa(manualMonth, displayMonth, 10); itoa(manualDay, displayDay, 10); itoa(manualYear, displayYear, 10); display.setTextSize(2); display.setCursor(0, 56); if(currentHoriMenuSelection == 0) display.setTextColor(SSD1327_BLACK, SSD1327_WHITE); if(manualMonth < 10) display.print('0'); display.print(manualMonth); display.setTextColor(SSD1327_WHITE); display.print('/'); if(currentHoriMenuSelection == 1) display.setTextColor(SSD1327_BLACK, SSD1327_WHITE); if(manualDay < 10) display.print('0'); display.print(manualDay); display.setTextColor(SSD1327_WHITE); display.print('/'); if(currentHoriMenuSelection == 2) display.setTextColor(SSD1327_BLACK, SSD1327_WHITE); display.print(manualYear); display.setTextColor(SSD1327_WHITE); display.setTextSize(1); break; } case(3): // Time entry { display.drawLine(0, 10, display.width()-1, 10, SSD1327_WHITE); updateDisplay(""Enter time (UTC)"", 0, false); char displayHour[3]; char displayMinute[3]; itoa(manualHour, displayHour, 10); itoa(manualMinute, displayMinute, 10); display.setTextSize(2); display.setCursor(0, 56); if(currentHoriMenuSelection == 0) display.setTextColor(SSD1327_BLACK, SSD1327_WHITE); if(manualHour < 10) display.print('0'); display.print(manualHour); display.setTextColor(SSD1327_WHITE); display.print(':'); if(currentHoriMenuSelection == 1) display.setTextColor(SSD1327_BLACK, SSD1327_WHITE); if(manualMinute < 10) display.print('0'); display.print(manualMinute); display.setTextColor(SSD1327_WHITE); display.setTextSize(1); break; } case(4): // Viewing list of files on SD card { char allFiles[fileCount][30]; memcpy(allFiles, fileList, sizeof(allFiles)); char screenFiles[12][30]; // files being displayed on screen // #ifdef DEBUG_PRINT // Serial.println(""List of files on SD found in displayPage:""); // for(int i = 0; i < fileCount; ++i) // { // Serial.println(allFiles[i]); // } // Serial.println(); // #endif display.drawLine(0, 10, display.width()-1, 10, SSD1327_WHITE); updateDisplay(""Select a file"", 0, false); uint8_t numFilesToDisplay = 0; // copy next 12 names from allFiles into screenFiles, or fewer if there are fewer than 12 left if(fileCount - scroll*12 >= 12) { memcpy(screenFiles, allFiles[scroll*12], sizeof(screenFiles)); numFilesToDisplay = 12; } else if(fileCount - scroll*12 < 12) { numFilesToDisplay = fileCount - scroll*12; memcpy(screenFiles, allFiles[scroll*12], numFilesToDisplay*30); // 30 bytes per file name } for(uint8_t i = 0; i < numFilesToDisplay; i++) { if(scroll == 0) { if(currentVertMenuSelection == i) updateDisplay(screenFiles[i], 12 + i*8, true); else updateDisplay(screenFiles[i], 12 + i*8, false); } else { if(currentVertMenuSelection == i + 12*scroll) updateDisplay(screenFiles[i], 12 + i*8, true); else updateDisplay(screenFiles[i], 12 + i*8, false); } } break; } case(5): // Data collection { // uint16_t PM1p0_std = dustSensor.data.PM1p0_std; // uint16_t PM2p5_std = dustSensor.data.PM2p5_std; // uint16_t PM10p0_std = dustSensor.data.PM10p0_std; // uint16_t PM1p0_atm = dustSensor.data.PM1p0_atm; // uint16_t PM2p5_atm = dustSensor.data.PM2p5_atm; // uint16_t PM10p0_atm = dustSensor.data.PM10p0_atm; uint16_t count_0p3um = dustSensor.data.count_0p3um; // uint16_t count_0p5um = dustSensor.data.count_0p5um; // uint16_t count_1p0um = dustSensor.data.count_1p0um; // uint16_t count_2p5um = dustSensor.data.count_2p5um; // uint16_t count_5p0um = dustSensor.data.count_5p0um; // uint16_t count_10p0um = dustSensor.data.count_10p0um; char timeText[50]; // char pm1p0Text[10]; // char pm2p5Text[10]; // char pm10p0Text[10]; char hourText[10]; char minuteText[10]; char monthText[10]; char dayText[10]; char yearText[10]; // itoa(PM1p0_atm, pm1p0Text, 10); // itoa(PM2p5_atm, pm2p5Text, 10); // itoa(PM10p0_atm, pm10p0Text, 10); itoa(utcHour, hourText, 10); itoa(utcMinute, minuteText, 10); itoa(utcMonth, monthText, 10); itoa(utcDay, dayText, 10); itoa(utcYear, yearText, 10); display.setTextSize(2); display.setCursor(0, 20); display.print("">0.3um:""); display.setCursor(0, 48); display.print(count_0p3um); display.setCursor(0, 62); display.print(""count/0.1L""); display.setTextSize(1); // strcpy(displayText, ""PM1.0: ""); // strcat(displayText, pm1p0Text); // strcat(displayText, "" ug/m3""); // updateDisplay(displayText, 24, false); // strcpy(displayText, ""PM2.5: ""); // strcat(displayText, pm2p5Text); // strcat(displayText, "" ug/m3""); // updateDisplay(displayText, 32, false); // strcpy(displayText, ""PM10.0: ""); // strcat(displayText, pm10p0Text); // strcat(displayText, "" ug/m3""); // updateDisplay(displayText, 40, false); strcpy(timeText, monthText); strcat(timeText, ""/""); strcat(timeText, dayText); strcat(timeText, ""/""); strcat(timeText, yearText); strcat(timeText, "" ""); if(utcHour < 10) { strcat(timeText, ""0""); } strcat(timeText, hourText); strcat(timeText, "":""); if(utcMinute < 10) { strcat(timeText, ""0""); } strcat(timeText, minuteText); if(gpsDisplayFail || manualTimeEntry) strcat(timeText, "" (RTC)""); else strcat(timeText, "" (GPS)""); updateDisplay(timeText, 108, false); break; } } display.display(); } // function for displaying characters to OLED void updateDisplay(char* text, uint8_t height, bool bg) { // if(clear) display.clearDisplay(); display.setTextSize(1); if(bg) { display.setTextColor(SSD1327_BLACK, SSD1327_WHITE); } else { display.setTextColor(SSD1327_WHITE); } display.setCursor(0, height); display.print(text); // if(send) display.display(); } int cmpstr(void const *a, void const *b) { char const *aa = (char const *)a; char const *bb = (char const *)b; return -1*strcmp(aa, bb); } /* * Functions and variables below this point are used for updating to ThingSpeak, not used in this version */ /* WiFiClient client; const char server[] = ""api.thingspeak.com""; char tspeak_buf[5000]; // buffer for storing multiple rows of data from the CSV for ThingSpeak bulk updates char status_buf[20]; // buffer for status text uint8_t colPositions[17] = {0}; // array to store indices of commas in sd_buf, indicating column delineations unsigned long prevFileSize = 0; // last recorded file size unsigned long bytesLeft = 0; // bytes left in file to update to ThingSpeak bool firstLineDone = false; // flag for first line (titles) having been read uint32_t lastLinePosition = 0; char sd_buf[200]; // buffer to store single SD card line // updates to ThingSpeak in bulk updates of 5kB of data void updateThingSpeak() { // Initialize tspeak_buf memset(tspeak_buf, 0, sizeof(tspeak_buf)); strcpy(tspeak_buf, ""write_api_key=""); strcat(tspeak_buf, writeApiKey); strcat(tspeak_buf, ""&time_format=absolute&updates=""); // Open file on SD card display(""Updating to"", 16, true, false); display(""ThingSpeak...00%"", 24, false, true); dataFile = SD.open(dataFileName, FILE_READ); if(dataFile) { uint32_t charCount = strlen(tspeak_buf); uint32 rawByteCount = 0; uint32_t colCount = 0; uint32_t i = 0; uint32_t linePosition = 0; // location in file of most recent line int percentComplete = 0; dataFile.seek(lastLinePosition); bytesLeft = dataFile.size() - prevFileSize; prevFileSize = dataFile.size(); while(dataFile.available()) { char c = dataFile.read(); rawByteCount++; // Every time you fill up tspeak_buf, send an update to thing speak if((charCount >= sizeof(tspeak_buf) - 200) && (c != '\\n')) { Serial.println(""Buffer full!""); Serial.println(charCount); tspeak_buf[strlen(tspeak_buf) - 1] = 0; // remove last pipe character while(!httpRequest(tspeak_buf)); // keep trying until ThingSpeak/WiFi connection works percentComplete = (rawByteCount*100)/bytesLeft; // reset byte counter and thingspeak buffer memset(tspeak_buf, 0, sizeof(tspeak_buf)); strcpy(tspeak_buf, ""write_api_key=""); strcat(tspeak_buf, writeApiKey); strcat(tspeak_buf, ""&time_format=absolute&updates=""); i = 0; colCount = 0; charCount = strlen(tspeak_buf); char tspeakDisplay[20]; char percentDisplay[10]; itoa(percentComplete, percentDisplay, 10); strcpy(tspeakDisplay, ""ThingSpeak...""); if(percentComplete < 10) { strcat(tspeakDisplay, ""0""); } strcat(tspeakDisplay, percentDisplay); strcat(tspeakDisplay, ""%""); Serial.print(""Update ""); Serial.print(percentComplete); Serial.println(""% done""); // clear SD line buffer and move back to start of latest line memset(sd_buf, 0, sizeof(sd_buf)); dataFile.seek(linePosition); display(""Updating to"", 16, true, false); display(tspeakDisplay, 24, false, true); delay(15000); // can only update to Thingspeak every 15s Serial.println(""Back to updating""); } else if(c == '\\n') { // on a new line, process data on line i = 0; colCount = 0; // store position in file of the start of next line linePosition = dataFile.position(); // One time if statement to avoid reading the first row, which has titles of columns if(!firstLineDone) { firstLineDone = true; continue; } // only update line if GPS data isn't stale memset(status_buf, 0, sizeof(status_buf)); int j = 0; for(int k = colPositions[16]; k < strlen(sd_buf); k++) { status_buf[j++] = sd_buf[k]; } // if GPS time stamp isn't stale, include in tspeak_buf (data to be sent to thingspeak) if(status_buf[0] == 'g') { Serial.println(""Updating thingspeak buffer""); // Remove columns for standard PM data and 0.5um particles uint8_t pmStIndex = colPositions[1]; // index of first standard PM column uint8_t pmAtIndex = colPositions[4]; // index of first atmo PM column uint8_t zerop5umIndex = colPositions[8]; // index of 0.5um particles uint8_t oneumIndex = colPositions[9]; // index of 1um particles uint8_t pmColsDel = pmAtIndex - pmStIndex; // PM columns to delete uint8_t cntsColDel = oneumIndex - zerop5umIndex; // Particle count columns to be deleted // move indices since we'll be deleting characters zerop5umIndex -= pmColsDel; oneumIndex -= pmColsDel; for(int k = pmStIndex; k < sizeof(sd_buf) - pmColsDel; k++) { sd_buf[k] = sd_buf[k + pmColsDel]; // move all data back by pmColsDel } for(int k = zerop5umIndex; k < sizeof(sd_buf) - cntsColDel; k++) { sd_buf[k] = sd_buf[k + cntsColDel]; // do the same to get rid of the 0.5um column } // remove newline from the end of the line sd_buf[strlen(sd_buf) - 1] = 0; Serial.println(sd_buf); // SD data is already formatted for ThingSpeak updates, just concatenate each line with pipe character in between strcat(tspeak_buf, sd_buf); strcat(tspeak_buf, ""|""); // add pipe character between updates charCount += strlen(sd_buf)+1; } memset(sd_buf, 0, sizeof(sd_buf)); } else if(firstLineDone) { // fill up buffer with characters read if(c == ',') { colPositions[++colCount] = i+1; // store start of data in column, so character following a comma } sd_buf[i++] = c; } } // close file dataFile.close(); // store the position of the latest line that was read lastLinePosition = linePosition; // update with the latest data tspeak_buf[strlen(tspeak_buf) - 1] = 0; // remove last pipe character // Only update to ThingSpeak if there's data leftover if(strlen(tspeak_buf) >= 60) { while(!httpRequest(tspeak_buf)); } display(""All data updated"", 16, true, false); display(""to ThingSpeak!"", 24, false, true); delay(5000); } else { Serial.println(""unable to open file""); display(""Couldn't open file"", 20, true, false); delay(5000); } } // connect to WiFi void connectWiFi() { // Initialize WiFi unsigned long startTime = millis(); display(""Connecting to WiFi"", 20, true, true); WiFi.begin(ssid, password); while(WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("".""); if(millis() - startTime > 20000) // time out after a 20s, then retry { Serial.println(""\\nTime out, reconnecting""); WiFi.end(); delay(250); WiFi.begin(ssid, password); startTime = millis(); } } Serial.println(""\\nWiFi connected""); display(""WiFi connected"", 20, true, true); } // form HTTP request for bulk updates bool httpRequest(char* buffer) { bool success = false; // Connect to WiFi connectWiFi(); client.stop(); char data_length[10]; char post[200]; char channelID[10]; itoa(channelNumber, channelID, 10); strcpy(post, ""POST /channels/""); strcat(post, channelID); strcat(post, ""/bulk_update.csv HTTP/1.1""); itoa(strlen(buffer), data_length, 10); if(client.connect(server, 80)) { client.println(post); Serial.println(post); client.println(""Host: api.thingspeak.com""); Serial.println(""Host: api.thingspeak.com""); client.println(""Content-Type: application/x-www-form-urlencoded""); Serial.println(""Content-Type: application/x-www-form-urlencoded""); client.print(""Content-Length: ""); client.println(data_length); Serial.print(""Content-Length: ""); Serial.println(data_length); client.println(); Serial.println(); for(int i = 0; i < strlen(buffer); i++) { client.print(buffer[i]); Serial.print(buffer[i]); } client.println(); Serial.println(); } else { Serial.println(""Failed to connect to ThingSpeak""); return false; } delay(250); char displayBuffer[20] = ""Code: ""; char codeBuffer[10]; client.parseFloat(); int resp = client.parseInt(); itoa(resp, codeBuffer, 10); strcat(displayBuffer, codeBuffer); if(resp == 202) { Serial.print(""Successful update, code: ""); Serial.println(resp); display(""Successful update"", 16, true, false); display(displayBuffer, 24, false, true); success = true; delay(5000); } else { Serial.print(""Failed update, code: ""); Serial.println(resp); display(""Failed update"", 16, true, false); display(displayBuffer, 24, false, true); success = false; delay(5000); } client.stop(); Serial.println(""Client stopped""); WiFi.end(); Serial.println(""WiFi off""); return success; } */",16152,True,2836.926743027767,median "/* Feathers Copyright 2012-2020 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls.text { import feathers.core.FocusManager; import feathers.core.IIMETextEditor; import feathers.core.INativeFocusOwner; import feathers.events.FeathersEventType; import feathers.skins.IStyleProvider; import feathers.utils.text.TextEditorIMEClient; import feathers.utils.text.TextInputNavigation; import feathers.utils.text.TextInputRestrict; import flash.desktop.Clipboard; import flash.desktop.ClipboardFormats; import flash.display.DisplayObjectContainer; import flash.display.Sprite; import flash.display.Stage; import flash.events.Event; import flash.events.TextEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.TextFormatAlign; import flash.text.engine.TextElement; import flash.text.engine.TextLine; import flash.text.ime.CompositionAttributeRange; import flash.ui.Keyboard; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.Quad; import starling.events.Event; import starling.events.KeyboardEvent; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; import starling.rendering.Painter; import starling.utils.Pool; /** * Dispatched when the text property changes. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @see #text * * @eventType starling.events.Event.CHANGE */ [Event(name=""change"",type=""starling.events.Event"")] /** * Dispatched when the user presses the Enter key while the editor has * focus. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType feathers.events.FeathersEventType.ENTER */ [Event(name=""enter"",type=""starling.events.Event"")] /** * Dispatched when the text editor receives focus. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType feathers.events.FeathersEventType.FOCUS_IN */ [Event(name=""focusIn"",type=""starling.events.Event"")] /** * Dispatched when the text editor loses focus. * *

The properties of the event object have the following values:

* * * * * * *
PropertyValue
bubblesfalse
currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
datanull
targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
* * @eventType feathers.events.FeathersEventType.FOCUS_OUT */ [Event(name=""focusOut"",type=""starling.events.Event"")] /** * Text that may be edited at runtime by the user with the * TextInput component, rendered with a native * flash.text.engine.TextBlock from * Flash Text Engine * (sometimes abbreviated as FTE). Draws the text to BitmapData * to convert to Starling textures. Textures are managed internally by this * component, and they will be automatically disposed when the component is * disposed. * *

Warning: This text editor is intended for use in * desktop applications only, and it does not provide support for software * keyboards on mobile devices.

* *

The following example shows how to use * TextBlockTextEditor with a TextInput:

* * * var input:TextInput = new TextInput(); * input.textEditorFactory = function():ITextEditor * { * return new TextBlockTextEditor(); * }; * this.addChild( input ); * * @see feathers.controls.TextInput * @see ../../../../help/text-editors.html Introduction to Feathers text editors * @see http://help.adobe.com/en_US/as3/dev/WS9dd7ed846a005b294b857bfa122bd808ea6-8000.html Using the Flash Text Engine in ActionScript 3.0 Developer's Guide * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/engine/TextBlock.html flash.text.engine.TextBlock * * @productversion Feathers 2.0.0 */ public class TextBlockTextEditor extends TextBlockTextRenderer implements IIMETextEditor, INativeFocusOwner { /** * The text will be positioned to the left edge. * * @see feathers.controls.text.TextBlockTextRenderer#textAlign */ public static const TEXT_ALIGN_LEFT:String = ""left""; /** * The text will be centered horizontally. * * @see feathers.controls.text.TextBlockTextRenderer#textAlign */ public static const TEXT_ALIGN_CENTER:String = ""center""; /** * The text will be positioned to the right edge. * * @see feathers.controls.text.TextBlockTextRenderer#textAlign */ public static const TEXT_ALIGN_RIGHT:String = ""right""; /** * The default IStyleProvider for all TextBlockTextEditor * components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * Constructor. */ public function TextBlockTextEditor() { super(); this._text = """"; this._textElement = new TextElement(this._text); this._content = this._textElement; this.isQuickHitAreaEnabled = true; this.truncateToFit = false; this.addEventListener(TouchEvent.TOUCH, textEditor_touchHandler); } /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return globalStyleProvider; } /** * @private */ protected var _ignoreNextTextInputEvent:Boolean = false; /** * @private */ protected var _imeText:String; /** * @private */ protected var _imeCursorIndex:int = -1; /** * @private */ protected var _selectionSkin:DisplayObject; /** * The skin that indicates the currently selected range of text. */ public function get selectionSkin():DisplayObject { return this._selectionSkin; } /** * @private */ public function set selectionSkin(value:DisplayObject):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._selectionSkin == value) { return; } if(this._selectionSkin && this._selectionSkin.parent == this) { this._selectionSkin.removeFromParent(); } this._selectionSkin = value; if(this._selectionSkin) { this._selectionSkin.visible = false; this.addChildAt(this._selectionSkin, 0); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _cursorDelay:Number = 0.53; /** * @private */ protected var _cursorDelayID:uint = uint.MAX_VALUE; /** * @private */ protected var _cursorSkin:DisplayObject; /** * The skin that indicates the current position where text may be * entered. */ public function get cursorSkin():DisplayObject { return this._cursorSkin; } /** * @private */ public function set cursorSkin(value:DisplayObject):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._cursorSkin === value) { return; } if(this._cursorSkin !== null && this._cursorSkin.parent === this) { this._cursorSkin.removeFromParent(); } this._cursorSkin = value; if(this._cursorSkin !== null) { this._cursorSkin.visible = false; this.addChild(this._cursorSkin); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _unmaskedText:String; /** * @private */ protected var _displayAsPassword:Boolean = false; /** *

This property is managed by the TextInput.

* * @copy feathers.controls.TextInput#displayAsPassword * * @see feathers.controls.TextInput#displayAsPassword * * @see #passwordCharCode */ public function get displayAsPassword():Boolean { return this._displayAsPassword; } /** * @private */ public function set displayAsPassword(value:Boolean):void { if(this._displayAsPassword == value) { return; } this._displayAsPassword = value; if(this._displayAsPassword) { this._unmaskedText = this._text; this.refreshMaskedText(); } else { this._text = this._unmaskedText; this._unmaskedText = null; } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _passwordCharCode:int = 42; //asterisk /** * The character code of the character used to display a password. * *

In the following example, the substitute character for passwords * is set to a bullet:

* * * textEditor.displayAsPassword = true; * textEditor.passwordCharCode = ""•"".charCodeAt(0); * * @default 42 (asterisk) * * @see #displayAsPassword */ public function get passwordCharCode():int { return this._passwordCharCode; } /** * @private */ public function set passwordCharCode(value:int):void { if(this._passwordCharCode == value) { return; } this._passwordCharCode = value; if(this._displayAsPassword) { this.refreshMaskedText(); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _isEditable:Boolean = true; /** *

This property is managed by the TextInput.

* * @copy feathers.controls.TextInput#isEditable * * @see feathers.controls.TextInput#isEditable */ public function get isEditable():Boolean { return this._isEditable; } /** * @private */ public function set isEditable(value:Boolean):void { if(this._isEditable == value) { return; } this._isEditable = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _isSelectable:Boolean = true; /** *

This property is managed by the TextInput.

* * @copy feathers.controls.TextInput#isSelectable * * @see feathers.controls.TextInput#isSelectable */ public function get isSelectable():Boolean { return this._isSelectable; } /** * @private */ public function set isSelectable(value:Boolean):void { if(this._isSelectable == value) { return; } this._isSelectable = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @inheritDoc * * @default false */ public function get setTouchFocusOnEndedPhase():Boolean { return false; } /** * @private */ override public function get text():String { if(this._displayAsPassword) { return this._unmaskedText; } return this._text; } /** * @private */ override public function set text(value:String):void { if(value === null) { //don't allow null or undefined value = """"; } var currentValue:String = this._text; if(this._displayAsPassword) { currentValue = this._unmaskedText; } if(currentValue == value) { return; } if(this._displayAsPassword) { this._unmaskedText = value; this.refreshMaskedText(); } else { super.text = value; } var textLength:int = this._text.length; //we need to account for the possibility that the text is in the //middle of being selected when it changes if(this._selectionAnchorIndex > textLength) { this._selectionAnchorIndex = textLength; } //then, we need to make sure the selected range is still valid if(this._selectionBeginIndex > textLength) { this.selectRange(textLength, textLength); } else if(this._selectionEndIndex > textLength) { this.selectRange(this._selectionBeginIndex, textLength); } this.dispatchEventWith(starling.events.Event.CHANGE); } /** * @private */ protected var _maxChars:int = 0; /** *

This property is managed by the TextInput.

* * @copy feathers.controls.TextInput#maxChars * * @see feathers.controls.TextInput#maxChars */ public function get maxChars():int { return this._maxChars; } /** * @private */ public function set maxChars(value:int):void { if(this._maxChars == value) { return; } this._maxChars = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _restrict:TextInputRestrict; /** *

This property is managed by the TextInput.

* * @copy feathers.controls.TextInput#restrict * * @see feathers.controls.TextInput#restrict */ public function get restrict():String { if(!this._restrict) { return null; } return this._restrict.restrict; } /** * @private */ public function set restrict(value:String):void { if(this._restrict && this._restrict.restrict === value) { return; } if(!this._restrict && value === null) { return; } if(value === null) { this._restrict = null; } else { if(this._restrict) { this._restrict.restrict = value; } else { this._restrict = new TextInputRestrict(value); } } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _selectionBeginIndex:int = 0; /** * @inheritDoc * * @see #selectionEndIndex */ public function get selectionBeginIndex():int { return this._selectionBeginIndex; } /** * @private */ protected var _selectionEndIndex:int = 0; /** * @inheritDoc * * @see #selectionBeginIndex */ public function get selectionEndIndex():int { return this._selectionEndIndex; } /** * @private */ protected var _selectionAnchorIndex:int = 0; /** * @inheritDoc * * @see #selectionActiveIndex */ public function get selectionAnchorIndex():int { return this._selectionAnchorIndex; } /** * @inheritDoc * * @see #selectionAnchorIndex */ public function get selectionActiveIndex():int { if(this._selectionAnchorIndex == this._selectionBeginIndex) { return this._selectionEndIndex; } return this._selectionBeginIndex; } /** * @private */ protected var touchPointID:int = -1; /** * @private */ protected var _nativeFocus:Sprite; /** * @copy feathers.core.INativeFocusOwner#nativeFocus */ public function get nativeFocus():Object { return this._nativeFocus; } /** * @private */ protected var _isWaitingToSetFocus:Boolean = false; /** * @inheritDoc */ public function setFocus(position:Point = null):void { if(this._hasFocus && !position) { //we already have focus, and there isn't a touch position, we //can ignore this because nothing would change return; } if(this._nativeFocus !== null) { if(this._nativeFocus.parent === null) { var starling:Starling = this.stage !== null ? this.stage.starling : Starling.current; starling.nativeStage.addChild(this._nativeFocus); } var newIndex:int = -1; if(position !== null) { newIndex = this.getSelectionIndexAtPoint(position.x, position.y); } if(newIndex >= 0) { this.selectRange(newIndex, newIndex); } this.focusIn(); } else { this._isWaitingToSetFocus = true; } } /** * @inheritDoc */ public function clearFocus():void { if(!this._hasFocus) { return; } this._hasFocus = false; this._cursorSkin.visible = false; this._selectionSkin.visible = false; this.refreshCursorBlink(); this.stage.removeEventListener(TouchEvent.TOUCH, stage_touchHandler); this.stage.removeEventListener(KeyboardEvent.KEY_DOWN, stage_keyDownHandler); this.removeEventListener(starling.events.Event.ENTER_FRAME, hasFocus_enterFrameHandler); var starling:Starling = this.stage !== null ? this.stage.starling : Starling.current; var nativeStage:Stage = starling.nativeStage; if(nativeStage.focus === this._nativeFocus) { //only clear the native focus when our native target has focus //because otherwise another component may lose focus. //for consistency with StageTextTextEditor and //TextFieldTextEditor, we set the native stage's focus to null //here instead of setting it to the native stage due to issues //with those text editors on Android. nativeStage.focus = null; } this.dispatchEventWith(FeathersEventType.FOCUS_OUT); } /** * @inheritDoc */ public function selectRange(beginIndex:int, endIndex:int):void { if(!this._isEditable && !this._isSelectable) { return; } if(endIndex < beginIndex) { var temp:int = endIndex; endIndex = beginIndex; beginIndex = temp; } this._selectionBeginIndex = beginIndex; this._selectionEndIndex = endIndex; if(beginIndex == endIndex) { this._selectionAnchorIndex = beginIndex; if(beginIndex < 0) { this._cursorSkin.visible = false; } else { //cursor skin is not shown if isSelectable === true and //isEditable is false this._cursorSkin.visible = this._hasFocus && this._isEditable; } this._selectionSkin.visible = false; } else { this._cursorSkin.visible = false; this._selectionSkin.visible = true; } this.refreshCursorBlink(); this.invalidate(INVALIDATION_FLAG_SELECTED); } /** * @private */ override public function dispose():void { if(this._nativeFocus && this._nativeFocus.parent) { this._nativeFocus.parent.removeChild(this._nativeFocus); } this._nativeFocus = null; super.dispose(); } /** * @private */ override public function render(painter:Painter):void { var oldSnapshotX:Number = this._textSnapshotOffsetX; var oldCursorX:Number = this._cursorSkin.x; this._cursorSkin.x -= this._textSnapshotScrollX; super.render(painter); this._textSnapshotOffsetX = oldSnapshotX; this._cursorSkin.x = oldCursorX; } /** * @private */ override protected function initialize():void { if(!this._nativeFocus) { this._nativeFocus = new TextEditorIMEClient(this, imeClientStartCallback, imeClientUpdateCallback, imeClientConfirmCallback); //let's ensure that this can only get focus through code this._nativeFocus.tabEnabled = false; this._nativeFocus.tabChildren = false; this._nativeFocus.mouseEnabled = false; this._nativeFocus.mouseChildren = false; //adds support for mobile this._nativeFocus.needsSoftKeyboard = true; } this._nativeFocus.addEventListener(flash.events.Event.CUT, nativeFocus_cutHandler, false, 0, true); this._nativeFocus.addEventListener(flash.events.Event.COPY, nativeFocus_copyHandler, false, 0, true); this._nativeFocus.addEventListener(flash.events.Event.PASTE, nativeFocus_pasteHandler, false, 0, true); this._nativeFocus.addEventListener(flash.events.Event.SELECT_ALL, nativeFocus_selectAllHandler, false, 0, true); this._nativeFocus.addEventListener(TextEvent.TEXT_INPUT, nativeFocus_textInputHandler, false, 0, true); if(this._cursorSkin === null) { this.ignoreNextStyleRestriction(); this.cursorSkin = new Quad(1, 1, 0x000000); } if(this._selectionSkin === null) { this.ignoreNextStyleRestriction(); this.selectionSkin = new Quad(1, 1, 0x000000); } super.initialize(); } /** * @private */ override protected function draw():void { var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var selectionInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SELECTED); super.draw(); if(dataInvalid || selectionInvalid) { this.positionCursorAtCharIndex(this.getCursorIndexFromSelectionRange()); this.positionSelectionBackground(); } } /** * @private */ override protected function refreshTextElementText():void { if(this._textElement === null) { return } var displayText:String = this._text; if(this._imeText !== null) { displayText = this._imeText; } if(displayText) { this._textElement.text = displayText; if(displayText !== null && displayText.charAt(displayText.length - 1) == "" "") { //add an invisible control character because FTE apparently //doesn't think that it's important to include trailing //spaces in its width measurement. this._textElement.text += String.fromCharCode(3); } } else { //similar to above. this hack ensures that the baseline is //measured properly when the text is an empty string. this._textElement.text = String.fromCharCode(3); } } /** * @private */ override protected function refreshTextLines(textLines:Vector., textLineParent:DisplayObjectContainer, width:Number, height:Number, result:MeasureTextResult = null):MeasureTextResult { result = super.refreshTextLines(textLines, textLineParent, width, height, result); if(textLines !== this._measurementTextLines && textLineParent.width > width) { this.alignTextLines(textLines, width, TextFormatAlign.LEFT); } return result; } /** * @private */ protected function refreshMaskedText():void { var newText:String = """"; var textLength:int = this._unmaskedText.length; var maskChar:String = String.fromCharCode(this._passwordCharCode); for(var i:int = 0; i < textLength; i++) { newText += maskChar; } super.text = newText; } /** * @private */ protected function focusIn():void { var showSelection:Boolean = (this._isEditable || this._isSelectable) && this._selectionBeginIndex >= 0 && this._selectionBeginIndex != this._selectionEndIndex; var showCursor:Boolean = this._isEditable && this._selectionBeginIndex >= 0 && this._selectionBeginIndex == this._selectionEndIndex; this._cursorSkin.visible = showCursor; this._selectionSkin.visible = showSelection; this.refreshCursorBlink(); if(!FocusManager.isEnabledForStage(this.stage)) { var starling:Starling = this.stage !== null ? this.stage.starling : Starling.current; //if there isn't a focus manager, we need to set focus manually starling.nativeStage.focus = this._nativeFocus; } if(this._isEditable) { this._nativeFocus.requestSoftKeyboard(); } if(this._hasFocus) { return; } //we're reusing this variable. since this isn't a display object //that the focus manager can see, it's not being used anyway. this._hasFocus = true; this.stage.addEventListener(TouchEvent.TOUCH, stage_touchHandler); this.stage.addEventListener(KeyboardEvent.KEY_DOWN, stage_keyDownHandler); this.addEventListener(starling.events.Event.ENTER_FRAME, hasFocus_enterFrameHandler); this.dispatchEventWith(FeathersEventType.FOCUS_IN); } /** * @private */ protected function refreshCursorBlink():void { var starling:Starling = this.stage !== null ? this.stage.starling : Starling.current; if(this._cursorDelayID == uint.MAX_VALUE && this._cursorSkin.visible) { this._cursorSkin.alpha = 1; this._cursorDelayID = starling.juggler.delayCall(toggleCursorSkin, this._cursorDelay); } else if(this._cursorDelayID != uint.MAX_VALUE && !this._cursorSkin.visible) { starling.juggler.removeByID(this._cursorDelayID); this._cursorDelayID = uint.MAX_VALUE; } } /** * @private */ protected function toggleCursorSkin():void { if(this._cursorSkin.alpha > 0) { this._cursorSkin.alpha = 0; } else { this._cursorSkin.alpha = 1; } var starling:Starling = this.stage !== null ? this.stage.starling : Starling.current; this._cursorDelayID = starling.juggler.delayCall(toggleCursorSkin, this._cursorDelay); } /** * @private */ protected function getSelectionIndexAtPoint(pointX:Number, pointY:Number):int { if(!this._text || this._textLines.length == 0) { return 0; } var line:TextLine = this._textLines[0]; if((pointX - line.x) <= 0) { if(this._bidiLevel == 1) { return this._text.length; } return 0; } else if((pointX - line.x) >= line.width) { if(this._bidiLevel == 1) { return 0; } return this._text.length; } var atomIndex:int = line.getAtomIndexAtPoint(pointX, pointY); if(atomIndex < 0) { //try again with the middle of the line atomIndex = line.getAtomIndexAtPoint(pointX, line.ascent / 2); } if(atomIndex < 0) { //worse case: we couldn't figure it out at all return this._text.length; } //we're constraining the atom index to the text length because we //may have added an invisible control character at the end due to //the fact that FTE won't include trailing spaces in measurement if(atomIndex > this._text.length) { atomIndex = this._text.length; } var atomBounds:Rectangle = line.getAtomBounds(atomIndex); if((pointX - line.x - atomBounds.x) > atomBounds.width / 2) { return atomIndex + 1; } return atomIndex; } /** * @private */ protected function getXPositionOfCharIndex(index:int):Number { var displayText:String = this._text; if(this._imeText !== null) { displayText = this._imeText; } if(!displayText || this._textLines.length == 0) { if(this._currentHorizontalAlign == TextFormatAlign.CENTER) { return Math.round(this.actualWidth / 2); } else if(this._currentHorizontalAlign == TextFormatAlign.RIGHT) { return this.actualWidth; } return 0; } var line:TextLine = this._textLines[0]; if(index === displayText.length) { if(this._bidiLevel == 1) { return line.x; } return line.x + line.width; } var atomIndex:int = line.getAtomIndexAtCharIndex(index); var atomBounds:Rectangle = line.getAtomBounds(atomIndex); var result:Number = line.x + atomBounds.x; if(this._bidiLevel == 1) { result += atomBounds.width; } return result; } /** * @private */ protected function positionCursorAtCharIndex(index:int):void { if(index < 0) { index = 0; } var cursorX:Number = this.getXPositionOfCharIndex(index); cursorX = int(cursorX - (this._cursorSkin.width / 2)); this._cursorSkin.x = cursorX; this._cursorSkin.y = this._verticalAlignOffsetY; if(this._textLines.length > 0) { var line:TextLine = this._textLines[0]; this._cursorSkin.height = this.calculateLineAscent(line) + line.totalDescent; } else { this._cursorSkin.height = this.currentElementFormat.fontSize; } //then we update the scroll to always show the cursor var minScrollX:Number = cursorX + this._cursorSkin.width - this.actualWidth; var displayText:String = this._text; if(this._imeText !== null) { displayText = this._imeText; } var maxScrollX:Number = this.getXPositionOfCharIndex(displayText.length) - this.actualWidth; if(maxScrollX < 0) { maxScrollX = 0; } var oldScrollX:Number = this._textSnapshotScrollX; if(this._textSnapshotScrollX < minScrollX) { this._textSnapshotScrollX = minScrollX; } else if(this._textSnapshotScrollX > cursorX) { this._textSnapshotScrollX = cursorX; } if(this._textSnapshotScrollX > maxScrollX) { this._textSnapshotScrollX = maxScrollX; } if(this._textSnapshotScrollX != oldScrollX) { this.invalidate(INVALIDATION_FLAG_DATA); } } /** * @private */ protected function getCursorIndexFromSelectionRange():int { if(this._imeCursorIndex >= 0) { return this._imeCursorIndex; } var cursorIndex:int = this._selectionEndIndex; if(this.touchPointID >= 0 && this._selectionAnchorIndex >= 0 && this._selectionAnchorIndex == this._selectionEndIndex) { cursorIndex = this._selectionBeginIndex; } return cursorIndex; } /** * @private */ protected function positionSelectionBackground():void { var displayText:String = this._text; if(this._imeText !== null) { displayText = this._imeText; } var beginIndex:int = this._selectionBeginIndex; if(beginIndex > displayText.length) { beginIndex = displayText.length; } var startX:Number = this.getXPositionOfCharIndex(beginIndex) - this._textSnapshotScrollX; if(startX < 0) { startX = 0; } var endIndex:int = this._selectionEndIndex; if(endIndex > displayText.length) { endIndex = displayText.length; } var endX:Number = this.getXPositionOfCharIndex(endIndex) - this._textSnapshotScrollX; if(endX < 0) { endX = 0; } else if(endX > this.actualWidth) { endX = this.actualWidth; } this._selectionSkin.x = startX; this._selectionSkin.width = endX - startX; this._selectionSkin.y = this._verticalAlignOffsetY; if(this._textLines.length > 0) { var line:TextLine = this._textLines[0]; this._selectionSkin.height = this.calculateLineAscent(line) + line.totalDescent; } else { this._selectionSkin.height = this.currentElementFormat.fontSize; } } /** * @private */ protected function getSelectedText():String { if(this._selectionBeginIndex == this._selectionEndIndex) { return null; } return this._text.substr(this._selectionBeginIndex, this._selectionEndIndex - this._selectionBeginIndex); } /** * @private */ protected function deleteSelectedText():void { var currentValue:String = this._text; if(this._displayAsPassword) { currentValue = this._unmaskedText; } this.text = currentValue.substr(0, this._selectionBeginIndex) + currentValue.substr(this._selectionEndIndex); this.validate(); this.selectRange(this._selectionBeginIndex, this._selectionBeginIndex); } /** * @private */ protected function replaceSelectedText(text:String):void { var currentValue:String = this._text; if(this._displayAsPassword) { currentValue = this._unmaskedText; } var newText:String = currentValue.substr(0, this._selectionBeginIndex) + text + currentValue.substr(this._selectionEndIndex); if(this._maxChars > 0 && newText.length > this._maxChars) { return; } this.text = newText; this.validate(); var selectionIndex:int = this._selectionBeginIndex + text.length; this.selectRange(selectionIndex, selectionIndex); } /** * @private */ protected function imeClientStartCallback():void { } /** * @private */ protected function imeClientUpdateCallback(text:String, attributes:Vector., compositionStartIndex:int, compositionEndIndex:int):void { var currentValue:String = this._text; if(this._displayAsPassword) { currentValue = this._unmaskedText; } this._imeText = currentValue.substr(0, this._selectionBeginIndex) + text + currentValue.substr(this._selectionEndIndex); this._imeCursorIndex = this._selectionBeginIndex + compositionStartIndex; this._cursorSkin.visible = this._hasFocus; this._selectionSkin.visible = false; this.setInvalidationFlag(INVALIDATION_FLAG_DATA); this.validate(); } /** * @private */ protected function imeClientConfirmCallback(text:String = null, preserveSelection:Boolean = false):void { //the focus will dispatch an extra TextEvent.TEXT_INPUT event, for //some reason. we need to ignore it or extra text will be displayed. this._ignoreNextTextInputEvent = true; } /** * @private */ protected function hasFocus_enterFrameHandler(event:starling.events.Event):void { var target:DisplayObject = this; do { if(!target.visible) { this.clearFocus(); break; } target = target.parent; } while(target) } /** * @private */ protected function textEditor_touchHandler(event:TouchEvent):void { if(!this._isEnabled || (!this._isEditable && !this._isSelectable)) { this.touchPointID = -1; return; } if(this.touchPointID >= 0) { var touch:Touch = event.getTouch(this, null, this.touchPointID); var point:Point = Pool.getPoint(); touch.getLocation(this, point); point.x += this._textSnapshotScrollX; this.selectRange(this._selectionAnchorIndex, this.getSelectionIndexAtPoint(point.x, point.y)); Pool.putPoint(point); if(touch.phase == TouchPhase.ENDED) { this.touchPointID = -1; } } else //if we get here, we don't have a saved touch ID yet { touch = event.getTouch(this, TouchPhase.BEGAN); if(!touch) { return; } if(touch.tapCount == 2) { var start:int = TextInputNavigation.findCurrentWordStartIndex(this._text, this._selectionBeginIndex); var end:int = TextInputNavigation.findCurrentWordEndIndex(this._text, this._selectionEndIndex); this.selectRange(start, end); return; } else if(touch.tapCount > 2) { this.selectRange(0, this._text.length); return; } this.touchPointID = touch.id; point = Pool.getPoint(); touch.getLocation(this, point); point.x += this._textSnapshotScrollX; if(event.shiftKey) { if(this._selectionAnchorIndex < 0) { this._selectionAnchorIndex = this._selectionBeginIndex; } this.selectRange(this._selectionAnchorIndex, this.getSelectionIndexAtPoint(point.x, point.y)); } else { this.setFocus(point); } Pool.putPoint(point); } } /** * @private */ protected function stage_touchHandler(event:TouchEvent):void { if(FocusManager.isEnabledForStage(this.stage)) { //let the focus manager handle clearing focus return; } var touch:Touch = event.getTouch(this.stage, TouchPhase.BEGAN); if(!touch) //we only care about began touches { return; } var point:Point = Pool.getPoint(); touch.getLocation(this.stage, point); var isInBounds:Boolean = this.contains(this.stage.hitTest(point)); Pool.putPoint(point); if(isInBounds) //if the touch is in the text editor, it's all good { return; } //if the touch begins anywhere else, it's a focus out! this.clearFocus(); } /** * @private */ protected function stage_keyDownHandler(event:KeyboardEvent):void { if(!this._isEnabled || (!this._isEditable && !this._isSelectable) || this.touchPointID >= 0 || event.isDefaultPrevented()) { return; } //ignore select all, cut, copy, and paste var charCode:uint = event.charCode; if(event.ctrlKey && (charCode == 97 || charCode == 99 || charCode == 118 || charCode == 120)) //a, c, p, and x { return; } var newIndex:int = -1; if(!FocusManager.isEnabledForStage(this.stage) && event.keyCode == Keyboard.TAB) { this.clearFocus(); return; } else if(event.keyCode == Keyboard.HOME || event.keyCode == Keyboard.UP) { newIndex = 0; if(event.shiftKey) { this.selectRange(newIndex, this._selectionAnchorIndex); return; } } else if(event.keyCode == Keyboard.END || event.keyCode == Keyboard.DOWN) { newIndex = this._text.length; if(event.shiftKey) { this.selectRange(this._selectionAnchorIndex, newIndex); return; } } else if(event.keyCode == Keyboard.LEFT) { if(event.shiftKey) { if(this._selectionAnchorIndex >= 0 && this._selectionAnchorIndex == this._selectionBeginIndex && this._selectionBeginIndex != this._selectionEndIndex) { newIndex = this._selectionEndIndex - 1; this.selectRange(this._selectionBeginIndex, newIndex); } else { newIndex = this._selectionBeginIndex - 1; if(newIndex < 0) { newIndex = 0; } this.selectRange(newIndex, this._selectionEndIndex); } return; } else if(this._selectionBeginIndex != this._selectionEndIndex) { newIndex = this._selectionBeginIndex; } else { if(event.altKey || event.ctrlKey) { newIndex = TextInputNavigation.findPreviousWordStartIndex(this._text, this._selectionBeginIndex); } else { newIndex = this._selectionBeginIndex - 1; } if(newIndex < 0) { newIndex = 0; } } } else if(event.keyCode == Keyboard.RIGHT) { if(event.shiftKey) { if(this._selectionAnchorIndex >= 0 && this._selectionAnchorIndex == this._selectionEndIndex && this._selectionBeginIndex != this._selectionEndIndex) { newIndex = this._selectionBeginIndex + 1; this.selectRange(newIndex, this._selectionEndIndex); } else { newIndex = this._selectionEndIndex + 1; if(newIndex < 0 || newIndex > this._text.length) { newIndex = this._text.length; } this.selectRange(this._selectionBeginIndex, newIndex); } return; } else if(this._selectionBeginIndex != this._selectionEndIndex) { newIndex = this._selectionEndIndex; } else { if(event.altKey || event.ctrlKey) { newIndex = TextInputNavigation.findNextWordStartIndex(this._text, this._selectionEndIndex); } else { newIndex = this._selectionEndIndex + 1; } if(newIndex < 0 || newIndex > this._text.length) { newIndex = this._text.length; } } } if(newIndex < 0) { if(event.keyCode == Keyboard.ENTER) { this.dispatchEventWith(FeathersEventType.ENTER); return; } //everything after this point edits the text, so return if the text //editor isn't editable. if(!this._isEditable) { return; } var currentValue:String = this._text; if(this._displayAsPassword) { currentValue = this._unmaskedText; } if(event.keyCode == Keyboard.DELETE) { if(event.altKey || event.ctrlKey) { var nextWordStartIndex:int = TextInputNavigation.findNextWordStartIndex(this._text, this._selectionEndIndex); this.text = currentValue.substr(0, this._selectionBeginIndex) + currentValue.substr(nextWordStartIndex); } else if(this._selectionBeginIndex != this._selectionEndIndex) { this.deleteSelectedText(); } else if(this._selectionEndIndex < currentValue.length) { this.text = currentValue.substr(0, this._selectionBeginIndex) + currentValue.substr(this._selectionEndIndex + 1); } } else if(event.keyCode == Keyboard.BACKSPACE) { if(event.altKey || event.ctrlKey) { newIndex = TextInputNavigation.findPreviousWordStartIndex(this._text, this._selectionBeginIndex); this.text = currentValue.substr(0, newIndex) + currentValue.substr(this._selectionEndIndex); } else if(this._selectionBeginIndex != this._selectionEndIndex) { this.deleteSelectedText(); } else if(this._selectionBeginIndex > 0) { newIndex = this._selectionBeginIndex - 1; this.text = currentValue.substr(0, this._selectionBeginIndex - 1) + currentValue.substr(this._selectionEndIndex); } } } if(newIndex >= 0) { this.validate(); this.selectRange(newIndex, newIndex); } } /** * @private */ protected function nativeFocus_textInputHandler(event:TextEvent):void { if(this._ignoreNextTextInputEvent) { this._ignoreNextTextInputEvent = false; return; } if(!this._isEditable || !this._isEnabled) { return; } this._imeText = null; this._imeCursorIndex = -1; var text:String = event.text; if(text === CARRIAGE_RETURN || text === LINE_FEED) { //ignore new lines return; } var charCode:int = text.charCodeAt(0); if(!this._restrict || this._restrict.isCharacterAllowed(charCode)) { this.replaceSelectedText(text); } } /** * @private */ protected function nativeFocus_selectAllHandler(event:flash.events.Event):void { if(!this._isEnabled || (!this._isEditable && !this._isSelectable)) { return; } this._selectionAnchorIndex = 0; this.selectRange(0, this._text.length); } /** * @private */ protected function nativeFocus_cutHandler(event:flash.events.Event):void { if(!this._isEnabled || (!this._isEditable && !this._isSelectable) || this._selectionBeginIndex == this._selectionEndIndex || this._displayAsPassword) { return; } Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, this.getSelectedText()); if(!this._isEditable) { return; } this.deleteSelectedText(); } /** * @private */ protected function nativeFocus_copyHandler(event:flash.events.Event):void { if(!this._isEnabled || (!this._isEditable && !this._isSelectable) || this._selectionBeginIndex == this._selectionEndIndex || this._displayAsPassword) { return; } Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, this.getSelectedText()); } /** * @private */ protected function nativeFocus_pasteHandler(event:flash.events.Event):void { if(!this._isEditable || !this._isEnabled) { return; } var pastedText:String = Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT) as String; if(pastedText === null) { //the clipboard doesn't contain any text to paste return; } //new lines are not allowed pastedText = pastedText.replace(/[\\n\\r]/g, """"); if(this._restrict) { pastedText = this._restrict.filterText(pastedText); } this.replaceSelectedText(pastedText); } } } ",12062,False,2189.0580539467924,median "package fairygui { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.InteractiveObject; import flash.display.Stage; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.MouseEvent; import flash.events.TouchEvent; import flash.filters.ColorMatrixFilter; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.TextField; import flash.text.TextFieldType; import flash.ui.Mouse; import flash.utils.getTimer; import fairygui.event.DragEvent; import fairygui.event.GTouchEvent; import fairygui.event.IBubbleEvent; import fairygui.utils.ColorMatrix; import fairygui.utils.GTimers; import fairygui.utils.SimpleDispatcher; import fairygui.utils.ToolSet; [Event(name = ""startDrag"", type = ""fairygui.event.DragEvent"")] [Event(name = ""endDrag"", type = ""fairygui.event.DragEvent"")] [Event(name = ""dragMoving"", type = ""fairygui.event.DragEvent"")] [Event(name = ""beginGTouch"", type = ""fairygui.event.GTouchEvent"")] [Event(name = ""endGTouch"", type = ""fairygui.event.GTouchEvent"")] [Event(name = ""dragGTouch"", type = ""fairygui.event.GTouchEvent"")] [Event(name = ""clickGTouch"", type = ""fairygui.event.GTouchEvent"")] public class GObject extends EventDispatcher { public var packageItem:PackageItem; public static var draggingObject:GObject; public var sourceWidth:Number; public var sourceHeight:Number; public var initWidth:Number; public var initHeight:Number; public var minWidth:Number; public var minHeight:Number; public var maxWidth:Number; public var maxHeight:Number; private var _x:Number; private var _y:Number; private var _alpha:Number; private var _rotation:Number; private var _visible:Boolean; private var _touchable:Boolean; private var _grayed:Boolean; private var _draggable:Boolean; private var _scaleX:Number; private var _scaleY:Number; private var _skewX:Number; private var _skewY:Number; private var _pivotX:Number; private var _pivotY:Number; private var _pivotAsAnchor:Boolean; private var _pivotOffsetX:Number; private var _pivotOffsetY:Number; private var _sortingOrder:int; private var _internalVisible:Boolean; private var _handlingController:Boolean; private var _focusable:Boolean; private var _tooltips:String; private var _pixelSnapping:Boolean; private var _data:Object; private var _relations:Relations; private var _group:GGroup; private var _gears:Vector.; private var _displayObject:DisplayObject; private var _dragBounds:Rectangle; protected var _yOffset:int; //Size的实现方式,有两种,0-GObject的w/h等于DisplayObject的w/h。1-GObject的sourceWidth/sourceHeight等于DisplayObject的w/h,剩余部分由scale实现 protected var _sizeImplType:int; internal var _parent:GComponent; internal var _dispatcher:SimpleDispatcher; internal var _width:Number; internal var _height:Number; internal var _rawWidth:Number; internal var _rawHeight:Number; internal var _id:String; internal var _name:String; internal var _underConstruct:Boolean; internal var _gearLocked:Boolean; internal var _sizePercentInGroup:Number; internal static var _gInstanceCounter:uint; internal static const XY_CHANGED:int = 1; internal static const SIZE_CHANGED:int = 2; internal static const SIZE_DELAY_CHANGE:int = 3; public function GObject() { _x = 0; _y = 0; _width = 0; _height = 0; _rawWidth = 0; _rawHeight = 0; sourceWidth = 0; sourceHeight = 0; initWidth = 0; initHeight = 0; minWidth = 0; minHeight = 0; maxWidth = 0; maxHeight = 0; _id = ""_n"" + _gInstanceCounter++; _name = """"; _alpha = 1; _rotation = 0; _visible = true; _internalVisible = true; _touchable = true; _scaleX = 1; _scaleY = 1; _skewX=0; _skewY=0; _pivotX = 0; _pivotY = 0; _pivotOffsetX = 0; _pivotOffsetY = 0; createDisplayObject(); _relations = new Relations(this); _dispatcher = new SimpleDispatcher(); _gears = new Vector.(8, true); } final public function get id():String { return _id; } final public function get name():String { return _name; } final public function set name(value:String):void { _name = value; } final public function set data(data:Object):void { this._data = data; } final public function get data():Object { return this._data; } final public function get x():Number { return _x; } final public function set x(value:Number):void { setXY(value, _y); } final public function get y():Number { return _y; } final public function set y(value:Number):void { setXY(_x, value); } final public function setXY(xv:Number, yv:Number):void { if(_x!=xv || _y!=yv) { var dx:Number = xv-_x; var dy:Number = yv-_y; _x = xv; _y = yv; handlePositionChanged(); if(this is GGroup) GGroup(this).moveChildren(dx, dy); updateGear(1); if (parent != null && !(parent is GList)) { _parent.setBoundsChangedFlag(); if (_group != null) _group.setBoundsChangedFlag(); _dispatcher.dispatch(this, XY_CHANGED); } if (draggingObject == this && !sUpdateInDragging) this.localToGlobalRect(0,0,this.width,this.height,sGlobalRect); } } final public function get xMin():Number { return _pivotAsAnchor ? (_x - _width * _pivotX) : _x; } final public function set xMin(value:Number):void { if (_pivotAsAnchor) setXY(value + _width * _pivotX, _y); else setXY(value, _y); } final public function get yMin():Number { return _pivotAsAnchor ? (_y - _height * _pivotY) : _y; } final public function set yMin(value:Number):void { if (_pivotAsAnchor) setXY(_x, value + _height * _pivotY); else setXY(_x, value); } public function get pixelSnapping():Boolean { return _pixelSnapping; } public function set pixelSnapping(value:Boolean):void { if(_pixelSnapping!=value) { _pixelSnapping = value; handlePositionChanged(); } } public function center(restraint:Boolean=false):void { var r:GComponent; if (parent != null) r = parent; else r = this.root; this.setXY(int((r.width-this.width)/2), int((r.height-this.height)/2)); if (restraint) { this.addRelation(r, RelationType.Center_Center); this.addRelation(r, RelationType.Middle_Middle); } } final public function get width():Number { if(!this._underConstruct) { ensureSizeCorrect(); if(_relations.sizeDirty) _relations.ensureRelationsSizeCorrect(); } return _width; } final public function set width(value:Number):void { setSize(value, _rawHeight); } final public function get height():Number { if(!this._underConstruct) { ensureSizeCorrect(); if(_relations.sizeDirty) _relations.ensureRelationsSizeCorrect(); } return _height; } final public function set height(value:Number):void { setSize(_rawWidth, value); } public function setSize(wv:Number, hv:Number, ignorePivot:Boolean = false):void { if(_rawWidth!=wv || _rawHeight!=hv) { _rawWidth = wv; _rawHeight = hv; if(wv0 && wv>maxWidth) wv = maxWidth; if(maxHeight>0 && hv>maxHeight) hv = maxHeight; var dWidth:Number = wv-_width; var dHeight:Number = hv-_height; _width = wv; _height = hv; handleSizeChanged(); if(_pivotX!=0 || _pivotY!=0) { if(!_pivotAsAnchor) { if(!ignorePivot) this.setXY(this.x-_pivotX*dWidth, this.y-_pivotY*dHeight); updatePivotOffset(); } else applyPivot(); } if (this is GGroup) GGroup(this).resizeChildren(dWidth, dHeight); updateGear(2); if(_parent) { _parent.setBoundsChangedFlag(); _relations.onOwnerSizeChanged(dWidth, dHeight, _pivotAsAnchor || !ignorePivot); if (_group != null) _group.setBoundsChangedFlag(true); } _dispatcher.dispatch(this, SIZE_CHANGED); } } public function ensureSizeCorrect():void { } final public function get actualWidth():Number { return this.width*_scaleX; } final public function get actualHeight():Number { return this.height*_scaleY; } final public function get scaleX():Number { return _scaleX; } final public function set scaleX(value:Number):void { setScale(value, _scaleY); } final public function get scaleY():Number { return _scaleY; } final public function set scaleY(value:Number):void { setScale(_scaleX, value); } final public function setScale(sx:Number, sy:Number):void { if(_scaleX!=sx || _scaleY!=sy) { _scaleX = sx; _scaleY = sy; handleScaleChanged(); applyPivot(); updateGear(2); } } final public function get skewX():Number { return _skewX; } public function set skewX(value:Number):void { setSkew(value, _skewY); } final public function get skewY():Number { return _skewY; } public function set skewY(value:Number):void { setSkew(_skewX, value); } public function setSkew(xv:Number, yv:Number):void { if(_skewX!=xv || _skewY!=yv) { _skewX = xv; _skewY = yv; if(_displayObject!=null) { var skewMatrix:Matrix=this._displayObject.transform.matrix; var angleX:Number =_skewX*Math.PI/180; var angleY:Number =_skewY*Math.PI/180; skewMatrix.b = Math.tan(angleY); skewMatrix.c= Math.tan(angleX); this._displayObject.transform.matrix=skewMatrix; updatePivotOffset(); } } } final public function get pivotX():Number { return _pivotX; } final public function set pivotX(value:Number):void { setPivot(value, _pivotY); } final public function get pivotY():Number { return _pivotY; } final public function set pivotY(value:Number):void { setPivot(_pivotX, value); } final public function setPivot(xv:Number, yv:Number, asAnchor:Boolean=false):void { if(_pivotX!=xv || _pivotY!=yv || _pivotAsAnchor!=asAnchor) { _pivotX = xv; _pivotY = yv; _pivotAsAnchor = asAnchor; updatePivotOffset(); handlePositionChanged(); } } final public function get pivotAsAnchor():Boolean { return _pivotAsAnchor; } protected function internalSetPivot(xv:Number, yv:Number, asAnchor:Boolean):void { _pivotX = xv; _pivotY = yv; _pivotAsAnchor = asAnchor; if(_pivotAsAnchor) handlePositionChanged(); } private function updatePivotOffset():void { if(_skewX!=0||_skewY!=0) { if(_displayObject!=null) { //GObject的特点是旋转和缩放不影响坐标,所以要有一个GObject坐标和DisplayObject坐标的转换。pivotOffset就是两个坐标的偏移值 if(_pivotX!=0 || _pivotY!=0) { var pt:Point = transformCoords(_displayObject.transform.matrix, _pivotX*_width, _pivotY*_height); _pivotOffsetX = _pivotX*_width - (pt.x - _displayObject.x); _pivotOffsetY = _pivotY*_height - (pt.y - _displayObject.y); } else { _pivotOffsetX = 0; _pivotOffsetY = 0; } } }else { updatePivotOffset1(); } } private function updatePivotOffset1():void { if(_pivotX!=0 || _pivotY!=0) { var rot:Number = this.normalizeRotation; if(rot!=0 || _scaleX!=1 || _scaleY!=1) { var rotInRad:Number = rot * ToolSet.DEG_TO_RAD; var cos:Number = Math.cos(rotInRad); var sin:Number = Math.sin(rotInRad); var a:Number = _scaleX * cos; var b:Number = _scaleX * sin; var c:Number = _scaleY * -sin; var d:Number = _scaleY * cos; var px:Number = _pivotX * _width; var py:Number = _pivotY * _height; _pivotOffsetX = px - (a * px + c * py); _pivotOffsetY = py - (d * py + b * px); } else { _pivotOffsetX = 0; _pivotOffsetY = 0; } } else { _pivotOffsetX = 0; _pivotOffsetY = 0; } } public static function transformCoords(matrix:Matrix, x:Number, y:Number,out:Point=null):Point { if (out == null) out = new Point(); out.x = matrix.a * x + matrix.c * y + matrix.tx; out.y = matrix.d * y + matrix.b * x + matrix.ty; return out; } private function applyPivot():void { if(_pivotX!=0 || _pivotY!=0) { updatePivotOffset(); handlePositionChanged(); } } final public function get touchable():Boolean { return _touchable; } public function set touchable(value:Boolean):void { if(_touchable!=value) { _touchable = value; updateGear(3); if((this is GImage) || (this is GMovieClip) || (this is GTextField) && !(this is GTextInput) && !(this is GRichTextField)) //Touch is not supported by GImage/GMovieClip/GTextField return; if(_displayObject is InteractiveObject) { if(this is GComponent) { GComponent(this).handleTouchable(_touchable); } else { InteractiveObject(_displayObject).mouseEnabled = _touchable; if(_displayObject is DisplayObjectContainer) DisplayObjectContainer(_displayObject).mouseChildren = _touchable; } } } } final public function get grayed():Boolean { return _grayed; } public function set grayed(value:Boolean):void { if(_grayed!=value) { _grayed = value; handleGrayedChanged(); updateGear(3); } } final public function get enabled():Boolean { return !_grayed && _touchable; } public function set enabled(value:Boolean):void { this.grayed = !value; this.touchable = value; } final public function get rotation():Number { return _rotation; } public function set rotation(value:Number):void { if(_rotation!=value) { _rotation = value; if(_displayObject) _displayObject.rotation = this.normalizeRotation; applyPivot(); updateGear(3); } } public function get normalizeRotation():Number { var rot:Number = _rotation%360; if(rot>180) rot = rot-360; else if(rot<-180) rot = 360+rot; return rot; } final public function get alpha():Number { return _alpha; } public function set alpha(value:Number):void { if(_alpha!=value) { _alpha = value; handleAlphaChanged(); updateGear(3); } } final public function get visible():Boolean { return _visible; } public function set visible(value:Boolean):void { if(_visible!=value) { _visible = value; handleVisibleChanged(); if(_parent) _parent.setBoundsChangedFlag(); } } public function get internalVisible():Boolean { return _internalVisible && (!_group || _group.internalVisible); } public function get internalVisible2():Boolean { return _visible && (!_group || _group.internalVisible2); } final public function get sortingOrder():int { return _sortingOrder; } public function set sortingOrder(value:int):void { if(value<0) value = 0; if(_sortingOrder!=value) { var old:int = _sortingOrder; _sortingOrder = value; if(_parent!=null) _parent.childSortingOrderChanged(this, old, _sortingOrder); } } final public function get focusable():Boolean { return _focusable; } public function set focusable(value:Boolean):void { _focusable = value; } public function get focused():Boolean { return this.root.focus == this; } public function requestFocus():void { var p:GObject = this; while(p && !p._focusable) p = p.parent; if(p!=null) this.root.focus = p; } final public function get tooltips():String { return _tooltips; } public function set tooltips(value:String):void { if(_tooltips && Mouse.supportsCursor) { this.removeEventListener(MouseEvent.ROLL_OVER, __rollOver); this.removeEventListener(MouseEvent.ROLL_OUT, __rollOut); } _tooltips = value; if(_tooltips && Mouse.supportsCursor) { this.addEventListener(MouseEvent.ROLL_OVER, __rollOver); this.addEventListener(MouseEvent.ROLL_OUT, __rollOut); } } private function __rollOver(evt:Event):void { GTimers.inst.callDelay(100, __doShowTooltips); } private function __doShowTooltips():void { var r:GRoot = this.root; if(r) this.root.showTooltips(_tooltips); } private function __rollOut(evt:Event):void { GTimers.inst.remove(__doShowTooltips); this.root.hideTooltips(); } public function get blendMode():String { return _displayObject.blendMode; } public function set blendMode(value:String):void { _displayObject.blendMode = value; } public function get filters():Array { return _displayObject.filters; } public function set filters(value:Array):void { _displayObject.filters = value; } final public function get inContainer():Boolean { return _displayObject!=null && _displayObject.parent!=null; } final public function get onStage():Boolean { return _displayObject!=null && _displayObject.stage!=null; } final public function get resourceURL():String { if(packageItem!=null) return ""ui://""+packageItem.owner.id + packageItem.id; else return null; } final public function set group(value:GGroup):void { if (_group != value) { if (_group != null) _group.setBoundsChangedFlag(true); _group = value; if (_group != null) _group.setBoundsChangedFlag(true); handleVisibleChanged(); if (_parent != null) _parent.childStateChanged(this); } } final public function get group():GGroup { return _group; } final public function getGear(index:int):GearBase { var gear:GearBase = _gears[index]; if (gear == null) { switch (index) { case 0: gear = new GearDisplay(this); break; case 1: gear = new GearXY(this); break; case 2: gear = new GearSize(this); break; case 3: gear = new GearLook(this); break; case 4: gear = new GearColor(this); break; case 5: gear = new GearAnimation(this); break; case 6: gear = new GearText(this); break; case 7: gear = new GearIcon(this); break; default: throw new Error(""FairyGUI: invalid gear index!""); } _gears[index] = gear; } return gear; } protected function updateGear(index:int):void { if(_underConstruct || _gearLocked) return; var gear:GearBase = _gears[index]; if ( gear!= null && gear.controller!=null) gear.updateState(); } internal function checkGearController(index:int, c:Controller):Boolean { return _gears[index] != null && _gears[index].controller==c; } internal function updateGearFromRelations(index:int, dx:Number, dy:Number):void { if (_gears[index] != null) _gears[index].updateFromRelations(dx, dy); } internal function addDisplayLock():uint { var gearDisplay:GearDisplay = GearDisplay(_gears[0]); if(gearDisplay && gearDisplay.controller) { var ret:uint = gearDisplay.addLock(); checkGearDisplay(); return ret; } else return 0; } internal function releaseDisplayLock(token:uint):void { var gearDisplay:GearDisplay = GearDisplay(_gears[0]); if(gearDisplay && gearDisplay.controller) { gearDisplay.releaseLock(token); checkGearDisplay(); } } private function checkGearDisplay():void { if(_handlingController) return; var connected:Boolean = _gears[0]==null || GearDisplay(_gears[0]).connected; if(connected!=_internalVisible) { _internalVisible = connected; if(_parent) _parent.childStateChanged(this); } } final public function get gearXY():GearXY { return GearXY(getGear(1)); } final public function get gearSize():GearSize { return GearSize(getGear(2)); } final public function get gearLook():GearLook { return GearLook(getGear(3)); } final public function get relations():Relations { return _relations; } final public function addRelation(target:GObject, relationType:int, usePercent:Boolean = false):void { _relations.add(target, relationType, usePercent); } final public function removeRelation(target:GObject, relationType:int):void { _relations.remove(target, relationType); } final public function get displayObject():DisplayObject { return _displayObject; } final protected function setDisplayObject(value:DisplayObject):void { _displayObject = value; } final public function get parent():GComponent { return _parent; } final public function set parent(val:GComponent):void { _parent = val; } final public function removeFromParent():void { if(_parent) _parent.removeChild(this); } public function get root():GRoot { if(this is GRoot) return GRoot(this); var p:GObject = _parent; while(p) { if(p is GRoot) return GRoot(p); p = p.parent; } return GRoot.inst; } final public function get asCom():GComponent { return this as GComponent; } final public function get asButton():GButton { return this as GButton; } final public function get asLabel():GLabel { return this as GLabel; } final public function get asProgress():GProgressBar { return this as GProgressBar; } final public function get asTextField():GTextField { return this as GTextField; } final public function get asRichTextField():GRichTextField { return this as GRichTextField; } final public function get asTextInput():GTextInput { return this as GTextInput; } final public function get asLoader():GLoader { return this as GLoader; } final public function get asList():GList { return this as GList; } final public function get asGraph():GGraph { return this as GGraph; } final public function get asGroup():GGroup { return this as GGroup; } final public function get asSlider():GSlider { return this as GSlider; } final public function get asComboBox():GComboBox { return this as GComboBox; } final public function get asImage():GImage { return this as GImage; } final public function get asMovieClip():GMovieClip { return this as GMovieClip; } public function get text():String { return null; } public function set text(value:String):void { } public function get icon():String { return null; } public function set icon(value:String):void { } public function dispose():void { removeFromParent(); _relations.dispose(); } public function addClickListener(listener:Function):void { addEventListener(GTouchEvent.CLICK, listener); } public function removeClickListener(listener:Function):void { removeEventListener(GTouchEvent.CLICK, listener); } public function hasClickListener():Boolean { return hasEventListener(GTouchEvent.CLICK); } public function addXYChangeCallback(listener:Function):void { _dispatcher.addListener(XY_CHANGED, listener); } public function addSizeChangeCallback(listener:Function):void { _dispatcher.addListener(SIZE_CHANGED, listener); } internal function addSizeDelayChangeCallback(listener:Function):void { _dispatcher.addListener(SIZE_DELAY_CHANGE, listener); } public function removeXYChangeCallback(listener:Function):void { _dispatcher.removeListener(XY_CHANGED, listener); } public function removeSizeChangeCallback(listener:Function):void { _dispatcher.removeListener(SIZE_CHANGED, listener); } internal function removeSizeDelayChangeCallback(listener:Function):void { _dispatcher.removeListener(SIZE_DELAY_CHANGE, listener); } override public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void { super.addEventListener(type, listener, false, priority, useWeakReference); if(_displayObject!=null) { if(MTOUCH_EVENTS.indexOf(type)!=-1) initMTouch(); else { if(type==""rightClick"" && (this is GComponent)) GComponent(this).opaque = true; _displayObject.addEventListener(type, _reDispatch, useCapture, priority, useWeakReference); } } } override public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void { super.removeEventListener(type, listener, false); if(_displayObject!=null && !this.hasEventListener(type)) { _displayObject.removeEventListener(type, _reDispatch, true); _displayObject.removeEventListener(type, _reDispatch, false); } } private function _reDispatch(evt:Event):void { var nevt:Event = evt.clone(); this.dispatchEvent(nevt); if(evt.bubbles && (nevt is IBubbleEvent) && IBubbleEvent(nevt).propagationStopped) evt.stopPropagation(); } final public function get draggable():Boolean { return _draggable; } final public function set draggable(value:Boolean):void { if (_draggable != value) { _draggable = value; initDrag(); } } final public function get dragBounds():Rectangle { return _dragBounds; } final public function set dragBounds(value:Rectangle):void { _dragBounds = value; } public function startDrag(touchPointID:int=-1):void { if (_displayObject.stage==null) return; dragBegin(null); triggerDown(touchPointID); } public function stopDrag():void { dragEnd(); } public function get dragging():Boolean { return draggingObject==this; } public function localToGlobal(ax:Number=0, ay:Number=0):Point { if(_pivotAsAnchor) { ax += _pivotX*_width; ay += _pivotY*_height; } sHelperPoint.x = ax; sHelperPoint.y = ay; return _displayObject.localToGlobal(sHelperPoint); } public function globalToLocal(ax:Number=0, ay:Number=0):Point { sHelperPoint.x = ax; sHelperPoint.y = ay; var pt:Point = _displayObject.globalToLocal(sHelperPoint); if(_pivotAsAnchor) { pt.x -= _pivotX*_width; pt.y -= _pivotY*_height; } return pt; } public function localToRoot(ax:Number=0, ay:Number=0):Point { if(_pivotAsAnchor) { ax += _pivotX*_width; ay += _pivotY*_height; } sHelperPoint.x = ax; sHelperPoint.y = ay; var pt:Point = _displayObject.localToGlobal(sHelperPoint); pt.x /= GRoot.contentScaleFactor; pt.y /= GRoot.contentScaleFactor; return pt; } public function rootToLocal(ax:Number=0, ay:Number=0):Point { sHelperPoint.x = ax; sHelperPoint.y = ay; sHelperPoint.x *= GRoot.contentScaleFactor; sHelperPoint.y *= GRoot.contentScaleFactor; var pt:Point = _displayObject.globalToLocal(sHelperPoint); if(_pivotAsAnchor) { pt.x -= _pivotX*_width; pt.y -= _pivotY*_height; } return pt; } public function localToGlobalRect(ax:Number=0, ay:Number=0, aWidth:Number=0, aHeight:Number=0, resultRect:Rectangle = null):Rectangle { if(resultRect==null) resultRect = new Rectangle(); var pt:Point = this.localToGlobal(ax, ay); resultRect.x = pt.x; resultRect.y = pt.y; pt = this.localToGlobal(ax+aWidth, ay+aHeight); resultRect.right = pt.x; resultRect.bottom = pt.y; return resultRect; } public function globalToLocalRect(ax:Number=0, ay:Number=0, aWidth:Number=0, aHeight:Number=0, resultRect:Rectangle = null):Rectangle { if(resultRect==null) resultRect = new Rectangle(); var pt:Point = this.globalToLocal(ax, ay); resultRect.x = pt.x; resultRect.y = pt.y; pt = this.globalToLocal(ax+aWidth, ay+aHeight); resultRect.right = pt.x; resultRect.bottom = pt.y; return resultRect; } protected function createDisplayObject():void { } protected function switchDisplayObject(newObj:DisplayObject):void { if(newObj==_displayObject) return; var old:DisplayObject = _displayObject; if(_displayObject.parent!=null) { var i:int = _displayObject.parent.getChildIndex(_displayObject); _displayObject.parent.addChildAt(newObj, i); _displayObject.parent.removeChild(_displayObject); } _displayObject = newObj; _displayObject.x = old.x; _displayObject.y = old.y; _displayObject.rotation = old.rotation; _displayObject.alpha = old.alpha; _displayObject.visible = old.visible; _displayObject.scaleX = old.scaleX; _displayObject.scaleY = old.scaleY; _displayObject.filters = old.filters; old.filters = null; if((_displayObject is InteractiveObject) && (old is InteractiveObject)) { InteractiveObject(_displayObject).mouseEnabled = InteractiveObject(old).mouseEnabled; if(_displayObject is DisplayObjectContainer) DisplayObjectContainer(_displayObject).mouseChildren = DisplayObjectContainer(old).mouseChildren; } } protected function handlePositionChanged():void { if(_displayObject) { var xv:Number = _x; var yv:Number = _y+_yOffset; if(_pivotAsAnchor) { xv -= _pivotX*_width; yv -= _pivotY*_height; } if(_pixelSnapping) { xv = Math.round(xv); yv = Math.round(yv); } _displayObject.x = xv+_pivotOffsetX; _displayObject.y = yv+_pivotOffsetY; } } protected function handleSizeChanged():void { if(_displayObject!=null && _sizeImplType==1 && sourceWidth!=0 && sourceHeight!=0) { _displayObject.scaleX = _width/sourceWidth*_scaleX; _displayObject.scaleY = _height/sourceHeight*_scaleY; } } protected function handleScaleChanged():void { if(_displayObject!=null) { if( _sizeImplType==0 || sourceWidth==0 || sourceHeight==0) { _displayObject.scaleX = _scaleX; _displayObject.scaleY = _scaleY; } else { _displayObject.scaleX = _width/sourceWidth*_scaleX; _displayObject.scaleY = _height/sourceHeight*_scaleY; } } } public function handleControllerChanged(c:Controller):void { _handlingController = true; for (var i:int = 0; i < 8; i++) { var gear:GearBase = _gears[i]; if (gear != null && gear.controller == c) gear.apply(); } _handlingController = false; checkGearDisplay(); } protected function handleGrayedChanged():void { if(_displayObject) { if(_grayed) _displayObject.filters = ToolSet.GRAY_FILTERS; else _displayObject.filters = null; } } protected function handleAlphaChanged():void { if(_displayObject) _displayObject.alpha = _alpha; } internal function handleVisibleChanged():void { if(_displayObject) _displayObject.visible = internalVisible2; } public function constructFromResource():void { } public function setup_beforeAdd(xml:XML):void { var str:String; var arr:Array; _id = xml.@id; _name = xml.@name; str = xml.@xy; arr = str.split("",""); this.setXY(parseInt(arr[0]), parseInt(arr[1])); str = xml.@size; if(str) { arr = str.split("",""); initWidth = parseInt(arr[0]); initHeight = parseInt(arr[1]); setSize(initWidth,initHeight, true); } str = xml.@restrictSize; if(str) { arr = str.split("",""); minWidth = parseInt(arr[0]); maxWidth = parseInt(arr[1]); minHeight = parseInt(arr[2]); maxHeight= parseInt(arr[3]); } str = xml.@scale; if(str) { arr = str.split("",""); setScale(parseFloat(arr[0]), parseFloat(arr[1])); } str = xml.@skew; if(str) { arr = str.split("",""); setSkew(parseFloat(arr[0]),parseFloat(arr[1])); } str = xml.@rotation; if(str) this.rotation = parseFloat(str); str = xml.@alpha; if(str) this.alpha = parseFloat(str); str = xml.@pivot; if(str) { arr = str.split("",""); str = xml.@anchor; this.setPivot(parseFloat(arr[0]), parseFloat(arr[1]), str==""true""); } if(xml.@touchable==""false"") this.touchable = false; if(xml.@visible==""false"") this.visible = false; if(xml.@grayed==""true"") this.grayed = true; this.tooltips = xml.@tooltips; str = xml.@blend; if (str) this.blendMode = str; str = xml.@filter; if (str) { switch (str) { case ""color"": str = xml.@filterData; arr = str.split("",""); var cm:ColorMatrix = new ColorMatrix(); cm.adjustBrightness(parseFloat(arr[0])); cm.adjustContrast(parseFloat(arr[1])); cm.adjustSaturation(parseFloat(arr[2])); cm.adjustHue(parseFloat(arr[3])); var cf:ColorMatrixFilter = new ColorMatrixFilter(cm); this.filters = [cf]; break; } } str = xml.@customData; if(str) this.data = str; } private static var GearXMLKeys:Object = { ""gearDisplay"":0, ""gearXY"":1, ""gearSize"":2, ""gearLook"":3, ""gearColor"":4, ""gearAni"":5, ""gearText"":6, ""gearIcon"":7 }; public function setup_afterAdd(xml:XML):void { var s:String = xml.@group; if(s) _group = _parent.getChildById(s) as GGroup; var col:Object = xml.elements(); for each(var cxml:XML in col) { var index:* = GearXMLKeys[cxml.name().localName]; if(index!=undefined) getGear(int(index)).setup(cxml); } } internal function setLang(xml:XML):void { if(String(xml.@tooltips).length) { tooltips=xml.@tooltips; } var col:Object = xml.elements(); for each(var cxml:XML in col) { var index:* = GearXMLKeys[cxml.name().localName]; if(index!=undefined && int(index)==6)//只更新文本 { getGear(int(index)).setLang(cxml); } } } public function get disabled():Boolean { return _touchable; } /** *禁用 透明度变成 0.3 * @param value * */ public function set disabled(value:Boolean):void { this.alpha=value?0.3:1; this.touchable = !value; } //touch support //------------------------------------------------------------------- private var _touchPointId:int; private var _lastClick:int; private var _buttonStatus:int; private var _touchDownPoint:Point; private static const MTOUCH_EVENTS:Array = [GTouchEvent.BEGIN, GTouchEvent.DRAG, GTouchEvent.END, GTouchEvent.CLICK]; public function get isDown():Boolean { return _buttonStatus==1; } public function triggerDown(touchPointID:int=-1):void { var st:Stage = _displayObject.stage; if(st!=null) { _buttonStatus = 1; if(!GRoot.touchPointInput) { _displayObject.stage.addEventListener(MouseEvent.MOUSE_UP, __stageMouseup, false, 20); if(hasEventListener(GTouchEvent.DRAG)) _displayObject.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mousemove); } else { _touchPointId = touchPointID; _displayObject.stage.addEventListener(TouchEvent.TOUCH_END, __stageMouseup, false, 20); if(hasEventListener(GTouchEvent.DRAG)) _displayObject.stage.addEventListener(TouchEvent.TOUCH_MOVE, __mousemove); } } } private function initMTouch():void { if(this is GComponent) { /*GComponent is by default not opaque for optimization. if a click listener registered, we set opaque to true */ GComponent(this).opaque = true; } if(!GRoot.touchPointInput) { _displayObject.addEventListener(MouseEvent.MOUSE_DOWN, __mousedown); _displayObject.addEventListener(MouseEvent.MOUSE_UP, __mouseup); } else { _displayObject.addEventListener(TouchEvent.TOUCH_BEGIN, __mousedown); _displayObject.addEventListener(TouchEvent.TOUCH_END, __mouseup); } } private function __mousedown(evt:Event):void { var devt:GTouchEvent = new GTouchEvent(GTouchEvent.BEGIN); devt.copyFrom(evt); this.dispatchEvent(devt); if(devt.isPropagationStop) evt.stopPropagation(); if(_touchDownPoint==null) _touchDownPoint = new Point(); if(!GRoot.touchPointInput) { _touchDownPoint.x = MouseEvent(evt).stageX; _touchDownPoint.y = MouseEvent(evt).stageY; triggerDown(); } else { _touchDownPoint.x = TouchEvent(evt).stageX; _touchDownPoint.y = TouchEvent(evt).stageY; triggerDown(TouchEvent(evt).touchPointID); } } private function __mousemove(evt:Event):void { if(_buttonStatus!=1 || GRoot.touchPointInput && _touchPointId!=TouchEvent(evt).touchPointID) return; if(GRoot.touchPointInput) { var sensitivity:int = UIConfig.touchDragSensitivity; if(_touchDownPoint!=null && Math.abs(_touchDownPoint.x - TouchEvent(evt).stageX) < sensitivity && Math.abs(_touchDownPoint.y - TouchEvent(evt).stageY) < sensitivity) return; } else { sensitivity = UIConfig.clickDragSensitivity; if(_touchDownPoint!=null && Math.abs(_touchDownPoint.x - MouseEvent(evt).stageX) < sensitivity && Math.abs(_touchDownPoint.y - MouseEvent(evt).stageY) < sensitivity) return; } var devt:GTouchEvent = new GTouchEvent(GTouchEvent.DRAG); devt.copyFrom(evt); this.dispatchEvent(devt); if(devt.isPropagationStop) evt.stopPropagation(); } private function __mouseup(evt:Event):void { if(_buttonStatus!=1 || GRoot.touchPointInput && _touchPointId!=TouchEvent(evt).touchPointID) return; _buttonStatus = 2; } private function __stageMouseup(evt:Event):void { if(!GRoot.touchPointInput) { evt.currentTarget.removeEventListener(MouseEvent.MOUSE_UP, __stageMouseup); evt.currentTarget.removeEventListener(MouseEvent.MOUSE_MOVE, __mousemove); } else { if(_touchPointId!=TouchEvent(evt).touchPointID) return; evt.currentTarget.removeEventListener(TouchEvent.TOUCH_END, __stageMouseup); evt.currentTarget.removeEventListener(TouchEvent.TOUCH_MOVE, __mousemove); } if(_buttonStatus==2) { var cc:int = 1; var now:int = getTimer(); if(now-_lastClick<500) { cc = 2; _lastClick = 0; } else _lastClick = now; var devt:GTouchEvent = new GTouchEvent(GTouchEvent.CLICK); devt.copyFrom(evt, cc); this.dispatchEvent(devt); if(devt.isPropagationStop) { var p:GObject = this.parent; while(p!=null) { p._buttonStatus = 0; p = p.parent; } } } _buttonStatus = 0; devt = new GTouchEvent(GTouchEvent.END); devt.copyFrom(evt); this.dispatchEvent(devt); } public function cancelClick():void { _buttonStatus = 0; var cnt:int = GComponent(this).numChildren; for(var i:int=0;i rect.right) { xx = rect.right - sGlobalRect.width; if (xx < rect.x) xx = rect.x; } if(yy < rect.y) yy = rect.y; else if(yy + sGlobalRect.height > rect.bottom) { yy = rect.bottom - sGlobalRect.height; if(yy < rect.y) yy = rect.y; } } sUpdateInDragging = true; var pt:Point = this.parent.globalToLocal(xx, yy); this.setXY(Math.round(pt.x), Math.round(pt.y)); sUpdateInDragging = false; var dragEvent:DragEvent = new DragEvent(DragEvent.DRAG_MOVING); dragEvent.stageX = evt.stageX; dragEvent.stageY = evt.stageY; dragEvent.touchPointID = evt.touchPointID; dispatchEvent(dragEvent); } private function __dragEnd(evt:GTouchEvent):void { if (draggingObject==this) { stopDrag(); var dragEvent:DragEvent = new DragEvent(DragEvent.DRAG_END); dragEvent.stageX = evt.stageX; dragEvent.stageY = evt.stageY; dragEvent.touchPointID = evt.touchPointID; dispatchEvent(dragEvent); } } //------------------------------------------------------------------- } } ",12275,False,2361.5976082366606,median "/* HelloWorld.ino Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Demonstrate hardware based inversion of the display. The special command 0x0a7 is used for this. Only some display controller support this command: SSD1306 and compatible controller ST7565 and compatible controller Maybe also others support this command. Consult the datasheet... */ #include #include #ifdef U8X8_HAVE_HW_SPI #include #endif #ifdef U8X8_HAVE_HW_I2C #include #endif /* U8g2lib Example Overview: Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only. This is a page buffer example. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Picture Loop Page Buffer) // The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8g2setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8G2_NULL u8g2(U8G2_R0); // null device, a 8x8 pixel display which does nothing //U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_3W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_1_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SSD1306_128X64_ALT0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8G2_SH1106_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8G2_SH1106_128X64_WINSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8G2_SH1106_72X40_WISE_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_PIMORONI_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_128X128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1107_SEEED_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_128X32_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8G2_SSD1306_48X64_WINSTAR_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1306_72X40_ER_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.42"" OLED //U8G2_SSD1322_NHD_256X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_256X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD0323_OS128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1326_ER_256X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8G2_SSD1327_SEEED_96X96_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_MIDAS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); /* Uno: A4=SDA, A5=SCL, add ""u8g2.setBusClock(400000);"" into setup() for speedup if possible */ //U8G2_SSD1327_WS_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_WS_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_VISIONOX_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_ADAFRUIT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X64_RAYSTAR_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1316_128X32_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1317_96X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // not tested, not confirmed //U8G2_SSD1318_128X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1318_128X96_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_1_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_KS0108_ERM19264_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*dc=*/ 17, /*cs0=*/ 14, /*cs1=*/ 15, /*cs2=*/ 16, /* reset=*/ U8X8_PIN_NONE); // Set R/W to low! //U8G2_ST7920_192X32_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ U8X8_PIN_NONE, /*dc=*/ 17, /*reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_192X32_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18 /* A4 */, /*cs=*/ U8X8_PIN_NONE, /*dc/rs=*/ 17 /* A3 */, /*reset=*/ 15 /* A1 */); // Remember to set R/W to 0 //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, /* clock=*/ 14, /* data=*/ 13, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_1_HW_SPI u8g2(U8G2_R0, /* CS=*/ 15, /* reset=*/ 16); // Feather HUZZAH ESP8266, E=clock=14, RW=data=13, RS=CS //U8G2_ST7565_EA_DOGM128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_KS0713_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_KS0713_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // KS0713 controller //U8G2_ST7565_LX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_ERC12864_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // contrast improved version for ERC12864 //U8G2_ST7565_NHD_C12832_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_OS12864_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_64X32_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7567_HEM6432_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST75256_JLX172104_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX19296_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_WO256X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 9, /* data=*/ 8, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 6, /* reset=*/ 5); // MKR Zero, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160M_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_ALT_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_ST75320_JLX320240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Uno, Enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_1_6800 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8G2_IST3020_ERC19264_1_8080 u8g2(U8G2_R0, 44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8G2_IST3020_ERC19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_IST7920_128X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_IST7920_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Round display //U8G2_LC7981_160X80_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_160X160_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_LC7981_240X64_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RW with GND //U8G2_SED1520_122X32_1 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*dc=*/ A0, /*e1=*/ A3, /*e2=*/ A2, /* reset=*/ A4); // Set R/W to low! //U8G2_T6963_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_128X64_ALT_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable/wr=*/ 17, /*cs/ce=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_SED1330_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_RA8835_NHD_240X128_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect /RD = E with +5V, enable is /WR = RW, FG with GND, 14=Uno Pin A0 //U8G2_RA8835_NHD_240X128_1_6800 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // A0 is dc pin, /WR = RW = GND, enable is /RD = E //U8G2_UC1601_128X32_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1601_128X32_1_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_DEM240064_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1608_ERC240120_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due ERC24064-1 Test Setup //U8G2_UC1610_EA_DOGXL160_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8G2_UC1611_EW50850_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1611_CG160160_1_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 17); // Connect WR1 and CD1 pin with 3.3V, connect CS0 with cs, WR0 with enable, CD with dc //U8G2_UC1617_JLX128128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1617_JLX128128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1638_160X128_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8G2_SSD1607_GD_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_SSD1607_WS_200X200_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Waveshare //U8G2_IL3820_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // WaveShare 2.9 inch eInk/ePaper Display, enable 16 bit mode for this display! //U8G2_IL3820_V2_296X128_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // ePaper Display, lesser flickering and faster speed, enable 16 bit mode for this display! //U8G2_LS013B7DH03_128X128_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS027B7DH01_400X240_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_LS013B7DH05_144X168_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ 8); // there is no DC line for this display //U8G2_ST7511_AVD_320X240_1_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable/WR=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // Enable U8g2 16Bit Mode and connect RD pin with 3.3V/5V // End of constructor list void setup(void) { /* U8g2 Project: SSD1306 Test Board */ //pinMode(10, OUTPUT); //pinMode(9, OUTPUT); //digitalWrite(10, 0); //digitalWrite(9, 0); /* U8g2 Project: T6963 Test Board */ //pinMode(18, OUTPUT); //digitalWrite(18, 1); /* U8g2 Project: KS0108 Test Board */ //pinMode(16, OUTPUT); //digitalWrite(16, 0); /* U8g2 Project: LC7981 Test Board, connect RW to GND */ //pinMode(17, OUTPUT); //digitalWrite(17, 0); /* U8g2 Project: Pax Instruments Shield: Enable Backlight */ //pinMode(6, OUTPUT); //digitalWrite(6, 0); u8g2.begin(); u8g2.firstPage(); do { u8g2.setFont(u8g2_font_ncenB10_tr); u8g2.drawStr(0,24,""Hello World!""); } while ( u8g2.nextPage() ); } void loop(void) { delay(1000); u8g2.sendF(""c"", 0x0a7); delay(1000); u8g2.sendF(""c"", 0x0a6); } ",16256,True,5113.213360824173,median "/* Feathers Copyright 2012-2015 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls { import feathers.core.FeathersControl; import feathers.core.IFeathersControl; import feathers.core.ITextRenderer; import feathers.core.IValidating; import feathers.core.PropertyProxy; import feathers.events.FeathersEventType; import feathers.layout.HorizontalLayout; import feathers.layout.LayoutBoundsResult; import feathers.layout.ViewPortBounds; import feathers.skins.IStyleProvider; import feathers.system.DeviceCapabilities; import flash.display.Stage; import flash.display.StageDisplayState; import flash.events.FullScreenEvent; import flash.geom.Point; import flash.system.Capabilities; import starling.core.Starling; import starling.display.DisplayObject; import starling.events.Event; /** * A header that displays an optional title along with a horizontal regions * on the sides for additional UI controls. The left side is typically for * navigation (to display a back button, for example) and the right for * additional actions. The title is displayed in the center by default, * but it may be aligned to the left or right if there are no items on the * desired side. * *

In the following example, a header is created, given a title, and a * back button:

* * * var header:Header = new Header(); * header.title = ""I'm a header""; * * var backButton:Button = new Button(); * backButton.label = ""Back""; * backButton.styleNameList.add( Button.ALTERNATE_STYLE_NAME_BACK_BUTTON ); * backButton.addEventListener( Event.TRIGGERED, backButton_triggeredHandler ); * header.leftItems = new <DisplayObject>[ backButton ]; * * this.addChild( header ); * * @see ../../../help/header.html How to use the Feathers Header component */ public class Header extends FeathersControl { /** * @private */ protected static const INVALIDATION_FLAG_LEFT_CONTENT:String = ""leftContent""; /** * @private */ protected static const INVALIDATION_FLAG_RIGHT_CONTENT:String = ""rightContent""; /** * @private */ protected static const INVALIDATION_FLAG_CENTER_CONTENT:String = ""centerContent""; /** * @private */ protected static const IOS_STATUS_BAR_HEIGHT:Number = 20; /** * @private */ protected static const IOS_DPI:Number = 132; /** * @private */ protected static const IOS_NAME_PREFIX:String = ""iPhone OS ""; /** * @private */ protected static const STATUS_BAR_MIN_IOS_VERSION:int = 7; /** * The default IStyleProvider for all Header * components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * The title will appear in the center of the header. * * @see #titleAlign */ public static const TITLE_ALIGN_CENTER:String = ""center""; /** * The title will appear on the left of the header, if there is no other * content on that side. If there is content, the title will appear in * the center. * * @see #titleAlign */ public static const TITLE_ALIGN_PREFER_LEFT:String = ""preferLeft""; /** * The title will appear on the right of the header, if there is no * other content on that side. If there is content, the title will * appear in the center. * * @see #titleAlign */ public static const TITLE_ALIGN_PREFER_RIGHT:String = ""preferRight""; /** * The items will be aligned to the top of the bounds. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_TOP:String = ""top""; /** * The items will be aligned to the middle of the bounds. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_MIDDLE:String = ""middle""; /** * The items will be aligned to the bottom of the bounds. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_BOTTOM:String = ""bottom""; /** * The default value added to the styleNameList of the header's * items. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_ITEM:String = ""feathers-header-item""; /** * The default value added to the styleNameList of the header's * title. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_TITLE:String = ""feathers-header-title""; /** * @private */ private static const HELPER_BOUNDS:ViewPortBounds = new ViewPortBounds(); /** * @private */ private static const HELPER_LAYOUT_RESULT:LayoutBoundsResult = new LayoutBoundsResult(); /** * @private */ private static const HELPER_POINT:Point = new Point(); /** * Constructor. */ public function Header() { super(); this.addEventListener(Event.ADDED_TO_STAGE, header_addedToStageHandler); this.addEventListener(Event.REMOVED_FROM_STAGE, header_removedFromStageHandler); } /** * The text renderer for the header's title. * *

For internal use in subclasses.

* * @see #title * @see #titleFactory * @see #createTitle() */ protected var titleTextRenderer:ITextRenderer; /** * The value added to the styleNameList of the header's * title text renderer. This variable is protected so that * sub-classes can customize the title text renderer style name in their * constructors instead of using the default style name defined by * DEFAULT_CHILD_STYLE_NAME_TITLE. * * @see feathers.core.FeathersControl#styleNameList */ protected var titleStyleName:String = DEFAULT_CHILD_STYLE_NAME_TITLE; /** * The value added to the styleNameList of each of the * header's items. This variable is protected so that * sub-classes can customize the item style name in their constructors * instead of using the default style name defined by * DEFAULT_CHILD_STYLE_NAME_ITEM. * * @see feathers.core.FeathersControl#styleNameList */ protected var itemStyleName:String = DEFAULT_CHILD_STYLE_NAME_ITEM; /** * @private */ protected var leftItemsWidth:Number = 0; /** * @private */ protected var rightItemsWidth:Number = 0; /** * @private * The layout algorithm. Shared by both sides. */ protected var _layout:HorizontalLayout; /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return Header.globalStyleProvider; } /** * @private */ protected var _title:String = """"; /** * The text displayed for the header's title. * *

In the following example, the header's title is set:

* * * header.title = ""I'm a Header""; * * @default """" * * @see #titleFactory */ public function get title():String { return this._title; } /** * @private */ public function set title(value:String):void { if(value === null) { value = """"; } if(this._title == value) { return; } this._title = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _titleFactory:Function; /** * A function used to instantiate the header's title text renderer * sub-component. By default, the header will use the global text * renderer factory, FeathersControl.defaultTextRendererFactory(), * to create the title text renderer. The title text renderer must be an * instance of ITextRenderer. This factory can be used to * change properties on the title text renderer when it is first * created. For instance, if you are skinning Feathers components * without a theme, you might use this factory to style the title text * renderer. * *

If you are not using a theme, the title factory can be used to * provide skin the title with appropriate text styles.

* *

The factory should have the following function signature:

*
function():ITextRenderer
* *

In the following example, a custom title factory is passed to the * header:

* * * header.titleFactory = function():ITextRenderer * { * var titleRenderer:TextFieldTextRenderer = new TextFieldTextRenderer(); * titleRenderer.textFormat = new TextFormat( ""_sans"", 12, 0xff0000 ); * return titleRenderer; * } * * @default null * * @see #title * @see feathers.core.ITextRenderer * @see feathers.core.FeathersControl#defaultTextRendererFactory */ public function get titleFactory():Function { return this._titleFactory; } /** * @private */ public function set titleFactory(value:Function):void { if(this._titleFactory == value) { return; } this._titleFactory = value; this.invalidate(INVALIDATION_FLAG_TEXT_RENDERER); } /** * @private */ protected var _disposeItems:Boolean = true; /** * Determines if the leftItems, centerItems, * and rightItems are disposed or not when the header is * disposed. * *

If you change this value to false, you must dispose * the items manually. Failing to dispose the items may result in a * memory leak.

* * @default true */ public function get disposeItems():Boolean { return this._disposeItems; } /** * @private */ public function set disposeItems(value:Boolean):void { this._disposeItems = value; } /** * @private */ protected var _leftItems:Vector.; /** * The UI controls that appear in the left region of the header. * *

In the following example, a back button is displayed on the left * side of the header:

* * * var backButton:Button = new Button(); * backButton.label = ""Back""; * backButton.styleNameList.add( Button.ALTERNATE_STYLE_NAME_BACK_BUTTON ); * backButton.addEventListener( Event.TRIGGERED, backButton_triggeredHandler ); * header.leftItems = new <DisplayObject>[ backButton ]; * * @default null */ public function get leftItems():Vector. { return this._leftItems; } /** * @private */ public function set leftItems(value:Vector.):void { if(this._leftItems == value) { return; } if(this._leftItems) { for each(var item:DisplayObject in this._leftItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.remove(this.itemStyleName); item.removeEventListener(FeathersEventType.RESIZE, item_resizeHandler); } item.removeFromParent(); } } this._leftItems = value; if(this._leftItems) { for each(item in this._leftItems) { if(item is IFeathersControl) { item.addEventListener(FeathersEventType.RESIZE, item_resizeHandler); } } } this.invalidate(INVALIDATION_FLAG_LEFT_CONTENT); } /** * @private */ protected var _centerItems:Vector.; /** * The UI controls that appear in the center region of the header. If * centerItems is not null, and the * titleAlign property is Header.TITLE_ALIGN_CENTER, * the title text renderer will be hidden. * *

In the following example, a settings button is displayed in the * center of the header:

* * * var settingsButton:Button = new Button(); * settingsButton.label = ""Settings""; * settingsButton.addEventListener( Event.TRIGGERED, settingsButton_triggeredHandler ); * header.centerItems = new <DisplayObject>[ settingsButton ]; * * @default null */ public function get centerItems():Vector. { return this._centerItems; } /** * @private */ public function set centerItems(value:Vector.):void { if(this._centerItems == value) { return; } if(this._centerItems) { for each(var item:DisplayObject in this._centerItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.remove(this.itemStyleName); item.removeEventListener(FeathersEventType.RESIZE, item_resizeHandler); } item.removeFromParent(); } } this._centerItems = value; if(this._centerItems) { for each(item in this._centerItems) { if(item is IFeathersControl) { item.addEventListener(FeathersEventType.RESIZE, item_resizeHandler); } } } this.invalidate(INVALIDATION_FLAG_CENTER_CONTENT); } /** * @private */ protected var _rightItems:Vector.; /** * The UI controls that appear in the right region of the header. * *

In the following example, a settings button is displayed on the * right side of the header:

* * * var settingsButton:Button = new Button(); * settingsButton.label = ""Settings""; * settingsButton.addEventListener( Event.TRIGGERED, settingsButton_triggeredHandler ); * header.rightItems = new <DisplayObject>[ settingsButton ]; * * @default null */ public function get rightItems():Vector. { return this._rightItems; } /** * @private */ public function set rightItems(value:Vector.):void { if(this._rightItems == value) { return; } if(this._rightItems) { for each(var item:DisplayObject in this._rightItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.remove(this.itemStyleName); item.removeEventListener(FeathersEventType.RESIZE, item_resizeHandler); } item.removeFromParent(); } } this._rightItems = value; if(this._rightItems) { for each(item in this._rightItems) { if(item is IFeathersControl) { item.addEventListener(FeathersEventType.RESIZE, item_resizeHandler); } } } this.invalidate(INVALIDATION_FLAG_RIGHT_CONTENT); } /** * Quickly sets all padding properties to the same value. The * padding getter always returns the value of * paddingTop, but the other padding values may be * different. * *

In the following example, the header's padding is set to 20 pixels:

* * * header.padding = 20; * * @default 0 * * @see #paddingTop * @see #paddingRight * @see #paddingBottom * @see #paddingLeft */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The minimum space, in pixels, between the header's top edge and the * header's content. * *

In the following example, the header's top padding is set to 20 * pixels:

* * * header.paddingTop = 20; * * @default 0 */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingRight:Number = 0; /** * The minimum space, in pixels, between the header's right edge and the * header's content. * *

In the following example, the header's right padding is set to 20 * pixels:

* * * header.paddingRight = 20; * * @default 0 */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The minimum space, in pixels, between the header's bottom edge and * the header's content. * *

In the following example, the header's bottom padding is set to 20 * pixels:

* * * header.paddingBottom = 20; * * @default 0 */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The minimum space, in pixels, between the header's left edge and the * header's content. * *

In the following example, the header's left padding is set to 20 * pixels:

* * * header.paddingLeft = 20; * * @default 0 */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _gap:Number = 0; /** * Space, in pixels, between items. The same value is used with the * leftItems and rightItems. * *

Set the titleGap to make the gap on the left and * right of the title use a different value.

* *

In the following example, the header's gap between items is set to * 20 pixels:

* * * header.gap = 20; * * @default 0 * * @see #titleGap * @see #leftItems * @see #rightItems */ public function get gap():Number { return _gap; } /** * @private */ public function set gap(value:Number):void { if(this._gap == value) { return; } this._gap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _titleGap:Number = NaN; /** * Space, in pixels, between the title and the left or right groups of * items. If NaN (the default), the default gap * property is used instead. * *

In the following example, the header's title gap is set to 20 * pixels:

* * * header.titleGap = 20; * * @default NaN * * @see #gap */ public function get titleGap():Number { return _titleGap; } /** * @private */ public function set titleGap(value:Number):void { if(this._titleGap == value) { return; } this._titleGap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _useExtraPaddingForOSStatusBar:Boolean = false; /** * If enabled, the header's top padding will be increased to account for * the height of the OS status bar when the app is rendered under the OS * status bar. The header will not add extra padding to apps that aren't * rendered under the OS status bar. * *

iOS started rendering apps that aren't full screen under the OS * status bar in version 7.

* *

In the following example, the header's padding will account for * the iOS status bar height:

* * * header.useExtraPaddingForOSStatusBar = true; * * @default false; * * @see #paddingTop */ public function get useExtraPaddingForOSStatusBar():Boolean { return this._useExtraPaddingForOSStatusBar; } /** * @private */ public function set useExtraPaddingForOSStatusBar(value:Boolean):void { if(this._useExtraPaddingForOSStatusBar == value) { return; } this._useExtraPaddingForOSStatusBar = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _verticalAlign:String = VERTICAL_ALIGN_MIDDLE; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * The alignment of the items vertically, on the y-axis. * *

In the following example, the header's vertical alignment is set * to the middle:

* * * header.verticalAlign = Header.VERTICAL_ALIGN_MIDDLE; * * @default Header.VERTICAL_ALIGN_MIDDLE * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get verticalAlign():String { return this._verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this._verticalAlign == value) { return; } this._verticalAlign = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var originalBackgroundWidth:Number = NaN; /** * @private */ protected var originalBackgroundHeight:Number = NaN; /** * @private */ protected var currentBackgroundSkin:DisplayObject; /** * @private */ protected var _backgroundSkin:DisplayObject; /** * A display object displayed behind the header's content. * *

In the following example, the header's background skin is set to * a Quad:

* * * header.backgroundSkin = new Quad( 10, 10, 0xff0000 ); * * @default null */ public function get backgroundSkin():DisplayObject { return this._backgroundSkin; } /** * @private */ public function set backgroundSkin(value:DisplayObject):void { if(this._backgroundSkin == value) { return; } if(this._backgroundSkin && this._backgroundSkin != this._backgroundDisabledSkin) { this.removeChild(this._backgroundSkin); } this._backgroundSkin = value; if(this._backgroundSkin && this._backgroundSkin.parent != this) { this._backgroundSkin.visible = false; this.addChildAt(this._backgroundSkin, 0); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _backgroundDisabledSkin:DisplayObject; /** * A background to display when the header is disabled. If the property * is null, the value of the backgroundSkin * property will be used instead. * *

In the following example, the header's disabled background skin is * set to a Quad:

* * * header.backgroundDisabledSkin = new Quad( 10, 10, 0x999999 ); * * @default null */ public function get backgroundDisabledSkin():DisplayObject { return this._backgroundDisabledSkin; } /** * @private */ public function set backgroundDisabledSkin(value:DisplayObject):void { if(this._backgroundDisabledSkin == value) { return; } if(this._backgroundDisabledSkin && this._backgroundDisabledSkin != this._backgroundSkin) { this.removeChild(this._backgroundDisabledSkin); } this._backgroundDisabledSkin = value; if(this._backgroundDisabledSkin && this._backgroundDisabledSkin.parent != this) { this._backgroundDisabledSkin.visible = false; this.addChildAt(this._backgroundDisabledSkin, 0); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _customTitleStyleName:String; /** * A style name to add to the header's title text renderer * sub-component. Typically used by a theme to provide different styles * to different headers. * *

In the following example, a custom title style name is passed to * the header:

* * * header.customTitleStyleName = ""my-custom-header-title""; * *

In your theme, you can target this sub-component style name to * provide different styles than the default:

* * * getStyleProviderForClass( BitmapFontTextRenderer ).setFunctionForStyleName( ""my-custom-header-title"", setCustomHeaderTitleStyles ); * * @default null * * @see #DEFAULT_CHILD_STYLE_NAME_TITLE * @see feathers.core.FeathersControl#styleNameList * @see #titleFactory */ public function get customTitleStyleName():String { return this._customTitleStyleName; } /** * @private */ public function set customTitleStyleName(value:String):void { if(this._customTitleStyleName == value) { return; } this._customTitleStyleName = value; this.invalidate(INVALIDATION_FLAG_TEXT_RENDERER); } /** * @private */ protected var _titleProperties:PropertyProxy; /** * An object that stores properties for the header's title text renderer * sub-component, and the properties will be passed down to the text * renderer when the header validates. The available properties * depend on which ITextRenderer implementation is returned * by textRendererFactory. Refer to * feathers.core.ITextRenderer * for a list of available text renderer implementations. * *

In the following example, some properties are set for the header's * title text renderer (this example assumes that the title text renderer * is a BitmapFontTextRenderer):

* * * header.titleProperties.textFormat = new BitmapFontTextFormat( bitmapFont ); * header.titleProperties.wordWrap = true; * *

If the subcomponent has its own subcomponents, their properties * can be set too, using attribute @ notation. For example, * to set the skin on the thumb which is in a SimpleScrollBar, * which is in a List, you can use the following syntax:

*
list.verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);
* *

Setting properties in a titleFactory function instead * of using titleProperties will result in better * performance.

* * @default null * * @see #titleFactory * @see feathers.core.ITextRenderer */ public function get titleProperties():Object { if(!this._titleProperties) { this._titleProperties = new PropertyProxy(titleProperties_onChange); } return this._titleProperties; } /** * @private */ public function set titleProperties(value:Object):void { if(this._titleProperties == value) { return; } if(value && !(value is PropertyProxy)) { value = PropertyProxy.fromObject(value); } if(this._titleProperties) { this._titleProperties.removeOnChangeCallback(titleProperties_onChange); } this._titleProperties = PropertyProxy(value); if(this._titleProperties) { this._titleProperties.addOnChangeCallback(titleProperties_onChange); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _titleAlign:String = TITLE_ALIGN_CENTER; [Inspectable(type=""String"",enumeration=""center,preferLeft,preferRight"")] /** * The preferred position of the title. If leftItems and/or * rightItems are not null, the title may be * forced to the center even if the preferred position is on the left or * right. If centerItems is not null, and the * title is centered, the title will be hidden. * *

In the following example, the header's title aligment is set to * prefer the left side:

* * * header.titleAlign = Header.TITLE_ALIGN_PREFER_LEFT; * * @default Header.TITLE_ALIGN_CENTER * * @see #TITLE_ALIGN_CENTER * @see #TITLE_ALIGN_PREFER_LEFT * @see #TITLE_ALIGN_PREFER_RIGHT */ public function get titleAlign():String { return this._titleAlign; } /** * @private */ public function set titleAlign(value:String):void { if(this._titleAlign == value) { return; } this._titleAlign = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ override public function dispose():void { if(this._disposeItems) { for each(var item:DisplayObject in this._leftItems) { item.dispose(); } for each(item in this._centerItems) { item.dispose(); } for each(item in this._rightItems) { item.dispose(); } } this.leftItems = null; this.rightItems = null; this.centerItems = null; super.dispose(); } /** * @private */ override protected function initialize():void { if(!this._layout) { this._layout = new HorizontalLayout(); this._layout.useVirtualLayout = false; this._layout.verticalAlign = HorizontalLayout.VERTICAL_ALIGN_MIDDLE; } } /** * @private */ override protected function draw():void { var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); var leftContentInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_LEFT_CONTENT); var rightContentInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_RIGHT_CONTENT); var centerContentInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_CENTER_CONTENT); var textRendererInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_TEXT_RENDERER); if(textRendererInvalid) { this.createTitle(); } if(textRendererInvalid || dataInvalid) { this.titleTextRenderer.text = this._title; } if(stateInvalid || stylesInvalid) { this.refreshBackground(); } if(textRendererInvalid || stylesInvalid || sizeInvalid) { this.refreshLayout(); } if(textRendererInvalid || stylesInvalid) { this.refreshTitleStyles(); } if(leftContentInvalid) { if(this._leftItems) { for each(var item:DisplayObject in this._leftItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.add(this.itemStyleName); } this.addChild(item); } } } if(rightContentInvalid) { if(this._rightItems) { for each(item in this._rightItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.add(this.itemStyleName); } this.addChild(item); } } } if(centerContentInvalid) { if(this._centerItems) { for each(item in this._centerItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.add(this.itemStyleName); } this.addChild(item); } } } if(stateInvalid || textRendererInvalid) { this.refreshEnabled(); } sizeInvalid = this.autoSizeIfNeeded() || sizeInvalid; if(sizeInvalid || stylesInvalid) { this.layoutBackground(); } if(sizeInvalid || leftContentInvalid || rightContentInvalid || centerContentInvalid || stylesInvalid) { this.leftItemsWidth = 0; this.rightItemsWidth = 0; if(this._leftItems) { this.layoutLeftItems(); } if(this._rightItems) { this.layoutRightItems(); } if(this._centerItems) { this.layoutCenterItems(); } } if(textRendererInvalid || sizeInvalid || stylesInvalid || dataInvalid || leftContentInvalid || rightContentInvalid || centerContentInvalid) { this.layoutTitle(); } } /** * If the component's dimensions have not been set explicitly, it will * measure its content and determine an ideal size for itself. If the * explicitWidth or explicitHeight member * variables are set, those value will be used without additional * measurement. If one is set, but not the other, the dimension with the * explicit value will not be measured, but the other non-explicit * dimension will still need measurement. * *

Calls setSizeInternal() to set up the * actualWidth and actualHeight member * variables used for layout.

* *

Meant for internal use, and subclasses may override this function * with a custom implementation.

*/ protected function autoSizeIfNeeded():Boolean { var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN if(!needsWidth && !needsHeight) { return false; } var newWidth:Number = needsWidth ? (this._paddingLeft + this._paddingRight) : this.explicitWidth; var newHeight:Number = needsHeight ? 0 : this.explicitHeight; var totalItemWidth:Number = 0; var leftItemCount:int = this._leftItems ? this._leftItems.length : 0; for(var i:int = 0; i < leftItemCount; i++) { var item:DisplayObject = this._leftItems[i]; if(item is IValidating) { IValidating(item).validate(); } var itemWidth:Number = item.width; if(needsWidth && itemWidth === itemWidth) //!isNaN { totalItemWidth += itemWidth; if(i > 0) { totalItemWidth += this._gap; } } var itemHeight:Number = item.height; if(needsHeight && itemHeight === itemHeight && //!isNaN itemHeight > newHeight) { newHeight = itemHeight; } } var centerItemCount:int = this._centerItems ? this._centerItems.length : 0; for(i = 0; i < centerItemCount; i++) { item = this._centerItems[i]; if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width; if(needsWidth && itemWidth === itemWidth) //!isNaN { totalItemWidth += itemWidth; if(i > 0) { totalItemWidth += this._gap; } } itemHeight = item.height; if(needsHeight && itemHeight === itemHeight && //!isNaN itemHeight > newHeight) { newHeight = itemHeight; } } var rightItemCount:int = this._rightItems ? this._rightItems.length : 0; for(i = 0; i < rightItemCount; i++) { item = this._rightItems[i]; if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width if(needsWidth && itemWidth === itemWidth) //!isNaN { totalItemWidth += itemWidth; if(i > 0) { totalItemWidth += this._gap; } } itemHeight = item.height; if(needsHeight && itemHeight === itemHeight && //!isNaN itemHeight > newHeight) { newHeight = itemHeight; } } newWidth += totalItemWidth; if(this._title && !(this._titleAlign == TITLE_ALIGN_CENTER && this._centerItems)) { var calculatedTitleGap:Number = this._titleGap; if(calculatedTitleGap !== calculatedTitleGap) //isNaN { calculatedTitleGap = this._gap; } newWidth += 2 * calculatedTitleGap; var maxTitleWidth:Number = (needsWidth ? this._maxWidth : this.explicitWidth) - totalItemWidth; if(leftItemCount > 0) { maxTitleWidth -= calculatedTitleGap; } if(centerItemCount > 0) { maxTitleWidth -= calculatedTitleGap; } if(rightItemCount > 0) { maxTitleWidth -= calculatedTitleGap; } this.titleTextRenderer.maxWidth = maxTitleWidth; this.titleTextRenderer.measureText(HELPER_POINT); var measuredTitleWidth:Number = HELPER_POINT.x; var measuredTitleHeight:Number = HELPER_POINT.y; if(needsWidth && measuredTitleWidth === measuredTitleWidth) //!isNaN { newWidth += measuredTitleWidth; if(leftItemCount > 0) { newWidth += calculatedTitleGap; } if(rightItemCount > 0) { newWidth += calculatedTitleGap; } } if(needsHeight && measuredTitleHeight === measuredTitleHeight && //!isNaN measuredTitleHeight > newHeight) { newHeight = measuredTitleHeight; } } if(needsHeight) { newHeight += this._paddingTop + this._paddingBottom; var extraPaddingTop:Number = this.calculateExtraOSStatusBarPadding(); if(extraPaddingTop > 0) { //account for the minimum height before adding the padding if(newHeight < this._minHeight) { newHeight = this._minHeight; } newHeight += extraPaddingTop; } } if(needsWidth && this.originalBackgroundWidth === this.originalBackgroundWidth && //!isNaN this.originalBackgroundWidth > newWidth) { newWidth = this.originalBackgroundWidth; } if(needsHeight && this.originalBackgroundHeight === this.originalBackgroundHeight && //!isNaN this.originalBackgroundHeight > newHeight) { newHeight = this.originalBackgroundHeight; } return this.setSizeInternal(newWidth, newHeight, false); } /** * Creates and adds the titleTextRenderer sub-component and * removes the old instance, if one exists. * *

Meant for internal use, and subclasses may override this function * with a custom implementation.

* * @see #title * @see #titleTextRenderer * @see #titleFactory */ protected function createTitle():void { if(this.titleTextRenderer) { this.removeChild(DisplayObject(this.titleTextRenderer), true); this.titleTextRenderer = null; } var factory:Function = this._titleFactory != null ? this._titleFactory : FeathersControl.defaultTextRendererFactory; this.titleTextRenderer = ITextRenderer(factory()); var uiTitleRenderer:IFeathersControl = IFeathersControl(this.titleTextRenderer); var titleStyleName:String = this._customTitleStyleName != null ? this._customTitleStyleName : this.titleStyleName; uiTitleRenderer.styleNameList.add(titleStyleName); this.addChild(DisplayObject(uiTitleRenderer)); } /** * @private */ protected function refreshBackground():void { this.currentBackgroundSkin = this._backgroundSkin; if(!this._isEnabled && this._backgroundDisabledSkin) { if(this._backgroundSkin) { this._backgroundSkin.visible = false; } this.currentBackgroundSkin = this._backgroundDisabledSkin; } else if(this._backgroundDisabledSkin) { this._backgroundDisabledSkin.visible = false; } if(this.currentBackgroundSkin) { this.currentBackgroundSkin.visible = true; if(this.originalBackgroundWidth !== this.originalBackgroundWidth) //isNaN { this.originalBackgroundWidth = this.currentBackgroundSkin.width; } if(this.originalBackgroundHeight !== this.originalBackgroundHeight) //isNaN { this.originalBackgroundHeight = this.currentBackgroundSkin.height; } } } /** * @private */ protected function refreshLayout():void { this._layout.gap = this._gap; this._layout.paddingTop = this._paddingTop + this.calculateExtraOSStatusBarPadding(); this._layout.paddingBottom = this._paddingBottom; this._layout.verticalAlign = this._verticalAlign; } /** * @private */ protected function refreshEnabled():void { this.titleTextRenderer.isEnabled = this._isEnabled; } /** * @private */ protected function refreshTitleStyles():void { for(var propertyName:String in this._titleProperties) { var propertyValue:Object = this._titleProperties[propertyName]; this.titleTextRenderer[propertyName] = propertyValue; } } /** * @private */ protected function calculateExtraOSStatusBarPadding():Number { if(!this._useExtraPaddingForOSStatusBar) { return 0; } //first, we check if it's iOS or not. at this time, we only need to //use extra padding on iOS. android and others are fine. var os:String = Capabilities.os; if(os.indexOf(IOS_NAME_PREFIX) != 0 || parseInt(os.substr(IOS_NAME_PREFIX.length, 1), 10) < STATUS_BAR_MIN_IOS_VERSION) { return 0; } //next, we check if the app is full screen or not. if it is full //screen, then the status bar isn't visible, and we don't need the //extra padding. var nativeStage:Stage = Starling.current.nativeStage; if(nativeStage.displayState != StageDisplayState.NORMAL) { return 0; } return IOS_STATUS_BAR_HEIGHT * Math.floor(DeviceCapabilities.dpi / IOS_DPI) / Starling.current.contentScaleFactor; } /** * @private */ protected function layoutBackground():void { if(!this.currentBackgroundSkin) { return; } this.currentBackgroundSkin.width = this.actualWidth; this.currentBackgroundSkin.height = this.actualHeight; } /** * @private */ protected function layoutLeftItems():void { for each(var item:DisplayObject in this._leftItems) { if(item is IValidating) { IValidating(item).validate(); } } HELPER_BOUNDS.x = HELPER_BOUNDS.y = 0; HELPER_BOUNDS.scrollX = HELPER_BOUNDS.scrollY = 0; HELPER_BOUNDS.explicitWidth = this.actualWidth; HELPER_BOUNDS.explicitHeight = this.actualHeight; this._layout.horizontalAlign = HorizontalLayout.HORIZONTAL_ALIGN_LEFT; this._layout.paddingRight = 0; this._layout.paddingLeft = this._paddingLeft; this._layout.layout(this._leftItems, HELPER_BOUNDS, HELPER_LAYOUT_RESULT); this.leftItemsWidth = HELPER_LAYOUT_RESULT.contentWidth; if(this.leftItemsWidth !== this.leftItemsWidth) //isNaN { this.leftItemsWidth = 0; } } /** * @private */ protected function layoutRightItems():void { for each(var item:DisplayObject in this._rightItems) { if(item is IValidating) { IValidating(item).validate(); } } HELPER_BOUNDS.x = HELPER_BOUNDS.y = 0; HELPER_BOUNDS.scrollX = HELPER_BOUNDS.scrollY = 0; HELPER_BOUNDS.explicitWidth = this.actualWidth; HELPER_BOUNDS.explicitHeight = this.actualHeight; this._layout.horizontalAlign = HorizontalLayout.HORIZONTAL_ALIGN_RIGHT; this._layout.paddingRight = this._paddingRight; this._layout.paddingLeft = 0; this._layout.layout(this._rightItems, HELPER_BOUNDS, HELPER_LAYOUT_RESULT); this.rightItemsWidth = HELPER_LAYOUT_RESULT.contentWidth; if(this.rightItemsWidth !== this.rightItemsWidth) //isNaN { this.rightItemsWidth = 0; } } /** * @private */ protected function layoutCenterItems():void { for each(var item:DisplayObject in this._centerItems) { if(item is IValidating) { IValidating(item).validate(); } } HELPER_BOUNDS.x = HELPER_BOUNDS.y = 0; HELPER_BOUNDS.scrollX = HELPER_BOUNDS.scrollY = 0; HELPER_BOUNDS.explicitWidth = this.actualWidth; HELPER_BOUNDS.explicitHeight = this.actualHeight; this._layout.horizontalAlign = HorizontalLayout.HORIZONTAL_ALIGN_CENTER; this._layout.paddingRight = this._paddingRight; this._layout.paddingLeft = this._paddingLeft; this._layout.layout(this._centerItems, HELPER_BOUNDS, HELPER_LAYOUT_RESULT); } /** * @private */ protected function layoutTitle():void { if((this._titleAlign == TITLE_ALIGN_CENTER && this._centerItems) || this._title.length == 0) { this.titleTextRenderer.visible = false; return; } this.titleTextRenderer.visible = true; var calculatedTitleGap:Number = this._titleGap; if(calculatedTitleGap !== calculatedTitleGap) //isNaN { calculatedTitleGap = this._gap; } //left and right offsets already include padding var leftOffset:Number = (this._leftItems && this._leftItems.length > 0) ? (this.leftItemsWidth + calculatedTitleGap) : 0; var rightOffset:Number = (this._rightItems && this._rightItems.length > 0) ? (this.rightItemsWidth + calculatedTitleGap) : 0; if(this._titleAlign == TITLE_ALIGN_PREFER_LEFT && (!this._leftItems || this._leftItems.length == 0)) { this.titleTextRenderer.maxWidth = this.actualWidth - this._paddingLeft - rightOffset; this.titleTextRenderer.validate(); this.titleTextRenderer.x = this._paddingLeft; } else if(this._titleAlign == TITLE_ALIGN_PREFER_RIGHT && (!this._rightItems || this._rightItems.length == 0)) { this.titleTextRenderer.maxWidth = this.actualWidth - this._paddingRight - leftOffset; this.titleTextRenderer.validate(); this.titleTextRenderer.x = this.actualWidth - this._paddingRight - this.titleTextRenderer.width; } else { var actualWidthMinusPadding:Number = this.actualWidth - this._paddingLeft - this._paddingRight; var actualWidthMinusOffsets:Number = this.actualWidth - leftOffset - rightOffset; this.titleTextRenderer.maxWidth = actualWidthMinusOffsets; this.titleTextRenderer.validate(); var idealTitlePosition:Number = this._paddingLeft + (actualWidthMinusPadding - this.titleTextRenderer.width) / 2; if(leftOffset > idealTitlePosition || (idealTitlePosition + this.titleTextRenderer.width) > (this.actualWidth - rightOffset)) { this.titleTextRenderer.x = leftOffset + (actualWidthMinusOffsets - this.titleTextRenderer.width) / 2; } else { this.titleTextRenderer.x = idealTitlePosition; } } var paddingTop:Number = this._paddingTop + this.calculateExtraOSStatusBarPadding(); if(this._verticalAlign == VERTICAL_ALIGN_TOP) { this.titleTextRenderer.y = paddingTop; } else if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { this.titleTextRenderer.y = this.actualHeight - this._paddingBottom - this.titleTextRenderer.height; } else { this.titleTextRenderer.y = paddingTop + (this.actualHeight - paddingTop - this._paddingBottom - this.titleTextRenderer.height) / 2; } } /** * @private */ protected function header_addedToStageHandler(event:Event):void { Starling.current.nativeStage.addEventListener(""fullScreen"", nativeStage_fullScreenHandler); } /** * @private */ protected function header_removedFromStageHandler(event:Event):void { Starling.current.nativeStage.removeEventListener(""fullScreen"", nativeStage_fullScreenHandler); } /** * @private */ protected function nativeStage_fullScreenHandler(event:FullScreenEvent):void { this.invalidate(INVALIDATION_FLAG_SIZE); } /** * @private */ protected function titleProperties_onChange(proxy:PropertyProxy, propertyName:String):void { this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected function item_resizeHandler(event:Event):void { this.invalidate(INVALIDATION_FLAG_SIZE); } } } ",12424,True,2624.266795364124,median " #include ""encoding.h"" #include //SW_UART eshtablishment #include //SW_I2C eshtablishment #include SlowSoftWire Wire = SlowSoftWire(18, 19, true); SlowSoftWire EEPROM = SlowSoftWire(2, 3, true); SoftwareSerial32 ss(15, 16); // RX,TX #define EEPROM_I2C_ADDRESS 0x50 #define ADC_CHANNEL 1 //#define BAT_LOW_LED 1 #define GPS_LED 8 #define STATUS_LED 9 #include Adafruit_MCP3008 adc; int ppm_pin = 17; int ppm_pinmask; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //PID gain and limit settings /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float pid_p_gain_roll = 0.75; //1.875; //Gain setting for the roll P-controller float pid_i_gain_roll = 0.00010; //Gain setting for the roll I-controller float pid_d_gain_roll = 3.5; //Gain setting for the roll D-controller int pid_max_roll = 400; //Maximum output of the PID-controller (+/-) float pid_p_gain_pitch = pid_p_gain_roll; //Gain setting for the pitch P-controller. float pid_i_gain_pitch = pid_i_gain_roll; //Gain setting for the pitch I-controller. float pid_d_gain_pitch = pid_d_gain_roll; //Gain setting for the pitch D-controller. int pid_max_pitch = pid_max_roll; //Maximum output of the PID-controller (+/-) //float pid_p_gain_yaw = 4.0; //Gain setting for the pitch P-controller. //4.0 float pid_p_gain_yaw = 3.5; //Gain setting for the pitch P-controller. //4.0 float pid_i_gain_yaw = 0.02; //Gain setting for the pitch I-controller. //0.02 float pid_d_gain_yaw = 0.0; //Gain setting for the pitch D-controller. int pid_max_yaw = 400; //Maximum output of the PID-controller (+/-) float gps_p_gain = 0.2; //Gain setting for the GPS P-controller (default = 2.7). float gps_d_gain = 0.5; //Gain setting for the GPS D-controller (default = 6.5). boolean auto_level = true; //Auto level on (true) or off (false) /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Declaring global variables /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// byte last_channel_1, last_channel_2, last_channel_3, last_channel_4; byte eeprom_data[36]; byte highByte, lowByte; uint8_t channel_select_counter; int32_t measured_time, measured_time_start; volatile int receiver_input_channel_1, receiver_input_channel_2, receiver_input_channel_3, receiver_input_channel_4, receiver_input_channel_5, receiver_input_channel_6, pid_roll_setpoint_base, pid_pitch_setpoint_base; int esc_1, esc_2, esc_3, esc_4; int throttle, battery_voltage; int cal_int, start, gyro_address; int receiver_input[7]; int16_t temperature; int16_t acc_axis[4], gyro_axis[4]; float roll_level_adjust, pitch_level_adjust; int16_t acc_x, acc_y, acc_z; int acc_total_vector; unsigned long timer_channel_1, timer_channel_2, timer_channel_3, timer_channel_4, esc_timer, esc_loop_timer, esc_loop_timer1, esc_loop_timer2, esc_loop_timer3; unsigned long timer_1, timer_2, timer_3, timer_4, current_time; unsigned long loop_timer, loop_timer1, loop_timer2, loop_timer3, loop_timer4, loop_counter; int gyro_pitch, gyro_roll, gyro_yaw; int gyro_axis_cal[4]; float pid_error_temp; float pid_i_mem_roll, pid_roll_setpoint, gyro_roll_input, pid_output_roll, pid_last_roll_d_error; float pid_i_mem_pitch, pid_pitch_setpoint, gyro_pitch_input, pid_output_pitch, pid_last_pitch_d_error; float pid_i_mem_yaw, pid_yaw_setpoint, gyro_yaw_input, pid_output_yaw, pid_last_yaw_d_error; float angle_roll_acc, angle_pitch_acc, angle_pitch, angle_roll, angle_yaw; boolean gyro_angles_set; uint32_t pin4 = 4; uint32_t pin5 = 5; uint32_t pin6 = 6; uint32_t pin7 = 7; uint32_t bitmask4 = digitalPinToBitMask(pin4); uint32_t bitmask5 = digitalPinToBitMask(pin5); uint32_t bitmask6 = digitalPinToBitMask(pin6); uint32_t bitmask7 = digitalPinToBitMask(pin7); //GPS variables uint8_t read_serial_byte, incomming_message[250], number_used_sats, fix_type; uint8_t waypoint_set, latitude_north, longiude_east ; uint16_t message_counter; int16_t gps_add_counter; int32_t l_lat_gps, l_lon_gps, lat_gps_previous, lon_gps_previous; int32_t lat_gps_actual, lon_gps_actual, l_lat_waypoint, l_lon_waypoint; float gps_pitch_adjust_north, gps_pitch_adjust, gps_roll_adjust_north, gps_roll_adjust; float lat_gps_loop_add, lon_gps_loop_add, lat_gps_add, lon_gps_add; uint8_t new_line_found, new_gps_data_available, new_gps_data_counter; uint8_t gps_rotating_mem_location; int32_t gps_lat_total_avarage, gps_lon_total_avarage; int32_t gps_lat_rotating_mem[40], gps_lon_rotating_mem[40]; int32_t gps_lat_error, gps_lon_error; int32_t gps_lat_error_previous, gps_lon_error_previous; uint32_t gps_watchdog_timer; uint8_t flight_mode, flight_mode_counter, flight_mode_led; int channel = ADC_CHANNEL; int lowExit = 0; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Setup routine /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void setup() { Serial.begin(57600); pinMode(STATUS_LED, OUTPUT); pinMode(GPS_LED, OUTPUT); // pinMode(BAT_LOW_LED, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); delay(2000); Wire.setClock(400000L); Wire.begin(); delay(250); EEPROM.begin(); EEPROM.setClock(400000L); //Start the wire library as master delay(250); delay(550); // Software SPI (specify all, use any available digital) // (sck, mosi, miso, cs); //adc.begin(15, 17, 16, 13); // Assign pins for ADC // adc.begin(13, 11, 12, 10); // Hardware SPI adc.begin();//uses (13, 11, 12, 10-cs); delay(500); Serial.println("">>START""); //Copy the EEPROM data for fast access data. for (start = 0; start <= 35; start++)eeprom_data[start] = EEPROMreadAddr(start); start = 0; //Set start back to zero. gyro_address = eeprom_data[32]; //Store the gyro address in the variable. //GPS setup //Configure digital pins. //Use the led on the Arduino for startup indication. //digitalWrite(STATUS_LED, LOW); //Turn on the warning led. pinMode(ppm_pin, INPUT_PULLUP); ppm_pinmask = digitalPinToBitMask(ppm_pin); //Setup interrupt attachInterrupt(digitalPinToInterrupt(ppm_pin), ISR, RISING); set_csr(mstatus, MSTATUS_MIE); //Check the EEPROM signature to make sure that the setup program is executed. while(eeprom_data[33] != 'J' || eeprom_data[34] != 'M' || eeprom_data[35] != 'B')delay(10); Serial.println("">>Verified-EEPROM""); //The flight controller needs the MPU-6050 with gyro and accelerometer //If setup is completed without MPU-6050 stop the flight controller program if(eeprom_data[31] == 2 || eeprom_data[31] == 3)delay(10); set_gyro_registers(); //Set the specific gyro registers. Serial.println("">>START-GYRO""); for (cal_int = 0; cal_int < 1250 ; cal_int ++){ //Wait 5 seconds before continuing. //Set digital port 4, 5, 6 and 7 high. GPIO_REG(GPIO_OUTPUT_VAL) |= bitmask4 | bitmask5 | bitmask6| bitmask7 ;//HIGH delayMicroseconds(1000); //Wait 1000us. //Set digital port 4, 5, 6 and 7 low. GPIO_REG(GPIO_OUTPUT_VAL) &= ~bitmask4 & (~bitmask5) & (~bitmask6) & (~bitmask7);//LOW delayMicroseconds(3000); //Wait 3000us. } Serial.println("">>Gyro Calib...""); //Let's take multiple gyro data samples so we can determine the average gyro offset (calibration). for (cal_int = 0; cal_int < 2000 ; cal_int ++){ //Take 2000 readings for calibration. digitalWrite(STATUS_LED, LOW); if(cal_int % 15 == 0)digitalWrite(STATUS_LED,HIGH); //Change the led status to indicate calibration. gyro_signalen(); //Read the gyro output. gyro_axis_cal[1] += gyro_axis[1]; //Ad roll value to gyro_roll_cal. gyro_axis_cal[2] += gyro_axis[2]; //Ad pitch value to gyro_pitch_cal. gyro_axis_cal[3] += gyro_axis[3]; //Ad yaw value to gyro_yaw_cal. //We don't want the esc's to be beeping annoyingly. So let's give them a 1000us puls while calibrating the gyro. //Set digital port 4, 5, 6 and 7 high. GPIO_REG(GPIO_OUTPUT_VAL) |= bitmask4 | bitmask5 | bitmask6| bitmask7 ; //HIGH delayMicroseconds(1000); //Wait 1000us. GPIO_REG(GPIO_OUTPUT_VAL) &= ~bitmask4 & (~bitmask5) & (~bitmask6) & (~bitmask7);//LOW delay(3); //Wait 3 milliseconds before the next loop. } Serial.println("">>Calibrated.""); //Now that we have 2000 measures, we need to devide by 2000 to get the average gyro offset. gyro_axis_cal[1] /= 2000; //Divide the roll total by 2000. gyro_axis_cal[2] /= 2000; //Divide the pitch total by 2000. gyro_axis_cal[3] /= 2000; //Divide the yaw total by 2000. Serial.println("">>ReceiverStart...""); //Wait until the receiver is active and the throtle is set to the lower position. while (receiver_input_channel_3 < 990 || receiver_input_channel_3 > 1020 || receiver_input_channel_4 < 1400) { receiver_input_channel_3 = convert_receiver_channel(3); //Convert the actual receiver signals for throttle to the standard 1000 - 2000us receiver_input_channel_4 = convert_receiver_channel(4); //Convert the actual receiver signals for yaw to the standard 1000 - 2000us start ++; //While waiting increment start whith every loop. //We don't want the esc's to be beeping annoyingly. So let's give them a 1000us puls while waiting for the receiver inputs. //Set digital poort 4, 5, 6 and 7 high. GPIO_REG(GPIO_OUTPUT_VAL) |= bitmask4 | bitmask5 | bitmask6 | bitmask7 ; //HIGH delayMicroseconds(1000); //Wait 1000us. //Set digital poort 4, 5, 6 and 7 low. GPIO_REG(GPIO_OUTPUT_VAL) &= ~bitmask4 & (~bitmask5) & (~bitmask6) & (~bitmask7);//LOW delay(3); //Wait 3 milliseconds before the next loop. digitalWrite(STATUS_LED, HIGH); if (start == 125) { //Every 125 loops (500ms). digitalWrite(STATUS_LED, LOW); //Change the led status. start = 0; //Start again at 0. } } start = 0; //Set start back to 0. Serial.println("">>Setup Done.""); gps_setup(); delay(250); //HIFIVE1 does not have analog inputs , hence we use an ADC. Here MCP3008 is used //Load the battery voltage to the battery_voltage variable. //65 is the voltage compensation for the diode. //12.6V equals ~5V @ Analog 0. //12.6V equals 1023 analogRead(0). //1260 / 1023 = 1.2317. //The variable battery_voltage holds 1050 if the battery voltage is 10.5V. // battery_voltage = (analogRead(0) + 65) * 1.2317; // Serial.print(""adc-"");Serial.println(adc.readADC(channel)); battery_voltage = (adc.readADC(channel) + 65) * 1.2317; // no diode is used loop_timer = micros(); //Set the timer for the next loop. //When everything is done, turn off the led. // digitalWrite(STATUS_LED, HIGH); //Turn off the warning led. } int roll=0; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Main program loop /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void loop() { loop_timer = micros(); flight_mode = 0; //In all other situations the flight mode is 1; if (receiver_input_channel_5 >= 1500)flight_mode = 1; //If channel 6 is between 1200us and 1600us the flight mode is 2 // if (channel_5 >= 1600 && channel_5 < 2100)flight_mode = 3; //If channel 6 is between 1600us and 1900us the flight mode is 3 gyro_signalen(); if (gps_add_counter >= 0)gps_add_counter --; read_gps(); //65.5 = 1 deg/sec (check the datasheet of the MPU-6050 for more information). gyro_roll_input = (gyro_roll_input * 0.7) + (((float)gyro_roll / 65.5) * 0.3); //Gyro pid input is deg/sec. gyro_pitch_input = (gyro_pitch_input * 0.7) + (((float)gyro_pitch / 65.5) * 0.3);//Gyro pid input is deg/sec. gyro_yaw_input = (gyro_yaw_input * 0.7) + (((float)gyro_yaw / 65.5) * 0.3); //Gyro pid input is deg/sec. //Gyro angle calculations //for 250HZ //0.0000611 = 1 / 250Hz / 65.5 angle_pitch += (float)gyro_pitch * 0.0000611; //Calculate the traveled pitch angle and add this to the angle_pitch variable. angle_roll += (float)gyro_roll * 0.0000611; //Calculate the traveled roll angle and add this to the angle_roll variable. angle_yaw += (float)gyro_yaw * 0.0000611; //Calculate the traveled yaw angle and add this to the angle_yaw variable. if (angle_yaw < 0) angle_yaw += 360; //If the compass heading becomes smaller then 0, 360 is added to keep it in the 0 till 360 degrees range. else if (angle_yaw >= 360) angle_yaw -= 360; //If the compass heading becomes larger then 360, 360 is subtracted to keep it in the 0 till 360 degrees range. //for 250HZ //0.000001066 = 0.0000611 * (3.142(PI) / 180degr) The Arduino sin function is in radians angle_pitch -= angle_roll * sin((float)gyro_yaw * 0.000001066); //If the IMU has yawed transfer the roll angle to the pitch angel. angle_roll += angle_pitch * sin((float)gyro_yaw * 0.000001066); //If the IMU has yawed transfer the pitch angle to the roll angel. //Accelerometer angle calculations acc_total_vector = sqrt((acc_x * acc_x) + (acc_y * acc_y) + (acc_z * acc_z)); //Calculate the total accelerometer vector. if (abs(acc_y) < acc_total_vector) { //Prevent the asin function to produce a NaN angle_pitch_acc = asin((float)acc_y / acc_total_vector) * 57.296; //Calculate the pitch angle. } if (abs(acc_x) < acc_total_vector) { //Prevent the asin function to produce a NaN angle_roll_acc = asin((float)acc_x / acc_total_vector) * -57.296; //Calculate the roll angle. } //Place the MPU-6050 spirit level and note the values in the following two lines for calibration. angle_pitch_acc -= 0.0; //Accelerometer calibration value for pitch. angle_roll_acc -= 0.00; //Accelerometer calibration value for roll. angle_pitch = angle_pitch * 0.9996 + angle_pitch_acc * 0.0004; //Correct the drift of the gyro pitch angle with the accelerometer pitch angle. angle_roll = angle_roll * 0.9996 + angle_roll_acc * 0.0004; //Correct the drift of the gyro roll angle with the accelerometer roll angle. pitch_level_adjust = angle_pitch * 15; //Calculate the pitch angle correction roll_level_adjust = angle_roll * 15; //Calculate the roll angle correction if (!auto_level) { //If the quadcopter is not in auto-level mode pitch_level_adjust = 0; //Set the pitch angle correction to zero. roll_level_adjust = 0; //Set the roll angle correcion to zero. } pid_roll_setpoint_base = receiver_input_channel_1; //Normally channel_1 is the pid_roll_setpoint input. pid_pitch_setpoint_base = receiver_input_channel_2; //Normally channel_2 is the pid_pitch_setpoint input. if (flight_mode == 1 && waypoint_set == 1) { pid_roll_setpoint_base += gps_roll_adjust; pid_pitch_setpoint_base += gps_pitch_adjust; } //Because we added the GPS adjust values we need to make sure that the control limits are not exceded. if (pid_roll_setpoint_base > 2000)pid_roll_setpoint_base = 2000; if (pid_roll_setpoint_base < 1000)pid_roll_setpoint_base = 1000; if (pid_pitch_setpoint_base > 2000)pid_pitch_setpoint_base = 2000; if (pid_pitch_setpoint_base < 1000)pid_pitch_setpoint_base = 1000; //The PID set point in degrees per second is determined by the roll receiver input. //In the case of deviding by 3 the max roll rate is aprox 164 degrees per second ( (500-8)/3 = 164d/s ). pid_roll_setpoint = 0; //We need a little dead band of 16us for better results. if (receiver_input_channel_1 > 1508)pid_roll_setpoint = pid_roll_setpoint_base - 1508; else if (receiver_input_channel_1 < 1492)pid_roll_setpoint = pid_roll_setpoint_base - 1492; pid_roll_setpoint -= roll_level_adjust; //Subtract the angle correction from the standardized receiver roll input value. pid_roll_setpoint /= 3.0; //Divide the setpoint for the PID roll controller by 3 to get angles in degrees. //The PID set point in degrees per second is determined by the pitch receiver input. //In the case of deviding by 3 the max pitch rate is aprox 164 degrees per second ( (500-8)/3 = 164d/s ). pid_pitch_setpoint = 0; //We need a little dead band of 16us for better results. if (receiver_input_channel_2 > 1508)pid_pitch_setpoint = pid_pitch_setpoint_base - 1508; else if (receiver_input_channel_2 < 1492)pid_pitch_setpoint = pid_pitch_setpoint_base - 1492; pid_pitch_setpoint -= pitch_level_adjust; //Subtract the angle correction from the standardized receiver pitch input value. pid_pitch_setpoint /= 3.0; //Divide the setpoint for the PID pitch controller by 3 to get angles in degrees. //The PID set point in degrees per second is determined by the yaw receiver input. //In the case of deviding by 3 the max yaw rate is aprox 164 degrees per second ( (500-8)/3 = 164d/s ). pid_yaw_setpoint = 0; //We need a little dead band of 16us for better results. if (receiver_input_channel_3 > 1050) { //Do not yaw when turning off the motors. if (receiver_input_channel_4 > 1508)pid_yaw_setpoint = (receiver_input_channel_4 - 1508) / 3.0; else if (receiver_input_channel_4 < 1492)pid_yaw_setpoint = (receiver_input_channel_4 - 1492) / 3.0; } calculate_pid(); //PID inputs are known. So we can calculate the pid output. //For starting the motors: throttle low and yaw left (step 1). if (receiver_input_channel_3 < 1050 && receiver_input_channel_4 < 1050)start = 1; //When yaw stick is back in the center position start the motors (step 2). if (start == 1 && receiver_input_channel_3 < 1050 && receiver_input_channel_4 > 1450) { start = 2; angle_pitch = angle_pitch_acc; //Set the gyro pitch angle equal to the accelerometer pitch angle when the quadcopter is started. angle_roll = angle_roll_acc; //Set the gyro roll angle equal to the accelerometer roll angle when the quadcopter is started. gyro_angles_set = true; //Set the IMU started flag. //Reset the PID controllers for a bumpless start. pid_i_mem_roll = 0; pid_last_roll_d_error = 0; pid_i_mem_pitch = 0; pid_last_pitch_d_error = 0; pid_i_mem_yaw = 0; pid_last_yaw_d_error = 0; } //Stopping the motors: throttle low and yaw right. if (start == 2 && receiver_input_channel_3 < 1050 && receiver_input_channel_4 > 1950)start = 0; //The battery voltage is needed for compensation. //A complementary filter is used to reduce noise. //0.09853 = 0.08 * 1.2317. battery_voltage = battery_voltage * 0.92 + (adc.readADC(channel) + 65) * 0.09853; //Turn on the led if battery voltage is to low. //Serial.println(battery_voltage); if (battery_voltage < 1000 && battery_voltage > 600);//digitalWrite(STATUS_LED, LOW); throttle = receiver_input_channel_3; //We need the throttle signal as a base signal. if (start == 2) { if (throttle > 1800) throttle = 1800; //We need some room to keep full control at full throttle. esc_1 = throttle - pid_output_pitch + pid_output_roll - pid_output_yaw; //Calculate the pulse for esc 1 (front-right - CCW) esc_2 = throttle + pid_output_pitch + pid_output_roll + pid_output_yaw; //Calculate the pulse for esc 2 (rear-right - CW) esc_3 = throttle + pid_output_pitch - pid_output_roll - pid_output_yaw; //Calculate the pulse for esc 3 (rear-left - CCW) esc_4 = throttle - pid_output_pitch - pid_output_roll + pid_output_yaw; //Calculate the pulse for esc 4 (front-left - CW) if (battery_voltage < 1240 && battery_voltage > 800){ //Is the battery connected? esc_1 += esc_1 * ((1240 - battery_voltage)/(float)3500); //Compensate the esc-1 pulse for voltage drop. esc_2 += esc_2 * ((1240 - battery_voltage)/(float)3500); //Compensate the esc-2 pulse for voltage drop. esc_3 += esc_3 * ((1240 - battery_voltage)/(float)3500); //Compensate the esc-3 pulse for voltage drop. esc_4 += esc_4 * ((1240 - battery_voltage)/(float)3500); //Compensate the esc-4 pulse for voltage drop. } if (esc_1 < 1100) esc_1 = 1200; //Keep the motors running. if (esc_2 < 1100) esc_2 = 1200; //Keep the motors running. if (esc_3 < 1100) esc_3 = 1200; //Keep the motors running. if (esc_4 < 1100) esc_4 = 1200; //Keep the motors running. if (esc_1 > 2000)esc_1 = 2000; //Limit the esc-1 pulse to 2000us. if (esc_2 > 2000)esc_2 = 2000; //Limit the esc-2 pulse to 2000us. if (esc_3 > 2000)esc_3 = 2000; //Limit the esc-3 pulse to 2000us. if (esc_4 > 2000)esc_4 = 2000; //Limit the esc-4 pulse to 2000us. } else { esc_1 = 1000; //If start is not 2 keep a 1000us pulse for ess-1. esc_2 = 1000; //If start is not 2 keep a 1000us pulse for ess-2. esc_3 = 1000; //If start is not 2 keep a 1000us pulse for ess-3. esc_4 = 1000; //If start is not 2 keep a 1000us pulse for ess-4. } //////////////////////////////////////////////////////////////////////////////////////////////////// //Creating the pulses for the ESC's is explained in this video: //https://youtu.be/fqEkVcqxtU8 //////////////////////////////////////////////////////////////////////////////////////////////////// //! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! //Because of the angle calculation the loop time is getting very important. If the loop time is //longer or shorter than 4000us the angle calculation is off. If you modify the code make sure //that the loop time is still 4000us and no longer! More information can be found on //the Q&A page: //! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! // loop_timer = micros(); //Set the timer for the next loop. //All the information for controlling the motor's is available. //The refresh rate is 250Hz. That means the esc's need there pulse every 4ms. //if (micros() - loop_timer > 4050)digitalWrite(STATUS_LED, LOW); //Turn on the LED if the loop time exceeds 4050us. while (micros() - loop_timer < 4000); //We wait until 4000us are passed. lowExit = 0; loop_timer = micros(); GPIO_REG(GPIO_OUTPUT_VAL) |= bitmask4 | bitmask5 | bitmask6 | bitmask7 ; //HIGH //Set digital outputs 4,5,6 and 7 high. timer_channel_1 = esc_1 + loop_timer; //Calculate the time of the faling edge of the esc-1 pulse. timer_channel_2 = esc_2 + loop_timer; //Calculate the time of the faling edge of the esc-2 pulse. timer_channel_3 = esc_3 + loop_timer; //Calculate the time of the faling edge of the esc-3 pulse. timer_channel_4 = esc_4 + loop_timer; //Calculate the time of the faling edge of the esc-4 pulse. //There is always 1000us of spare time. So let's do something usefull that is very time consuming. //Get the current gyro and receiver data and scale it to degrees per second for the pid calculations. // while(PORTD >= 16){ while (lowExit < 1) { //Stay in this loop until output 4,5,6 and 7 are low. esc_loop_timer = micros(); //Read the current time. if (timer_channel_1 <= esc_loop_timer) { GPIO_REG(GPIO_OUTPUT_VAL) &= ~bitmask4 ; //Set digital output 4 to low if the time is expired. }//digitalWrite(4,LOW);} if (timer_channel_2 <= esc_loop_timer ) { GPIO_REG(GPIO_OUTPUT_VAL) &= ~bitmask5; //Set digital output 5 to low if the time is expired. }//digitalWrite(5,LOW);} if (timer_channel_3 <= esc_loop_timer ) { GPIO_REG(GPIO_OUTPUT_VAL) &= ~bitmask6; //Set digital output 6 to low if the time is expired. }// digitalWrite(6,LOW);} if (timer_channel_4 <= esc_loop_timer ) { GPIO_REG(GPIO_OUTPUT_VAL) &= ~bitmask7; //Set digital output 7 to low if the time is expired. }//digitalWrite(7,LOW);lowExit=1;} if ( (timer_channel_1 <= esc_loop_timer) && (timer_channel_2 <= esc_loop_timer) && (timer_channel_3 <= esc_loop_timer) && (timer_channel_4 <= esc_loop_timer)) { lowExit = 1; } } /* if(loop_counter == 0)Serial.print(""Pitch: ""); if(loop_counter == 1)Serial.print(angle_pitch, 0 ); if(loop_counter == 2)Serial.print("" Roll: ""); if(loop_counter == 3)Serial.print(angle_roll ,0); if(loop_counter == 4)Serial.print("" Yaw: ""); if(loop_counter == 5)Serial.println(gyro_yaw / 65.5, 0 ); loop_counter ++; if(loop_counter == 60)loop_counter = 0; */ /* Serial.print(esc_1); Serial.print(""---""); Serial.print(esc_2); Serial.print(""---""); Serial.print(esc_3); Serial.print(""---""); Serial.println(esc_4);*/ } void gps_setup(void) { ss.begin(4800); delay(500); // uint8_t Set_to_50Hz[14] = {0xB5, 0x62, 0x06, 0x08, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x01, 0x00, 0x2A, 0x32};//50hz //A small delay is added to give the GPS some time to respond @ 9600bps. //Set the refresh rate to 5Hz by using the ublox protocol. uint8_t Set_to_5Hz[14] = {0xB5, 0x62, 0x06, 0x08, 0x06, 0x00, 0xC8, 0x00, 0x01, 0x00, 0x01, 0x00, 0xDE, 0x6A}; ss.write(Set_to_5Hz, 14); // uint8_t Set_to_10Hz[14] = {0xB5, 0x62, 0x06, 0x08, 0x06, 0x00, 0x64, 0x00, 0x01, 0x00, 0x01, 0x00, 0x7A, 0x12}; //ss.write(Set_to_10Hz, 14); delay(350); //Disable GPGSV messages by using the ublox protocol. uint8_t Disable_GPGSV[16] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x03, 0x00,0x00,0x00,0x00,0x00, 0x01, 0x03,0x39}; ss.write(Disable_GPGSV, 16); delay(350); uint8_t Disable_GPRMC[16] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x04, 0x00,0x00,0x00,0x00,0x00, 0x01, 0x04,0x40}; ss.write(Disable_GPRMC, 16); delay(350); uint8_t Disable_GPVTG[16] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x05, 0x00,0x00,0x00,0x00,0x00, 0x01, 0x05,0x47}; ss.write(Disable_GPVTG, 16); delay(350); } void EEPROMwriteAddr(int Waddress, byte val) { EEPROM.beginTransmission(EEPROM_I2C_ADDRESS); EEPROM.write((int)(Waddress >> 8)); // MSB EEPROM.write((int)(Waddress & 0xFF)); // LSB EEPROM.write(val); EEPROM.endTransmission(); delay(5); } byte EEPROMreadAddr(int Raddress) { byte rData = 0xFF; EEPROM.beginTransmission(EEPROM_I2C_ADDRESS); EEPROM.write((int)(Raddress >> 8)); // MSB EEPROM.write((int)(Raddress & 0xFF)); // LSB EEPROM.endTransmission(); EEPROM.requestFrom(EEPROM_I2C_ADDRESS, 1); rData = EEPROM.read(); return rData; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //This routine is called every time input 8, 9, 10 or 11 changed state. This is used to read the receiver signals. //More information about this subroutine can be found in this video: //https://youtu.be/bENjl1KQbvo /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void ISR() { measured_time = micros() - measured_time_start; if (measured_time < 0)measured_time += 0xFFFF; measured_time_start = micros(); if (measured_time > 3000)channel_select_counter = 0; else channel_select_counter++; if (channel_select_counter == 1)receiver_input[1] = measured_time; if (channel_select_counter == 2)receiver_input[2] = measured_time; if (channel_select_counter == 3)receiver_input[3] = measured_time; if (channel_select_counter == 4)receiver_input[4] = measured_time; if (channel_select_counter == 5)receiver_input[5] = measured_time; if (channel_select_counter == 6)receiver_input[6] = measured_time; // Clear out the interrupt pending bit, or the interrupt will // just happen again as soon as we return, // and we'll never get back into our loop() function. // These are write-one-to-clear. //GPIO_REG(GPIO_FALL_IP) = ppm_pinmask;//use if using FALLING GPIO_REG(GPIO_RISE_IP) = ppm_pinmask; } void receiverInput(void) { //get receiver's input receiver_input_channel_1 = convert_receiver_channel(1); //Convert the actual receiver signals for pitch to the standard 1000 - 2000us. receiver_input_channel_2 = convert_receiver_channel(2); //Convert the actual receiver signals for roll to the standard 1000 - 2000us. receiver_input_channel_3 = convert_receiver_channel(3); //Convert the actual receiver signals for throttle to the standard 1000 - 2000us. receiver_input_channel_4 = convert_receiver_channel(4); //Convert the actual receiver signals for yaw to the standard 1000 - 2000us. receiver_input_channel_5 = receiver_input[5]; receiver_input_channel_6 = receiver_input[6]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Subroutine for reading the gyro /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void gyro_signalen() { //Read the MPU-6050 if (eeprom_data[31] == 1) { Wire.beginTransmission(gyro_address); //Start communication with the gyro. Wire.write(0x3B); //Start reading @ register 43h and auto increment with every read. Wire.endTransmission(); //End the transmission. Wire.requestFrom(gyro_address, 14); //Request 14 bytes from the gyro. receiverInput(); while (Wire.available() < 14); //Wait until the 14 bytes are received. acc_axis[1] = Wire.read() << 8 | Wire.read(); //Add the low and high byte to the acc_x variable. acc_axis[2] = Wire.read() << 8 | Wire.read(); //Add the low and high byte to the acc_y variable. acc_axis[3] = Wire.read() << 8 | Wire.read(); //Add the low and high byte to the acc_z variable. temperature = Wire.read() << 8 | Wire.read(); //Add the low and high byte to the temperature variable. gyro_axis[1] = Wire.read() << 8 | Wire.read(); //Read high and low part of the angular data. gyro_axis[2] = Wire.read() << 8 | Wire.read(); //Read high and low part of the angular data. gyro_axis[3] = Wire.read() << 8 | Wire.read(); //Read high and low part of the angular data. } if (cal_int == 2000) { gyro_axis[1] -= gyro_axis_cal[1]; //Only compensate after the calibration. gyro_axis[2] -= gyro_axis_cal[2]; //Only compensate after the calibration. gyro_axis[3] -= gyro_axis_cal[3]; //Only compensate after the calibration. } gyro_roll = gyro_axis[eeprom_data[28] & 0b00000011]; //Set gyro_roll to the correct axis that was stored in the EEPROM. if (eeprom_data[28] & 0b10000000)gyro_roll *= -1; //Invert gyro_roll if the MSB of EEPROM bit 28 is set. gyro_pitch = gyro_axis[eeprom_data[29] & 0b00000011]; //Set gyro_pitch to the correct axis that was stored in the EEPROM. if (eeprom_data[29] & 0b10000000)gyro_pitch *= -1; //Invert gyro_pitch if the MSB of EEPROM bit 29 is set. gyro_yaw = gyro_axis[eeprom_data[30] & 0b00000011]; //Set gyro_yaw to the correct axis that was stored in the EEPROM. if (eeprom_data[30] & 0b10000000)gyro_yaw *= -1; //Invert gyro_yaw if the MSB of EEPROM bit 30 is set. acc_x = acc_axis[eeprom_data[29] & 0b00000011]; //Set acc_x to the correct axis that was stored in the EEPROM. if (eeprom_data[29] & 0b10000000)acc_x *= -1; //Invert acc_x if the MSB of EEPROM bit 29 is set. acc_y = acc_axis[eeprom_data[28] & 0b00000011]; //Set acc_y to the correct axis that was stored in the EEPROM. if (eeprom_data[28] & 0b10000000)acc_y *= -1; //Invert acc_y if the MSB of EEPROM bit 28 is set. acc_z = acc_axis[eeprom_data[30] & 0b00000011]; //Set acc_z to the correct axis that was stored in the EEPROM. if (eeprom_data[30] & 0b10000000)acc_z *= -1; //Invert acc_z if the MSB of EEPROM bit 30 is set. } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Subroutine for calculating pid outputs /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //The PID controllers are explained in part 5 of the YMFC-3D video session: //https://youtu.be/JBvnB0279-Q /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void calculate_pid() { //Roll calculations pid_error_temp = gyro_roll_input - pid_roll_setpoint; pid_i_mem_roll += pid_i_gain_roll * pid_error_temp; if (pid_i_mem_roll > pid_max_roll)pid_i_mem_roll = pid_max_roll; else if (pid_i_mem_roll < pid_max_roll * -1)pid_i_mem_roll = pid_max_roll * -1; pid_output_roll = pid_p_gain_roll * pid_error_temp + pid_i_mem_roll + pid_d_gain_roll * (pid_error_temp - pid_last_roll_d_error); if (pid_output_roll > pid_max_roll)pid_output_roll = pid_max_roll; else if (pid_output_roll < pid_max_roll * -1)pid_output_roll = pid_max_roll * -1; pid_last_roll_d_error = pid_error_temp; //Pitch calculations pid_error_temp = gyro_pitch_input - pid_pitch_setpoint; pid_i_mem_pitch += pid_i_gain_pitch * pid_error_temp; if (pid_i_mem_pitch > pid_max_pitch)pid_i_mem_pitch = pid_max_pitch; else if (pid_i_mem_pitch < pid_max_pitch * -1)pid_i_mem_pitch = pid_max_pitch * -1; pid_output_pitch = pid_p_gain_pitch * pid_error_temp + pid_i_mem_pitch + pid_d_gain_pitch * (pid_error_temp - pid_last_pitch_d_error); if (pid_output_pitch > pid_max_pitch)pid_output_pitch = pid_max_pitch; else if (pid_output_pitch < pid_max_pitch * -1)pid_output_pitch = pid_max_pitch * -1; pid_last_pitch_d_error = pid_error_temp; //Yaw calculations pid_error_temp = gyro_yaw_input - pid_yaw_setpoint; pid_i_mem_yaw += pid_i_gain_yaw * pid_error_temp; if (pid_i_mem_yaw > pid_max_yaw)pid_i_mem_yaw = pid_max_yaw; else if (pid_i_mem_yaw < pid_max_yaw * -1)pid_i_mem_yaw = pid_max_yaw * -1; pid_output_yaw = pid_p_gain_yaw * pid_error_temp + pid_i_mem_yaw + pid_d_gain_yaw * (pid_error_temp - pid_last_yaw_d_error); if (pid_output_yaw > pid_max_yaw)pid_output_yaw = pid_max_yaw; else if (pid_output_yaw < pid_max_yaw * -1)pid_output_yaw = pid_max_yaw * -1; pid_last_yaw_d_error = pid_error_temp; } //This part converts the actual receiver signals to a standardized 1000 – 1500 – 2000 microsecond value. //The stored data in the EEPROM is used. int convert_receiver_channel(byte function) { byte channel, reverse; //First we declare some local variables int low, center, high, actual; int difference; channel = eeprom_data[function + 23] & 0b00000111; //What channel corresponds with the specific function if (eeprom_data[function + 23] & 0b10000000)reverse = 1; //Reverse channel when most significant bit is set else reverse = 0; //If the most significant is not set there is no reverse actual = receiver_input[channel]; //Read the actual receiver value for the corresponding function low = (eeprom_data[channel * 2 + 15] << 8) | eeprom_data[channel * 2 + 14]; //Store the low value for the specific receiver input channel center = (eeprom_data[channel * 2 - 1] << 8) | eeprom_data[channel * 2 - 2]; //Store the center value for the specific receiver input channel high = (eeprom_data[channel * 2 + 7] << 8) | eeprom_data[channel * 2 + 6]; //Store the high value for the specific receiver input channel if (actual < center) { //The actual receiver value is lower than the center value if (actual < low)actual = low; //Limit the lowest value to the value that was detected during setup difference = ((long)(center - actual) * (long)500) / (center - low); //Calculate and scale the actual value to a 1000 - 2000us value if (reverse == 1)return 1500 + difference; //If the channel is reversed else return 1500 - difference; //If the channel is not reversed } else if (actual > center) { //The actual receiver value is higher than the center value if (actual > high)actual = high; //Limit the lowest value to the value that was detected during setup difference = ((long)(actual - center) * (long)500) / (high - center); //Calculate and scale the actual value to a 1000 - 2000us value if (reverse == 1)return 1500 - difference; //If the channel is reversed else return 1500 + difference; //If the channel is not reversed } else return 1500; } void set_gyro_registers() { //Setup the MPU-6050 if (eeprom_data[31] == 1) { Wire.beginTransmission(gyro_address); //Start communication with the address found during search. Wire.write(0x6B); //We want to write to the PWR_MGMT_1 register (6B hex) Wire.write(0x00); //Set the register bits as 00000000 to activate the gyro Wire.endTransmission(); //End the transmission with the gyro. Wire.beginTransmission(gyro_address); //Start communication with the address found during search. Wire.write(0x1B); //We want to write to the GYRO_CONFIG register (1B hex) Wire.write(0x08); //Set the register bits as 00001000 (500dps full scale) Wire.endTransmission(); //End the transmission with the gyro Wire.beginTransmission(gyro_address); //Start communication with the address found during search. Wire.write(0x1C); //We want to write to the ACCEL_CONFIG register (1A hex) Wire.write(0x10); //Set the register bits as 00010000 (+/- 8g full scale range) Wire.endTransmission(); //End the transmission with the gyro //Let's perform a random register check to see if the values are written correct Wire.beginTransmission(gyro_address); //Start communication with the address found during search Wire.write(0x1B); //Start reading @ register 0x1B Wire.endTransmission(); //End the transmission Wire.requestFrom(gyro_address, 1); //Request 1 bytes from the gyro while (Wire.available() < 1); //Wait until the 6 bytes are received if (Wire.read() != 0x08) { //Check if the value is 0x08 digitalWrite(STATUS_LED , LOW); //Turn on the warning led while (1)delay(10); //Stay in this loop for ever } Wire.beginTransmission(gyro_address); //Start communication with the address found during search Wire.write(0x1A); //We want to write to the CONFIG register (1A hex) Wire.write(0x03); //Set the register bits as 00000011 (Set Digital Low Pass Filter to ~43Hz) Wire.endTransmission(); //End the transmission with the gyro } } void read_gps(void) { while (ss.available() && new_line_found == 0) { //Stay in this loop as long as there is serial information from the GPS available. char read_serial_byte = ss.read(); //Load a new serial byte in the read_serial_byte variable. Serial.print(read_serial_byte); if (read_serial_byte == '$') { //If the new byte equals a $ character. for (message_counter = 0; message_counter <= 99; message_counter ++) { //Clear the old data from the incomming buffer array. incomming_message[message_counter] = '-'; //Write a - at every position. } message_counter = 0; //Reset the message_counter variable because we want to start writing at the begin of the array. } else if (message_counter <= 99)message_counter ++; //If the received byte does not equal a $ character, increase the message_counter variable. incomming_message[message_counter] = read_serial_byte; //Write the new received byte to the new position in the incomming_message array. if (read_serial_byte == '*') new_line_found = 1; //Every NMEA line end with a *. If this character is detected the new_line_found variable is set to 1. } //If the software has detected a new NMEA line it will check if it's a valid line that can be used. if (new_line_found == 1) { //If a new NMEA line is found. new_line_found = 0; digitalWrite(GPS_LED, HIGH); //Reset the new_line_found variable for the next line. if (incomming_message[4] == 'L' && incomming_message[5] == 'L' && incomming_message[7] == ',') { //When there is no GPS fix or latitude/longitude information available. digitalWrite(GPS_LED, LOW); //Change the LED on the STM32 to indicate GPS reception. //Set some variables to 0 if no valid information is found by the GPS module. This is needed for GPS lost when flying. l_lat_gps = 0; l_lon_gps = 0; lat_gps_previous = 0; lon_gps_previous = 0; number_used_sats = 0; } //If the line starts with GA and if there is a GPS fix we can scan the line for the latitude, longitude and number of satellites. if (incomming_message[4] == 'G' && incomming_message[5] == 'A' && (incomming_message[44] == '1' || incomming_message[44] == '2')) { lat_gps_actual = ((int)incomming_message[19] - 48) * (long)10000000; //Filter the minutes for the GGA line multiplied by 10. lat_gps_actual += ((int)incomming_message[20] - 48) * (long)1000000; //Filter the minutes for the GGA line multiplied by 10. lat_gps_actual += ((int)incomming_message[22] - 48) * (long)100000; //Filter the minutes for the GGA line multiplied by 10. lat_gps_actual += ((int)incomming_message[23] - 48) * (long)10000; //Filter the minutes for the GGA line multiplied by 10. lat_gps_actual += ((int)incomming_message[24] - 48) * (long)1000; //Filter the minutes for the GGA line multiplied by 10. lat_gps_actual += ((int)incomming_message[25] - 48) * (long)100; //Filter the minutes for the GGA line multiplied by 10. lat_gps_actual += ((int)incomming_message[26] - 48) * (long)10; //Filter the minutes for the GGA line multiplied by 10. lat_gps_actual /= (long)6; //To convert the minutes to degrees we need to divide the minutes by 6. lat_gps_actual += ((int)incomming_message[17] - 48) * (long)100000000; //Add the degrees multiplied by 10. lat_gps_actual += ((int)incomming_message[18] - 48) * (long)10000000; //Add the degrees multiplied by 10. lat_gps_actual /= 10; //Divide everything by 10. lon_gps_actual = ((int)incomming_message[33] - 48) * (long)10000000; //Filter the minutes for the GGA line multiplied by 10. lon_gps_actual += ((int)incomming_message[34] - 48) * (long)1000000; //Filter the minutes for the GGA line multiplied by 10. lon_gps_actual += ((int)incomming_message[36] - 48) * (long)100000; //Filter the minutes for the GGA line multiplied by 10. lon_gps_actual += ((int)incomming_message[37] - 48) * (long)10000; //Filter the minutes for the GGA line multiplied by 10. lon_gps_actual += ((int)incomming_message[38] - 48) * (long)1000; //Filter the minutes for the GGA line multiplied by 10. lon_gps_actual += ((int)incomming_message[39] - 48) * (long)100; //Filter the minutes for the GGA line multiplied by 10. lon_gps_actual += ((int)incomming_message[40] - 48) * (long)10; //Filter the minutes for the GGA line multiplied by 10. lon_gps_actual /= (long)6; //To convert the minutes to degrees we need to divide the minutes by 6. lon_gps_actual += ((int)incomming_message[30] - 48) * (long)1000000000; //Add the degrees multiplied by 10. lon_gps_actual += ((int)incomming_message[31] - 48) * (long)100000000; //Add the degrees multiplied by 10. lon_gps_actual += ((int)incomming_message[32] - 48) * (long)10000000; //Add the degrees multiplied by 10. lon_gps_actual /= 10; //Divide everything by 10. if (incomming_message[28] == 'N')latitude_north = 1; //When flying north of the equator the latitude_north variable will be set to 1. else latitude_north = 0; //When flying south of the equator the latitude_north variable will be set to 0. if (incomming_message[42] == 'E')longiude_east = 1; //When flying east of the prime meridian the longiude_east variable will be set to 1. else longiude_east = 0; //When flying west of the prime meridian the longiude_east variable will be set to 0. number_used_sats = ((int)incomming_message[46] - 48) * (long)10; //Filter the number of satillites from the GGA line. number_used_sats += (int)incomming_message[47] - 48; //Filter the number of satillites from the GGA line. if (lat_gps_previous == 0 && lon_gps_previous == 0) { //If this is the first time the GPS code is used. lat_gps_previous = lat_gps_actual; //Set the lat_gps_previous variable to the lat_gps_actual variable. lon_gps_previous = lon_gps_actual; //Set the lon_gps_previous variable to the lon_gps_actual variable. } lat_gps_loop_add = (float)(lat_gps_actual - lat_gps_previous) / 10.0; //Divide the difference between the new and previous latitude by ten. lon_gps_loop_add = (float)(lon_gps_actual - lon_gps_previous) / 10.0; //Divide the difference between the new and previous longitude by ten. l_lat_gps = lat_gps_previous; //Set the l_lat_gps variable to the previous latitude value. l_lon_gps = lon_gps_previous; //Set the l_lon_gps variable to the previous longitude value. lat_gps_previous = lat_gps_actual; //Remember the new latitude value in the lat_gps_previous variable for the next loop. lon_gps_previous = lon_gps_actual; //Remember the new longitude value in the lat_gps_previous variable for the next loop. //The GPS is set to a 5Hz refresh rate. Between every 2 GPS measurments, 9 GPS values are simulated. gps_add_counter = 5; //Set the gps_add_counter variable to 5 as a count down loop timer new_gps_data_counter = 9; //Set the new_gps_data_counter to 9. This is the number of simulated values between 2 GPS measurements. lat_gps_add = 0; //Reset the lat_gps_add variable. lon_gps_add = 0; //Reset the lon_gps_add variable. new_gps_data_available = 1; //Set the new_gps_data_available to indicate that there is new data available. } //If the line starts with SA and if there is a GPS fix we can scan the line for the fix type (none, 2D or 3D). if (incomming_message[4] == 'S' && incomming_message[5] == 'A') { fix_type = (int)incomming_message[9] - 48; if (((int)incomming_message[9] - 48) == 3) { digitalWrite(GPS_LED , LOW); Serial.print(""LAT:"");Serial.println(lat_gps_actual); Serial.print(""LONG:"");Serial.println(lon_gps_actual); /*Serial.print(receiver_input[1]); Serial.print(""---""); Serial.print(receiver_input[2]); Serial.print(""---""); Serial.print(receiver_input[3]); Serial.print(""---""); Serial.println(receiver_input[4]);*/ } else if (((int)incomming_message[9] - 48) == 1) { digitalWrite(GPS_LED , HIGH); } } } //After 5 program loops 5 x 4ms = 20ms the gps_add_counter is 0. if (gps_add_counter == 0 && new_gps_data_counter > 0) { //If gps_add_counter is 0 and there are new GPS simulations needed. new_gps_data_available = 1; //Set the new_gps_data_available to indicate that there is new data available. new_gps_data_counter --; //Decrement the new_gps_data_counter so there will only be 9 simulations gps_add_counter = 5; //Set the gps_add_counter variable to 5 as a count down loop timer lat_gps_add += lat_gps_loop_add; //Add the simulated part to a buffer float variable because the l_lat_gps can only hold integers. if (abs(lat_gps_add) >= 1) { //If the absolute value of lat_gps_add is larger then 1. l_lat_gps += (int)lat_gps_add; //Increment the lat_gps_add value with the lat_gps_add value as an integer. So no decimal part. lat_gps_add -= (int)lat_gps_add; //Subtract the lat_gps_add value as an integer so the decimal value remains. } lon_gps_add += lon_gps_loop_add; //Add the simulated part to a buffer float variable because the l_lat_gps can only hold integers. if (abs(lon_gps_add) >= 1) { //If the absolute value of lat_gps_add is larger then 1. l_lon_gps += (int)lon_gps_add; //Increment the lat_gps_add value with the lat_gps_add value as an integer. So no decimal part. lon_gps_add -= (int)lon_gps_add; //Subtract the lat_gps_add value as an integer so the decimal value remains. } } if (new_gps_data_available) { //If there is a new set of GPS data available. digitalWrite(GPS_LED, HIGH); if (number_used_sats < 8)digitalWrite(GPS_LED, LOW); //Change the LED on the STM32 to indicate GPS reception. else digitalWrite(GPS_LED, LOW); //Turn the LED on the STM solid on (LED function is inverted). Check the STM32 schematic. // gps_watchdog_timer = millis(); //Reset the GPS watch dog tmer. new_gps_data_available = 0; //Reset the new_gps_data_available variable. if (flight_mode == 1 && waypoint_set == 0) { //If the flight mode is 3 (GPS hold) and no waypoints are set. waypoint_set = 1; //Indicate that the waypoints are set. l_lat_waypoint = l_lat_gps; //Remember the current latitude as GPS hold waypoint. l_lon_waypoint = l_lon_gps; //Remember the current longitude as GPS hold waypoint. } if (flight_mode == 1 && waypoint_set == 1) { //If the GPS hold mode and the waypoints are stored. gps_lon_error = l_lon_waypoint - l_lon_gps; //Calculate the latitude error between waypoint and actual position. gps_lat_error = l_lat_gps - l_lat_waypoint; //Calculate the longitude error between waypoint and actual position. gps_lat_total_avarage -= gps_lat_rotating_mem[ gps_rotating_mem_location]; //Subtract the current memory position to make room for the new value. gps_lat_rotating_mem[ gps_rotating_mem_location] = gps_lat_error - gps_lat_error_previous; //Calculate the new change between the actual pressure and the previous measurement. gps_lat_total_avarage += gps_lat_rotating_mem[ gps_rotating_mem_location]; //Add the new value to the long term avarage value. gps_lon_total_avarage -= gps_lon_rotating_mem[ gps_rotating_mem_location]; //Subtract the current memory position to make room for the new value. gps_lon_rotating_mem[ gps_rotating_mem_location] = gps_lon_error - gps_lon_error_previous; //Calculate the new change between the actual pressure and the previous measurement. gps_lon_total_avarage += gps_lon_rotating_mem[ gps_rotating_mem_location]; //Add the new value to the long term avarage value. gps_rotating_mem_location++; //Increase the rotating memory location. if ( gps_rotating_mem_location == 35) gps_rotating_mem_location = 0; //Start at 0 when the memory location 35 is reached. gps_lat_error_previous = gps_lat_error; //Remember the error for the next loop. gps_lon_error_previous = gps_lon_error; //Remember the error for the next loop. //Calculate the GPS pitch and roll correction as if the nose of the multicopter is facing north. //The Proportional part = (float)gps_lat_error * gps_p_gain. //The Derivative part = (float)gps_lat_total_avarage * gps_d_gain. gps_pitch_adjust_north = (float)gps_lat_error * gps_p_gain + (float)gps_lat_total_avarage * gps_d_gain; gps_roll_adjust_north = (float)gps_lon_error * gps_p_gain + (float)gps_lon_total_avarage * gps_d_gain; if (!latitude_north)gps_pitch_adjust_north *= -1; //Invert the pitch adjustmet because the quadcopter is flying south of the equator. if (!longiude_east)gps_roll_adjust_north *= -1; //Invert the roll adjustmet because the quadcopter is flying west of the prime meridian. //Because the correction is calculated as if the nose was facing north, we need to convert it for the current heading. gps_roll_adjust = ((float)gps_roll_adjust_north * cos(angle_yaw * 0.017453)) + ((float)gps_pitch_adjust_north * cos((angle_yaw - 90) * 0.017453)); gps_pitch_adjust = ((float)gps_pitch_adjust_north * cos(angle_yaw * 0.017453)) + ((float)gps_roll_adjust_north * cos((angle_yaw + 90) * 0.017453)); //Limit the maximum correction to 300. This way we still have full controll with the pitch and roll stick on the transmitter. if (gps_roll_adjust > 300) gps_roll_adjust = 300; if (gps_roll_adjust < -300) gps_roll_adjust = -300; if (gps_pitch_adjust > 300) gps_pitch_adjust = 300; if (gps_pitch_adjust < -300) gps_pitch_adjust = -300; } } /* if (gps_watchdog_timer + 1000 < millis()) { //If the watchdog timer is exceeded the GPS signal is missing. if (flight_mode >= 3 && start > 0) { //If flight mode is set to 3 (GPS hold). flight_mode = 2; //Set the flight mode to 2. error = 4; //Output an error. } } */ if (flight_mode == 0 && waypoint_set > 0) { //If the GPS hold mode is disabled and the waypoints are set. gps_roll_adjust = 0; //Reset the gps_roll_adjust variable to disable the correction. gps_pitch_adjust = 0; //Reset the gps_pitch_adjust variable to disable the correction. if (waypoint_set == 1) { //If the waypoints are stored gps_rotating_mem_location = 0; //Set the gps_rotating_mem_location to zero so we can empty the waypoint_set = 2; //Set the waypoint_set variable to 2 as an indication that the buffer is not cleared. } gps_lon_rotating_mem[ gps_rotating_mem_location] = 0; //Reset the current gps_lon_rotating_mem location. gps_lat_rotating_mem[ gps_rotating_mem_location] = 0; //Reset the current gps_lon_rotating_mem location. gps_rotating_mem_location++; //Increment the gps_rotating_mem_location variable for the next loop. if (gps_rotating_mem_location == 36) { //If the gps_rotating_mem_location equals 36, all the buffer locations are cleared. waypoint_set = 0; //Reset the waypoint_set variable to 0. //Reset the variables that are used for the D-controller. gps_lat_error_previous = 0; gps_lon_error_previous = 0; gps_lat_total_avarage = 0; gps_lon_total_avarage = 0; gps_rotating_mem_location = 0; } } } ",16195,True,2787.604235551723,median "/** * VERSION: 1.66 * DATE: 2011-01-25 * AS3 (AS2 version is also available) * UPDATES AND DOCS AT: http://www.greensock.com/timelinemax/ **/ package com.greensock { import com.greensock.core.*; import com.greensock.events.TweenEvent; import flash.events.*; /** * TimelineMax extends TimelineLite, offering exactly the same functionality plus useful * (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, * currentLabel, addCallback(), removeCallback(), tweenTo(), tweenFromTo(), getLabelAfter(), getLabelBefore(), * and getActive() (and probably more in the future). It is the ultimate sequencing tool. * Think of a TimelineMax instance like a virtual MovieClip timeline or a container where * you place tweens (or other timelines) over the course of time. You can: * *
    *
  • build sequences easily by adding tweens with the append(), prepend(), insert(), appendMultiple(), * prependMultiple(), and insertMultiple() methods. Tweens can overlap as much as you want and you have * complete control over where they get placed on the timeline.
  • * *
  • add labels, play(), stop(), gotoAndPlay(), gotoAndStop(), restart(), tweenTo() and even reverse()!
  • * *
  • nest timelines within timelines as deeply as you want.
  • * *
  • set the progress of the timeline using its currentProgress property. For example, to skip to * the halfway point, set myTimeline.currentProgress = 0.5.
  • * *
  • tween the currentTime, totalTime, currentProgress, or totalProgress * property to fastforward/rewind the timeline. You could * even attach a slider to one of these properties to give the user the ability to drag * forwards/backwards through the whole timeline.
  • * *
  • add onStart, onUpdate, onComplete, onReverseComplete, and/or onRepeat callbacks using the * constructor's vars object.
  • * *
  • speed up or slow down the entire timeline with its timeScale property. You can even tween * this property to gradually speed up or slow down the timeline.
  • * *
  • use the insertMultiple(), appendMultiple(), or prependMultiple() methods to create * complex sequences including various alignment modes and staggering capabilities. * Works great in conjunction with TweenMax.allTo() too.
  • * *
  • base the timing on frames instead of seconds if you prefer. Please note, however, that * the timeline's timing mode dictates its childrens' timing mode as well.
  • * *
  • kill the tweens of a particular object inside the timeline with killTweensOf() or get the tweens of an object * with getTweensOf() or get all the tweens/timelines in the timeline with getChildren()
  • * *
  • set the timeline to repeat any number of times or indefinitely. You can even set a delay * between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse * every other cycle.
  • * *
  • listen for START, UPDATE, REPEAT, REVERSE_COMPLETE, and COMPLETE events.
  • * *
  • get the active tweens in the timeline with getActive().
  • * *
  • add callbacks (function calls) anywhere in the timeline that call a function of your choosing when * the ""virtual playhead"" passes a particular spot.
  • * *
  • Get the currentLabel or find labels at various positions in the timeline * using getLabelAfter() and getLabelBefore()
  • *
* * EXAMPLE:

* * import com.greensock.~~;

* * //create the timeline and add an onComplete call to myFunction when the timeline completes
* var myTimeline:TimelineMax = new TimelineMax({onComplete:myFunction});

* * //add a tween
* myTimeline.append(new TweenLite(mc, 1, {x:200, y:100}));

* * //add another tween at the end of the timeline (makes sequencing easy)
* myTimeline.append(new TweenLite(mc, 0.5, {alpha:0}));

* * //repeat the entire timeline twice
* myTimeline.repeat = 2;

* * //delay the repeat by 0.5 seconds each time.
* myTimeline.repeatDelay = 0.5;

* * //pause the timeline (stop() works too)
* myTimeline.pause();

* * //reverse it anytime...
* myTimeline.reverse();

* * //Add a ""spin"" label 3-seconds into the timeline.
* myTimeline.addLabel(""spin"", 3);

* * //insert a rotation tween at the ""spin"" label (you could also define the insert point as the time instead of a label)
* myTimeline.insert(new TweenLite(mc, 2, {rotation:""360""}), ""spin"");

* * //go to the ""spin"" label and play the timeline from there...
* myTimeline.gotoAndPlay(""spin"");

* * //call myCallbackwhen the ""virtual playhead"" travels past the 1.5-second point. * myTimeline.addCallback(myCallback, 1.5); * * //add a tween to the beginning of the timeline, pushing all the other existing tweens back in time
* myTimeline.prepend(new TweenMax(mc, 1, {tint:0xFF0000}));

* * //nest another TimelineMax inside your timeline...
* var nestedTimeline:TimelineMax = new TimelineMax();
* nestedTimeline.append(new TweenLite(mc2, 1, {x:200}));
* myTimeline.append(nestedTimeline);

* * * insertMultiple() and appendMultiple() provide some very powerful sequencing tools as well, * allowing you to add an Array of tweens/timelines and optionally align them with SEQUENCE or START * modes, and even stagger them if you want. For example, to insert 3 tweens into the timeline, aligning their start times but * staggering them by 0.2 seconds,

* * myTimeline.insertMultiple([new TweenLite(mc, 1, {y:""100""}), * new TweenLite(mc2, 1, {x:120}), * new TweenLite(mc3, 1, {alpha:0.5})], * 0, * TweenAlign.START, * 0.2);

* * You can use the constructor's vars object to do all the setup too, like:

* * var myTimeline:TimelineMax = new TimelineMax({tweens:[new TweenLite(mc1, 1, {y:""100""}), TweenMax.to(mc2, 1, {tint:0xFF0000})], align:TweenAlign.SEQUENCE, onComplete:myFunction, repeat:2, repeatDelay:1});

* * If that confuses you, don't worry. Just use the append(), insert(), and prepend() methods to build your * sequence. But power users will likely appreciate the quick, compact way they can set up sequences now.

* * * NOTES: *
    *
  • TimelineMax automatically inits the OverwriteManager class to prevent unexpected overwriting behavior in sequences. * The default mode is AUTO, but you can set it to whatever you want with OverwriteManager.init() * (see http://www.greensock.com/overwritemanager/)
  • *
  • TimelineMax adds about 4.9k to your SWF (not including OverwriteManager).
  • *
* * Copyright 2011, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com **/ public class TimelineMax extends TimelineLite implements IEventDispatcher { /** @private **/ public static const version:Number = 1.66; /** @private **/ protected var _repeat:int; /** @private **/ protected var _repeatDelay:Number; /** @private **/ protected var _cyclesComplete:int; /** @private **/ protected var _dispatcher:EventDispatcher; /** @private **/ protected var _hasUpdateListener:Boolean; /** * Works in conjunction with the repeat property, determining the behavior of each cycle; when yoyo is true, * the timeline will go back and forth, appearing to reverse every other cycle (this has no affect on the reversed property though). * So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. * But if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. **/ public var yoyo:Boolean; /** * Constructor.

* * SPECIAL PROPERTIES
* The following special properties may be passed in via the constructor's vars parameter, like * new TimelineMax({paused:true, onComplete:myFunction, repeat:2, yoyo:true}) * *
    *
  • delay : Number Amount of delay in seconds (or frames for frames-based timelines) before the timeline should begin.
  • * *
  • useFrames : Boolean If useFrames is set to true, the timeline's timing mode will be based on frames. * Otherwise, it will be based on seconds/time. NOTE: a TimelineLite's timing mode is * always determined by its parent timeline.
  • * *
  • paused : Boolean Sets the initial paused state of the timeline (by default, timelines automatically begin playing immediately)
  • * *
  • reversed : Boolean If true, the timeline will be reversed initially. This does NOT force it to the very end and start * playing backwards. It simply affects the orientation of the timeline, so if reversed is set to * true initially, it will appear not to play because it is already at the beginning. To cause it to * play backwards from the end, set reversed to true and then set the currentProgress property to 1 immediately * after creating the timeline.
  • * *
  • tweens : Array To immediately insert several tweens into the timeline, use the tweens special property * to pass in an Array of TweenLite/TweenMax/TimelineLite/TimelineMax instances. You can use this in conjunction * with the align and stagger special properties to set up complex sequences with minimal code. * These values simply get passed to the insertMultiple() method.
  • * *
  • align : String Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately through the constructor. The value simply gets passed to the * insertMultiple() method. The default is TweenAlign.NORMAL. Options are: *
      *
    • TweenAlign.SEQUENCE: aligns the tweens one-after-the-other in a sequence
    • *
    • TweenAlign.START: aligns the start times of all of the tweens (ignores delays)
    • *
    • TweenAlign.NORMAL: aligns the start times of all the tweens (honors delays)
    • *
    The align special property does not force all child tweens/timelines to maintain * relative positioning, so for example, if you use TweenAlign.SEQUENCE and then later change the duration * of one of the nested tweens, it does not force all subsequent timelines to change their position * on the timeline. The align special property only affects the alignment of the tweens that are * initially placed into the timeline through the tweens special property of the vars object.
  • * *
  • stagger : Number Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately. It staggers the tweens by a set amount of time (in seconds) (or * in frames if useFrames is true). For example, if the stagger value is 0.5 and the align * property is set to TweenAlign.START, the second tween will start 0.5 seconds after the first one * starts, then 0.5 seconds later the third one will start, etc. If the align property is * TweenAlign.SEQUENCE, there would be 0.5 seconds added between each tween. This value simply gets * passed to the insertMultiple() method. Default is 0.
  • * *
  • onStart : Function A function that should be called when the timeline begins (the currentProgress won't necessarily * be zero when onStart is called. For example, if the timeline is created and then its currentProgress * property is immediately set to 0.5 or if its currentTime property is set to something other than zero, * onStart will still get fired because it is the first time the timeline is getting rendered.)
  • * *
  • onStartParams : Array An Array of parameters to pass the onStart function.
  • * *
  • onUpdate : Function A function that should be called every time the timeline's time/position is updated * (on every frame while the timeline is active)
  • * *
  • onUpdateParams : Array An Array of parameters to pass the onUpdate function
  • * *
  • onComplete : Function A function that should be called when the timeline has finished
  • * *
  • onCompleteParams : Array An Array of parameters to pass the onComplete function
  • * *
  • onReverseComplete : Function A function that should be called when the timeline has reached its starting point again after having been reversed
  • * *
  • onReverseCompleteParams : Array An Array of parameters to pass the onReverseComplete functions
  • * *
  • onRepeat : Function A function that should be called every time the timeline repeats
  • * *
  • onRepeatParams : Array An Array of parameters to pass the onRepeat function
  • * *
  • autoRemoveChildren : Boolean If autoRemoveChildren is set to true, as soon as child tweens/timelines complete, * they will automatically get killed/removed. This is normally undesireable because * it prevents going backwards in time (like if you want to reverse() or set the * currentProgress value to a lower value, etc.). It can, however, improve speed and memory * management. TweenLite's root timelines use autoRemoveChildren:true.
  • * *
  • repeat : int Number of times that the timeline should repeat. To repeat indefinitely, use -1.
  • * *
  • repeatDelay : Number Amount of time in seconds (or frames for frames-based timelines) between repeats.
  • * *
  • yoyo : Boolean Works in conjunction with the repeat property, determining the behavior of each * cycle. When yoyo is true, the timeline will go back and forth, appearing to reverse * every other cycle (this has no affect on the reversed property though). So if repeat is * 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But * if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
  • * *
  • onStartListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it begins. * This is the same as doing myTimeline.addEventListener(TweenEvent.START, myFunction);
  • * *
  • onUpdateListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent every time it * updates values. This is the same as doing myTimeline.addEventListener(TweenEvent.UPDATE, myFunction);
  • * *
  • onCompleteListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it completes. * This is the same as doing myTimeline.addEventListener(TweenEvent.COMPLETE, myFunction);
  • *
* * @param vars optionally pass in special properties like useFrames, onComplete, onCompleteParams, onUpdate, onUpdateParams, onStart, onStartParams, tweens, align, stagger, delay, autoRemoveChildren, onCompleteListener, onStartListener, onUpdateListener, repeat, repeatDelay, and/or yoyo. */ public function TimelineMax(vars:Object=null) { super(vars); _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; _cyclesComplete = 0; this.yoyo = Boolean(this.vars.yoyo == true); this.cacheIsDirty = true; if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } } /** * If you want a function to be called at a particular time or label, use addCallback. When you add * a callback, it is technically considered a zero-duration tween, so if you getChildren() there will be * a tween returned for each callback. You can discern a callback from other tweens by the fact that * their target is a function and the duration is zero. * * @param function the function to be called * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label at which the callback should be inserted. For example, myTimeline.addCallback(myFunction, 3) would call myFunction() 3-seconds into the timeline, and myTimeline.addCallback(myFunction, ""myLabel"") would call it at the ""myLabel"" label. * @param params an Array of parameters to pass the callback * @return TweenLite instance */ public function addCallback(callback:Function, timeOrLabel:*, params:Array=null):TweenLite { var cb:TweenLite = new TweenLite(callback, 0, {onComplete:callback, onCompleteParams:params, overwrite:0, immediateRender:false}); insert(cb, timeOrLabel); return cb; } /** * Removes a callback from a particular time or label. If timeOrLabel is null, all callbacks of that * particular function are removed from the timeline. * * @param function callback function to be removed * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label from which the callback should be removed. For example, myTimeline.removeCallback(myFunction, 3) would remove the callback from 3-seconds into the timeline, and myTimeline.removeCallback(myFunction, ""myLabel"") would remove it from the ""myLabel"" label, and myTimeline.removeCallback(myFunction, null) would remove ALL callbacks of that function regardless of where they are on the timeline. * @return true if any callbacks were successfully found and removed. false otherwise. */ public function removeCallback(callback:Function, timeOrLabel:*=null):Boolean { if (timeOrLabel == null) { return killTweensOf(callback, false); } else { if (typeof(timeOrLabel) == ""string"") { if (!(timeOrLabel in _labels)) { return false; } timeOrLabel = _labels[timeOrLabel]; } var a:Array = getTweensOf(callback, false), success:Boolean; var i:int = a.length; while (--i > -1) { if (a[i].cachedStartTime == timeOrLabel) { remove(a[i] as TweenCore); success = true; } } return success; } } /** * Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops. For * example, to make the TimelineMax play to the ""myLabel2"" label, simply do:

* * myTimeline.tweenTo(""myLabel2"");

* * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween to the 5-second point on the * timeline and then call a function named myFunction and pass in a parameter that's references this * TimelineMax and use a Strong.easeOut ease, you'd do:

* * myTimeline.tweenTo(5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

* * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method.

* * If you plan to sequence multiple playhead tweens one-after-the-other, it is typically better to use * tweenFromTo() so that you can define the starting point and ending point, allowing the * duration to be accurately determined immediately. * * @see #tweenFromTo() * @param timeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(5) would play from wherever the timeline is currently to the 5-second point whereas myTimeline.tweenTo(""myLabel"") would play to wherever ""myLabel"" is on the timeline. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenTo() sets it internally) * @return TweenLite instance that handles tweening the timeline to the desired time/label. */ public function tweenTo(timeOrLabel:*, vars:Object=null):TweenLite { var varsCopy:Object = {ease:easeNone, overwrite:2, useFrames:this.useFrames, immediateRender:false}; for (var p:String in vars) { varsCopy[p] = vars[p]; } varsCopy.onInit = onInitTweenTo; varsCopy.onInitParams = [null, this, NaN]; varsCopy.currentTime = parseTimeOrLabel(timeOrLabel); var tl:TweenLite = new TweenLite(this, (Math.abs(Number(varsCopy.currentTime) - this.cachedTime) / this.cachedTimeScale) || 0.001, varsCopy); tl.vars.onInitParams[0] = tl; return tl; } /** * Creates a linear tween that essentially scrubs the playhead from a particular time or label to another * time or label and then stops. If you plan to sequence multiple playhead tweens one-after-the-other, * tweenFromTo() is better to use than tweenTo() because it allows the duration * to be determined immediately, ensuring that subsequent tweens that are appended to a sequence are * positioned appropriately. For example, to make the TimelineMax play from the label ""myLabel1"" to the ""myLabel2"" * label, and then from ""myLabel2"" back to the beginning (a time of 0), simply do:

* * var playheadTweens:TimelineMax = new TimelineMax();
* playheadTweens.append( myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") );
* playheadTweens.append( myTimeline.tweenFromTo(""myLabel2"", 0);

* * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween from the start (0) to the * 5-second point on the timeline and then call a function named myFunction and pass in a parameter * that's references this TimelineMax and use a Strong.easeOut ease, you'd do:

* * myTimeline.tweenFromTo(0, 5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

* * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenFromTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenFromTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method. * * @see #tweenTo() * @param fromTimeOrLabel The beginning time in seconds (or frame if the timeline is frames-based) or label from which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param toTimeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenFromTo() sets it internally) * @return TweenLite instance that handles tweening the timeline between the desired times/labels. */ public function tweenFromTo(fromTimeOrLabel:*, toTimeOrLabel:*, vars:Object=null):TweenLite { var tl:TweenLite = tweenTo(toTimeOrLabel, vars); tl.vars.onInitParams[2] = parseTimeOrLabel(fromTimeOrLabel); tl.duration = Math.abs(Number(tl.vars.currentTime) - tl.vars.onInitParams[2]) / this.cachedTimeScale; return tl; } /** @private **/ private static function onInitTweenTo(tween:TweenLite, timeline:TimelineMax, fromTime:Number):void { timeline.paused = true; if (!isNaN(fromTime)) { timeline.currentTime = fromTime; } if (tween.vars.currentTime != timeline.currentTime) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. tween.duration = Math.abs(Number(tween.vars.currentTime) - timeline.currentTime) / timeline.cachedTimeScale; } } /** @private **/ private static function easeNone(t:Number, b:Number, c:Number, d:Number):Number { return t / d; } /** @private **/ override public function renderTime(time:Number, suppressEvents:Boolean=false, force:Boolean=false):void { if (this.gc) { this.setEnabled(true, false); } else if (!this.active && !this.cachedPaused) { this.active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. } var totalDur:Number = (this.cacheIsDirty) ? this.totalDuration : this.cachedTotalDuration, prevTime:Number = this.cachedTime, prevTotalTime:Number = this.cachedTotalTime, prevStart:Number = this.cachedStartTime, prevTimeScale:Number = this.cachedTimeScale, tween:TweenCore, isComplete:Boolean, rendered:Boolean, repeated:Boolean, next:TweenCore, dur:Number, prevPaused:Boolean = this.cachedPaused; if (time >= totalDur) { if (_rawPrevTime <= totalDur && _rawPrevTime != time) { this.cachedTotalTime = totalDur; if (!this.cachedReversed && this.yoyo && _repeat % 2 != 0) { this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); } else { this.cachedTime = this.cachedDuration; forceChildrenToEnd(this.cachedDuration, suppressEvents); } isComplete = !this.hasPausedChild(); rendered = true; if (this.cachedDuration == 0 && isComplete && (time == 0 || _rawPrevTime < 0)) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; } } } else if (time <= 0) { if (time < 0) { this.active = false; if (this.cachedDuration == 0 && _rawPrevTime >= 0) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; isComplete = true; } } else if (time == 0 && !this.initted) { force = true; } if (_rawPrevTime >= 0 && _rawPrevTime != time) { this.cachedTotalTime = 0; this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); rendered = true; if (this.cachedReversed) { isComplete = true; } } } else { this.cachedTotalTime = this.cachedTime = time; } _rawPrevTime = time; if (_repeat != 0) { var cycleDuration:Number = this.cachedDuration + _repeatDelay; var prevCycles:int = _cyclesComplete; _cyclesComplete = (this.cachedTotalTime / cycleDuration) >> 0; //rounds result, like int() if (_cyclesComplete == this.cachedTotalTime / cycleDuration) { _cyclesComplete--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } if (prevCycles != _cyclesComplete) { repeated = true; } if (isComplete) { if (this.yoyo && _repeat % 2) { this.cachedTime = 0; } } else if (time > 0) { this.cachedTime = ((this.cachedTotalTime / cycleDuration) - _cyclesComplete) * cycleDuration; //originally this.cachedTotalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!) if (this.yoyo && _cyclesComplete % 2) { this.cachedTime = this.cachedDuration - this.cachedTime; } else if (this.cachedTime >= this.cachedDuration) { this.cachedTime = this.cachedDuration; } if (this.cachedTime < 0) { this.cachedTime = 0; } } else { _cyclesComplete = 0; } if (repeated && !isComplete && (this.cachedTime != prevTime || force)) { /* make sure children at the end/beginning of the timeline are rendered properly. If, for example, a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So we need to push the timeline to the end (and/or beginning depending on its yoyo value). */ var forward:Boolean = Boolean(!this.yoyo || (_cyclesComplete % 2 == 0)); var prevForward:Boolean = Boolean(!this.yoyo || (prevCycles % 2 == 0)); var wrap:Boolean = Boolean(forward == prevForward); if (prevCycles > _cyclesComplete) { prevForward = !prevForward; } if (prevForward) { prevTime = forceChildrenToEnd(this.cachedDuration, suppressEvents); if (wrap) { prevTime = forceChildrenToBeginning(0, true); } } else { prevTime = forceChildrenToBeginning(0, suppressEvents); if (wrap) { prevTime = forceChildrenToEnd(this.cachedDuration, true); } } rendered = false; } } if (this.cachedTotalTime == prevTotalTime && !force) { return; } else if (!this.initted) { this.initted = true; } if (prevTotalTime == 0 && this.cachedTotalTime != 0 && !suppressEvents) { if (this.vars.onStart) { this.vars.onStart.apply(null, this.vars.onStartParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START)); } } if (rendered) { //already rendered, so ignore } else if (this.cachedTime - prevTime > 0) { tween = _firstChild; while (tween) { next = tween.nextNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= this.cachedTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } else { tween = _lastChild; while (tween) { next = tween.prevNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= prevTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } if (_hasUpdate && !suppressEvents) { this.vars.onUpdate.apply(null, this.vars.onUpdateParams); } if (_hasUpdateListener && !suppressEvents) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE)); } if (repeated && !suppressEvents) { if (this.vars.onRepeat) { this.vars.onRepeat.apply(null, this.vars.onRepeatParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REPEAT)); } } if (isComplete && (prevStart == this.cachedStartTime || prevTimeScale != this.cachedTimeScale) && (totalDur >= this.totalDuration || this.cachedTime == 0)) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline) or if it added more tweens to the timeline, we shouldn't run complete() because it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would have called complete() if it was necessary at the new time. The only exception is the timeScale property. complete(true, suppressEvents); } } /** * Forces the timeline to completion. * * @param skipRender to skip rendering the final state of the timeline, set skipRender to true. * @param suppressEvents If true, no events or callbacks will be triggered for this render (like onComplete, onUpdate, onReverseComplete, etc.) */ override public function complete(skipRender:Boolean=false, suppressEvents:Boolean=false):void { super.complete(skipRender, suppressEvents); if (_dispatcher && !suppressEvents) { if (this.cachedReversed && this.cachedTotalTime == 0 && this.cachedDuration != 0) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REVERSE_COMPLETE)); } else { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE)); } } } /** * Returns the tweens/timelines that are currently active in the timeline. * * @param nested determines whether or not tweens and/or timelines that are inside nested timelines should be returned. If you only want the ""top level"" tweens/timelines, set this to false. * @param tweens determines whether or not tweens (TweenLite and TweenMax instances) should be included in the results * @param timelines determines whether or not timelines (TimelineLite and TimelineMax instances) should be included in the results * @return an Array of active tweens/timelines */ public function getActive(nested:Boolean=true, tweens:Boolean=true, timelines:Boolean=false):Array { var a:Array = [], all:Array = getChildren(nested, tweens, timelines), i:int; var l:int = all.length; var cnt:int = 0; for (i = 0; i < l; i += 1) { if (TweenCore(all[i]).active) { a[cnt++] = all[i]; } } return a; } /** @inheritDoc **/ override public function invalidate():void { _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; this.yoyo = Boolean(this.vars.yoyo == true); if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } setDirtyCache(true); super.invalidate(); } /** * Returns the next label (if any) that occurs AFTER the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time after which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is after the time passed to getLabelAfter() */ public function getLabelAfter(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var l:int = labels.length; for (var i:int = 0; i < l; i += 1) { if (labels[i].time > time) { return labels[i].name; } } return null; } /** * Returns the previous label (if any) that occurs BEFORE the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time before which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is before the time passed to getLabelBefore() */ public function getLabelBefore(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var i:int = labels.length; while (--i > -1) { if (labels[i].time < time) { return labels[i].name; } } return null; } /** @private Returns an Array of label objects, each with a ""time"" and ""name"" property, in the order that they occur in the timeline. **/ protected function getLabelsArray():Array { var a:Array = []; for (var p:String in _labels) { a[a.length] = {time:_labels[p], name:p}; } a.sortOn(""time"", Array.NUMERIC); return a; } //---- EVENT DISPATCHING ---------------------------------------------------------------------------------------------------------- /** @private **/ protected function initDispatcher():void { if (_dispatcher == null) { _dispatcher = new EventDispatcher(this); } if (this.vars.onStartListener is Function) { _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true); } if (this.vars.onUpdateListener is Function) { _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true); _hasUpdateListener = true; } if (this.vars.onCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true); } if (this.vars.onRepeatListener is Function) { _dispatcher.addEventListener(TweenEvent.REPEAT, this.vars.onRepeatListener, false, 0, true); } if (this.vars.onReverseCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.REVERSE_COMPLETE, this.vars.onReverseCompleteListener, false, 0, true); } } /** @private **/ public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { if (_dispatcher == null) { initDispatcher(); } if (type == TweenEvent.UPDATE) { _hasUpdateListener = true; } _dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** @private **/ public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { if (_dispatcher != null) { _dispatcher.removeEventListener(type, listener, useCapture); } } /** @private **/ public function hasEventListener(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.hasEventListener(type); } /** @private **/ public function willTrigger(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.willTrigger(type); } /** @private **/ public function dispatchEvent(e:Event):Boolean { return (_dispatcher == null) ? false : _dispatcher.dispatchEvent(e); } //---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- /** * Value between 0 and 1 indicating the overall progress of the timeline according to its totalDuration * where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished. currentProgress, * by contrast, describes the progress according to the timeline's duration which does not * include repeats and repeatDelays. For example, if a TimelineMax instance is set * to repeat once, at the end of the first cycle totalProgress would only be 0.5 * whereas currentProgress would be 1. If you tracked both properties over the course of the * tween, you'd see currentProgress go from 0 to 1 twice (once for each cycle) in the same * time it takes the totalProgress property to go from 0 to 1 once. **/ public function get totalProgress():Number { return this.cachedTotalTime / this.totalDuration; } public function set totalProgress(n:Number):void { setTotalTime(this.totalDuration * n, false); } /** * Duration of the timeline in seconds (or frames for frames-based timelines) including any repeats * or repeatDelays. ""duration"", by contrast, does NOT include repeats and repeatDelays. **/ override public function get totalDuration():Number { if (this.cacheIsDirty) { var temp:Number = super.totalDuration; //just forces refresh //Instead of Infinity, we use 999999999999 so that we can accommodate reverses. this.cachedTotalDuration = (_repeat == -1) ? 999999999999 : this.cachedDuration * (_repeat + 1) + (_repeatDelay * _repeat); } return this.cachedTotalDuration; } /** @private **/ override public function set currentTime(n:Number):void { if (_cyclesComplete == 0) { setTotalTime(n, false); } else if (this.yoyo && (_cyclesComplete % 2 == 1)) { setTotalTime((this.duration - n) + (_cyclesComplete * (this.cachedDuration + _repeatDelay)), false); } else { setTotalTime(n + (_cyclesComplete * (this.duration + _repeatDelay)), false); } } /** Number of times that the timeline should repeat; -1 repeats indefinitely. **/ public function get repeat():int { return _repeat; } public function set repeat(n:int):void { _repeat = n; setDirtyCache(true); } /** Amount of time in seconds (or frames for frames-based timelines) between repeats **/ public function get repeatDelay():Number { return _repeatDelay; } public function set repeatDelay(n:Number):void { _repeatDelay = n; setDirtyCache(true); } /** The closest label that is at or before the current time. **/ public function get currentLabel():String { return getLabelBefore(this.cachedTime + 0.00000001); } } }",12173,False,2070.2575315988097,median "// AS1 Selection Gallery /** * Gallery consisting of a set of images that can be selected with * mouse gestures into groups capable of being cycled or viewed individually. * @param target The movie clip in which to create the gallery * @param depth The depth in the target to create the main gallery movie clip * @param sourceUrl The URL of the XML containing the image information for the gallery * @param width The width to draw the gallery * @param height The height to draw the gallery */ function SelectionGallery(target, depth, sourceUrl, width, height){ this.groups = []; // array to contain all the groups currently selected this._listeners = []; // listeners for event broadcasting this.loader = new SGSourceLoader(this); // loader for loading XML this.gallery = this; // gallery reference this.target = target; // reference to target if (width) this.width = width; // width of the gallery interface if (height) this.height = height; // height of the gallery interface SGTweener.broadcaster = this; // assign this as the broadcaster signalling SGTweener events // create movie clip containers this.galleryContainer = target.createEmptyMovieClip(""SelectionGallery"", depth); this.slideContainer = this.galleryContainer.createEmptyMovieClip(""slideContainer"", 0); this.selectionContainer = this.galleryContainer.createEmptyMovieClip(""selectionContainer"", 1); this.controlsContainer = this.galleryContainer.createEmptyMovieClip(""controlsContainer"", 2); this.toolTipContainer = this.galleryContainer.createEmptyMovieClip(""toolTipContainer"", 1000); // create instance for managing user selections this.userSelection = new SGUserSelection(this, this.selectionContainer); // create instance for managing tooltips this.toolTip = new SGToolTip(this, this.toolTipContainer); // initiate UI this.updateUIDimensions(); this.initControls(); this.drawUI(); // event handlers this.onContent = this.contentLoaded; this.onSlideLoaded = this.slideLoaded; this.onSelection = this.slidesSelected; this.galleryContainer.onEnterFrame = SGEventHandler.scope(this.broadcastEnterFrame, this); // load XML if provided if (sourceUrl != null) this.load(sourceUrl); } SelectionGallery.prototype.width = 500; SelectionGallery.prototype.height = 400; SelectionGallery.prototype.padding = 10; SelectionGallery.prototype.faceBorder = 10; SelectionGallery.prototype.hudHeight = 30; SelectionGallery.prototype.slideMargin = 10; SelectionGallery.prototype.slidePadding = 20; SelectionGallery.prototype.selectionColor = 0xFF9700; SelectionGallery.prototype.faceColor = 0x000000; SelectionGallery.prototype.itemBackgroundColor = 0xB4AF91; SelectionGallery.prototype.backgroundColor = 0x263D48; SelectionGallery.prototype.textColor = 0xFFFFFF; SelectionGallery.prototype.openImages = true; SelectionGallery.prototype.currGroup = null; SelectionGallery.prototype.multiSelection = false; SelectionGallery.prototype.loadCount = 0; SelectionGallery.prototype.toString = function(){ return ""[object SelectionGallery]""; } /** * Broadcasts the onEnterFrame event every frame, primarily for tweener */ SelectionGallery.prototype.broadcastEnterFrame = function(){ this.broadcastMessage(""onEnterFrame""); } /** * Adds a listener to the selection gallery */ SelectionGallery.prototype.addListener = function(obj){ this._listeners.push(obj); } /** * Removes a listener to the selection gallery */ SelectionGallery.prototype.removeListener = function(obj){ var i = this._listeners.length; while (i--){ if (this._listeners[i] == obj){ this._listeners.splice(i, 1); break; } } } /** * Broadcasts an event to all listeners of the selection gallery */ SelectionGallery.prototype.broadcastMessage = function(msg){ var lists = this._listeners.slice(); var n = lists.length; var i; for (i=0; i= 0) ? this.groups[underIndex] : null; this.updateInfo(); } /** * Opens the next active selection for the gallery. This can be either a single slide * or a group if a group has recently been dropped */ SelectionGallery.prototype.openSelection = function(){ if (this.currGroup.slides.length == 1){ if (this.openImages){ getURL(this.currGroup.slides[0].image.url, ""_blank""); } return; } var slides = (this.currGroup.sets.length) ? this.currGroup.sets[0] : [this.currGroup.slides[0]]; this.addNewGroup(slides); this.generateSets(); this.draw(true); } /** * Drops the current group if allowed to be dropped */ SelectionGallery.prototype.closeSelection = function(){ if (this.groups.length < 2) return; this.dropGroup(); this.generateSets(); this.draw(true); } /** * Loads an XML file referencing images into the selection gallery */ SelectionGallery.prototype.load = function(url){ this.loader.load(url); this.setInfo(""Loading Gallery...""); } /** * Clears the gallery of all previously loaded images if they exist */ SelectionGallery.prototype.clearGallery = function(){ var slides = this.groups[0].slides; var i = slides.length; while(i--){ slides[i].remove(); } this.groups = []; this.currGroup = null; this.underGroup = null; this.loadCount = 0; this.draw(true); } /** * Indicates that the XML content has been loaded */ SelectionGallery.prototype.contentLoaded = function(source){ this.clearGallery(); this.currGroup = new SGImageGroup(this, 0); this.groups.push(this.currGroup); var images = this.loader.images.slice(); var n = images.length; var i; for (i=0; i 1){ if (slides.length == this.currGroup.slides.length){ this.dropGroup(); this.generateSets(); }else if (this.underGroup){ this.currGroup.dropSlides(slides, this.underGroup); this.generateSets(); this.updateInfo(); if (this.currGroup.slides.length == 1){ this.currGroup.slides[0].loadFullImage(); } } } break; } default:{ return; } } this.draw(true); } /** * Calls the next set based on the slides next to * the slides in the current set in the set below */ SelectionGallery.prototype.nextSet = function(){ var group = this.underGroup; if (!group) return; group.sets.push(group.sets.shift()); this.dropGroup(); this.addNewGroup(group.sets[0]); this.draw(true); } /** * Calls the previous set based on the slides next to * the slides in the current set in the set below */ SelectionGallery.prototype.prevSet = function(){ var group = this.underGroup; if (!group) return; group.sets.unshift(group.sets.pop()); this.dropGroup(); this.addNewGroup(group.sets[0]); this.draw(true); } /** * Calculates the sets associated with the current selection * This is used for nextSet and prevSet */ SelectionGallery.prototype.generateSets = function(){ var group = this.underGroup; if (!group) return; var setSlides = this.currGroup.slides.slice(); group.sets = []; group.sets.push(setSlides); var indices = []; var slideHash = new Object(); var i = setSlides.length; while (i--){ slideHash[setSlides[i].index] = i; } var slideIndex; i = group.slides.length; while(i--){ slideIndex = slideHash[group.slides[i].index]; if (slideIndex != undefined){ indices[slideIndex] = i; } } var n = group.slides.length; var currSet; do{ currSet = this.getNewSet(group.slides, indices, slideHash); if (currSet){ group.sets.push(currSet); } }while(currSet); } /** * Called by generateSets for the creation of a new set within the sets determined */ SelectionGallery.prototype.getNewSet = function(slides, indices, slideHash){ var nextSet = []; var nextIndex; var n = indices.length; var i; for (i=0; i= n){ i = 0; } while (i != index){ if (slideHash[slides[i].index] == undefined){ nextIndex = i; break; } i++; if (i >= n){ i = 0; } } return nextIndex; } /** * Changes the scope of a function to another scope using the scope() mathod */ function SGEventHandler(){} SGEventHandler.scope = function(method, scope){ return function(){ method.apply(scope, arguments.concat(this)); } } /** * Loads XML content and creates SGImage instance to represent the information it contains */ function SGSourceLoader(gallery){ this.images = []; this.gallery = gallery; this.imagesXml = new XML(); this.imagesXml.ignoreWhite = true; this.imagesXml.onLoad = SGEventHandler.scope(this.contentLoad, this); } /** * Loads an xml file */ SGSourceLoader.prototype.load = function(url){ this.imagesXml.load(url); } /** * Indicates when the XML has loaded */ SGSourceLoader.prototype.contentLoad = function(success){ this.images = []; if (success){ var atts; var imageNodes = this.imagesXml.firstChild.childNodes; var n = imageNodes.length; var i; for (i=0; i rows) ? 1/cols : 1/rows; var sWidth = scaleFactor*(this.gallery.availWidth + this.gallery.slideMargin); var sHeight = scaleFactor*(this.gallery.availHeight + this.gallery.slideMargin); var scale = (cols > rows) ? 100*(this.gallery.availWidth - (cols - 1)*this.gallery.slideMargin)/(cols*this.gallery.availWidth) : 100*(this.gallery.availHeight - (rows - 1)*this.gallery.slideMargin)/(rows*this.gallery.availHeight); var slide; var lastRow = rows - 1; var colCount; var colOffset; var rowOffset; var i = rows*cols; var currCol; var currRow = rows; while (currRow--){ colCount = (currRow == lastRow) ? (count - cols*lastRow) : cols; colOffset = this.gallery.centerX - sWidth*(colCount-1)/2; rowOffset = this.gallery.centerY + currRow*sHeight - sHeight*(rows-1)/2; currCol = cols; while (currCol--){ i--; slide = this.slides[i]; if (i < count && slide.loaded && slide.group == this){ if (!minor){ slide.draw(); } slide.setTint(isCurrGroup ? null : this.gallery.backgroundColor, fogAmount); slide.setDestination(colOffset + currCol*sWidth, rowOffset, scale); slide.target.swapDepths(slide.tween ? baseDepth + count + i : baseDepth + i); } if (!i) break; } if (!i) break; } } /** * Removes all slides from the group */ SGImageGroup.prototype.clearContent = function(){ var i = this.slides.length; while(i--){ this.slides[i].remove(); } this.slides = []; } /** * Contains an image as a slide object containing both the thumbnail * and the full size image when only the current slide is being viewed */ function SGImageSlide(gallery, target, index, image){ this.gallery = gallery; this.target = target; this.index = index; this.image = image; this.thumbnailContainer = this.target.createEmptyMovieClip(""thumbnailContainer"", 0); this.thumbnail = this.thumbnailContainer.createEmptyMovieClip(""thumbnail"", 0); this.fullImageContainer = this.target.createEmptyMovieClip(""fullImageContainer"", 1); this.preloader = this.target.createEmptyMovieClip(""preloader"", 2); this.clearFullImage(); this.target._x = this.gallery.centerX; this.target._y = this.gallery.centerY; this.target._xscale = 50; this.target._yscale = this.target._xscale; this.target.useHandCursor = false; this.target.trackAsMenu = true; this.target.onPress = SGEventHandler.scope(this.slideContact, this); this.target.onDragOver = SGEventHandler.scope(this.slideContact, this); this.target.onRollOver = SGEventHandler.scope(this.showToolTip, this); this.target.onRollOut = SGEventHandler.scope(this.gallery.toolTip.hide, this.gallery.toolTip); this.thumbnail.loadMovie(this.image.thumbnailUrl); this.thumbnailContainer.onEnterFrame = SGEventHandler.scope(this.thumbnailTestLoad, this); } SGImageSlide.prototype.loaded = false; SGImageSlide.prototype.border = 3; SGImageSlide.prototype.group = null; SGImageSlide.prototype.tween = null; SGImageSlide.prototype.destination = null; SGImageSlide.prototype.destinationSteps = 6; SGImageSlide.prototype.index = -1; SGImageSlide.prototype.toString = function(){ return ""[object SGImageSlide (""+this.index+"")]""; } /** * Draws the slide fading its color based on its group location */ SGImageSlide.prototype.draw = function(){ var w = this.gallery.availWidth; var h = this.gallery.availHeight; var w2 = w/2; var h2 = h/2; var b = this.gallery.slidePadding; this.target.clear(); var hilite = SGGraphics.addColor(this.gallery.itemBackgroundColor, 0xFFFFFF, .75); var lolite = SGGraphics.addColor(this.gallery.itemBackgroundColor, 0x000000, .75); SGGraphics.simpleLinearGradient(this.target, -h2, h, hilite, lolite); this.drawSlideShape(w2, h2, b); this.target.endFill(); hilite = SGGraphics.addColor(this.gallery.itemBackgroundColor, 0xFFFFFF, .20); lolite = SGGraphics.addColor(this.gallery.itemBackgroundColor, 0x000000, .20); SGGraphics.simpleLinearGradient(this.target, -h2, h, lolite, hilite); this.drawSlideShape(w2-this.border, h2-this.border, b-this.border/2); this.target.endFill(); this.fitImage(this.thumbnail); this.fitImage(this.fullImage); } /** * Colorizes a slide by a specified amount */ SGImageSlide.prototype.setTint = function(hex, amount){ var col = new Color(this.target); if (hex == undefined){ col.setTransform({ra:100,rb:0,ga:100,gb:0,ba:100,bb:0,aa:100,ab:0}); }else{ var r = hex >> 16; var g = (hex >> 8) & 0xff; var b = hex & 0xff; var a = 100-100*amount; col.setTransform({ra:a,rb:r*amount,ga:a,gb:g*amount,ba:a,bb:b*amount,aa:100,ab:0}); } } /** * Removes the full image being viewed in the slide revealing just the thumbnail */ SGImageSlide.prototype.clearFullImage = function(){ this.preloader.clear(); delete this.fullImageContainer.onEnterFrame; this.fullImage.unloadMovie(); this.fullImage.removeMovieClip(); this.fullImage = this.fullImageContainer.createEmptyMovieClip(""fullImage"", 0); } /** * Loads the full size version of the image into the slide for a single slide view */ SGImageSlide.prototype.loadFullImage = function(){ if (this.fullImage._width) return; this.clearFullImage(); this.fullImage.loadMovie(this.image.url); this.fullImageContainer.onEnterFrame = SGEventHandler.scope(this.fullImageTestLoad, this); } /** * Draws rounded rectangle shape for the slide */ SGImageSlide.prototype.drawSlideShape = function(w, h, b){ this.target.moveTo(-w+b, -h); this.target.lineTo(w-b, -h); this.target.curveTo(w, -h, w, -h+b); this.target.lineTo(w, h-b); this.target.curveTo(w, h, w-b, h); this.target.lineTo(-w+b, h); this.target.curveTo(-w, h, -w, h-b); this.target.lineTo(-w, -h+b); this.target.curveTo(-w, -h, -w+b, -h); } /** * Fits an image to the shape of the slide */ SGImageSlide.prototype.fitImage = function(target){ if (!target._width) return; target._xscale = 100; target._yscale = 100; var margin = 2*this.gallery.slideMargin; var slidePadding = 2*this.gallery.slidePadding; var w = this.gallery.availWidth - margin - slidePadding; var h = this.gallery.availHeight - margin - slidePadding; var scaleFactor = Math.min(w/target._width, h/target._height); target._xscale = 100 * scaleFactor; target._yscale = target._xscale; target._x = -target._width/2; target._y = -target._height/2; } /** * Removes a slide movie clip */ SGImageSlide.prototype.remove = function(){ this.target.removeMovieClip(); } /** * Polling function to check to see if the thumbnail has been * loaded by checking the size of the container movie clip */ SGImageSlide.prototype.thumbnailTestLoad = function(){ if (this.thumbnail._width){ this.loaded = true; this.draw(); delete this.thumbnailContainer.onEnterFrame; this.gallery.onSlideLoaded(this); } } /** * Polling function to check to see if the full image has been * loaded by checking the size of the container movie clip * While testing, it also manages a preloader seen at the bottom of the slide */ SGImageSlide.prototype.fullImageTestLoad = function(){ this.preloader.clear(); if (this.fullImage._width){ this.fitImage(this.fullImage); delete this.fullImageContainer.onEnterFrame; }else{ var left = this.thumbnail._x; var bottom = this.thumbnail._y + this.thumbnail._height; var right = left + this.thumbnail._width; var top = bottom - this.gallery.faceBorder; var loaded = this.fullImage.getBytesLoaded(); var total = this.fullImage.getBytesTotal(); var percentLoaded = (total) ? loaded/total : 0; right = left + (right-left)*percentLoaded; SGGraphics.simpleLinearGradient(this.preloader, top, bottom-top, this.gallery.backgroundColor, this.gallery.faceColor); this.preloader.moveTo(left, top); this.preloader.lineTo(right, top); this.preloader.lineTo(right, bottom); this.preloader.lineTo(left, bottom); this.preloader.lineTo(left, top); this.preloader.endFill(); } } /** * Sets up a keyframe for a tween to move a scale a slide to */ SGImageSlide.prototype.setDestination = function(x, y, scale){ var xr = Math.round(x); var yr = Math.round(y); var scaler = Math.round(scale); if (this.tween){ var args = this.tween.args; if (Math.round(args.x2) == xr && Math.round(args.y2) == yr && Math.round(args.scale2) == scaler){ return; } this.tween.stop(); delete this.tween; } if (Math.round(this.target._x) == xr && Math.round(this.target._y) == yr && Math.round(this.target._xscale) == scaler && this.target._rotation == 0){ return; } this.target._rotation = (this.target._x > x) ? 5 : -5; var args = { x:this.target._x, x2:x, spanX:x - this.target._x, y:this.target._y, y2:y, spanY:y - this.target._y, scale:this.target._xscale, scale2:scale, spanS:scale - this.target._xscale, r:this.target._rotation, r2:0, spanR:0 - this.target._rotation }; this.tween = new SGTweener(this.target, ""_xscale"", this.target._xscale, scale, this.destinationSteps, this.ease, args); this.tween.onTween = SGEventHandler.scope(this.onTween, this); this.tween.onTweenComplete = SGEventHandler.scope(this.onTweenComplete, this); this.tween.startTween(); } /** * Updates additional targets for a tween step; one tween is used per * slide and that tween only modifies one property */ SGImageSlide.prototype.onTween = function(){ this.target._yscale = this.target._xscale; var args = this.tween.args; this.target._x = args.x + args.spanX*this.tween.easePercent; this.target._y = args.y + args.spanY*this.tween.easePercent; this.target._rotation = args.r + args.spanR*this.tween.easePercent; } /** * Removes a tween instance when a tween completes */ SGImageSlide.prototype.onTweenComplete = function(n){ delete this.tween; } /** * Ease method for tweens */ SGImageSlide.prototype.ease = function(t){ return 1 + Math.sin(1.88*t - 1.88)/.95; } /** * Detects when the mouse comes in contact with this slide and saves it to the * selection contacts array for managing selections */ SGImageSlide.prototype.slideContact = function(){ this.gallery.toolTip.hide(); var sel = this.gallery.userSelection; var n = sel.contacts.length; var i; for (i=0; i mouseLoc.x){ this.directions |= 2; } if (this.last_ymouse < mouseLoc.y){ this.directions |= 4; }else if (this.last_ymouse > mouseLoc.y){ this.directions |= 8; } var dx = mouseLoc.x - this.last_xmouse; var dy = mouseLoc.y - this.last_ymouse; var dist = Math.sqrt(dx*dx, dy*dy); var thickness = Math.floor(dist/this.thicknessFactor); if (this.thickness > this.minThickness && thickness < this.thickness){ this.thickness--; }else if (this.thickness < this.maxThickness && thickness > this.thickness){ this.thickness++; } this.lineDraw.lineStyle(this.thickness, this.gallery.selectionColor); this.selectTest.lineTo(mouseLoc.x, mouseLoc.y); this.lineDraw.lineTo(mouseLoc.x, mouseLoc.y); this.last_xmouse = mouseLoc.x; this.last_ymouse = mouseLoc.y; } /** * Completes a gesture when the mouse is released */ SGUserSelection.prototype.selectRelease = function(){ if (!this.target.onMouseMove) return; delete this.target.onMouseMove; this.selectTest.endFill(); if (this.gallery.multiSelection) return; this.setSelection(); } /** * Returns the location of the mouse within the bounds of the gallery slide area */ SGUserSelection.prototype.getDrawingMouse = function(){ var x = this.target._xmouse; var y = this.target._ymouse; var clamped = false; var left = this.gallery.faceBorder; var right = this.gallery.width - this.gallery.faceBorder; var top = this.gallery.faceBorder; var bottom = this.gallery.height - this.gallery.faceBorder - this.gallery.hudHeight; if (x < left){ x = left; clamped = true; }else if (x > right){ x = right; clamped = true; } if (y < top){ y = top; clamped = true; }else if (y > bottom){ y = bottom; clamped = true; } return {x:x, y:y, clamped:clamped}; } /** * When a selection is complete, select or deselect slides and clear drawing */ SGUserSelection.prototype.setSelection = function(){ if (this.directions == 15){ this.selectionType = SGUserSelection.SELECT; this.slides = this.getSelectedSlides(); }else{ this.selectionType = SGUserSelection.DESELECT; this.slides = this.contacts; } this.selectTest.clear(); this.lineDraw.clear(); this.gallery.onSelection(this); this.selectionType = null; } /** * Finds and returns all slides selected in the current gesture */ SGUserSelection.prototype.getSelectedSlides = function(){ var selectedSlides = []; var slides = this.gallery.currGroup.slides; var graphic; var pt = new Object(); var n = slides.length; var i; for (i=0; i