text,length,is_long_context,metric_val,label_metric "// Animated eyes for Adafruit MONSTER M4SK and HALLOWING M4 dev boards. // This code is pretty tightly coupled to the resources of these boards // (one or two ST7789 240x240 pixel TFTs on separate SPI buses, and a // SAMD51 microcontroller), and not as generally portable as the prior // ""Uncanny Eyes"" project (better for SAMD21 chips or Teensy 3.X and // 128x128 TFT or OLED screens, single SPI bus). // IMPORTANT: in rare situations, a board may get ""bricked"" when running // this code while simultaneously connected to USB. A quick-flashing status // LED indicates the filesystem has gone corrupt. If this happens, install // CircuitPython to reinitialize the filesystem, copy over your eye files // (keep backups!), then re-upload this code. It seems to happen more often // at high optimization settings (above -O3), but there's not 1:1 causality. // The exact cause has not yet been found...possibly insufficient yield() // calls, or some rare alignment in the Arcada library or USB-handling code. // LET'S HAVE A WORD ABOUT COORDINATE SYSTEMS before continuing. From an // outside observer's point of view, looking at the display(s) on these // boards, the eyes are rendered COLUMN AT A TIME, working LEFT TO RIGHT, // rather than the horizontal scanline order of Uncanny Eyes and most other // graphics-heavy code. It was found much easier to animate the eyelids when // working along this axis. A ""column major"" display is easily achieved by // setting the screen(s) to ROTATION 3, which is a 90 degree // counterclockwise rotation relative to the default. This places (0,0) at // the BOTTOM-LEFT of the display, with +X being UP and +Y being RIGHT -- // so, conceptually, just swapping axes you have a traditional Cartesian // coordinate system and trigonometric functions work As Intended, and the // code tends to ""think"" that way in most places. Since the rotation is done // in hardware though...from the display driver's point of view, one might // think of these as ""horizontal"" ""scanlines,"" and that the eye is being // drawn sideways, with a left and right eyelid rather than bottom and top. // Just mentioning it here because there may still be lingering comments // and/or variables in the code where I refer to ""scanlines"" even though // visually/spatially these are columns. Will do my best to comment local // coordinate systems in different spots. (Any raster images loaded by // Adafruit_ImageReader are referenced in typical +Y = DOWN order.) // Oh also, ""left eye"" and ""right eye"" refer to the MONSTER'S left and // right. From an observer's point of view, looking AT the monster, the // ""right eye"" is on the left. #if !defined(USE_TINYUSB) #error ""Please select Tools->USB Stack->TinyUSB before compiling"" #endif #define GLOBAL_VAR #include ""globals.h"" // Global eye state that applies to all eyes (not per-eye): bool eyeInMotion = false; float eyeOldX, eyeOldY, eyeNewX, eyeNewY; uint32_t eyeMoveStartTime = 0L; int32_t eyeMoveDuration = 0L; uint32_t lastSaccadeStop = 0L; int32_t saccadeInterval = 0L; // Some sloppy eye state stuff, some carried over from old eye code... // kinda messy and badly named and will get cleaned up/moved/etc. uint32_t timeOfLastBlink = 0L, timeToNextBlink = 0L; int xPositionOverMap = 0; int yPositionOverMap = 0; uint8_t eyeNum = 0; uint32_t frames = 0; uint32_t lastFrameRateReportTime = 0; uint32_t lastLightReadTime = 0; float lastLightValue = 0.5; double irisValue = 0.5; int iPupilFactor = 42; uint32_t boopSum = 0, boopSumFiltered = 0; bool booped = false; int fixate = 7; uint8_t lightSensorFailCount = 0; // For autonomous iris scaling #define IRIS_LEVELS 7 float iris_prev[IRIS_LEVELS] = { 0 }; float iris_next[IRIS_LEVELS] = { 0 }; uint16_t iris_frame = 0; // Callback invoked after each SPI DMA transfer - sets a flag indicating // the next line of graphics can be issued as soon as its ready. static void dma_callback(Adafruit_ZeroDMA *dma) { // It's possible to assign each DMA channel its own callback function // (freeing up a few cycles vs. this channel-to-eye lookup), but it's // written this way to scale to as many eyes as needed (up to one per // SERCOM if this is ported to something like Grand Central). for(uint8_t e=0; e50MHz SPI was fun but just too glitchy to rely on //#if F_CPU < 200000000 // #define DISPLAY_FREQ (F_CPU / 2) // #define DISPLAY_CLKSRC SERCOM_CLOCK_SOURCE_FCPU //#else #define DISPLAY_FREQ 50000000 #define DISPLAY_CLKSRC SERCOM_CLOCK_SOURCE_100M //#endif SPISettings settings(DISPLAY_FREQ, MSBFIRST, SPI_MODE0); // The time required to issue one scanline (DISPLAY_SIZE pixels x 16 bits) over // SPI is a known(ish) quantity. The DMA scheduler isn't always perfectly // deterministic though...especially on startup, as things make their way // into caches. Very occasionally, something (not known yet) is causing // SPI DMA to seize up. This condition is pretty easy to check for... // periodically the code needs to wait on a DMA transfer to finish // anyway, and we can use the micros() function to determine if it's taken // considerably longer than expected (a factor of 4 is used - the ""4000"" // below, to allow for caching/scheduling fudge). If so, that's our signal // that something is likely amiss and we take evasive maneuvers, resetting // the affected DMA channel (DMAbuddy::fix()). #define DMA_TIMEOUT (uint32_t)((DISPLAY_SIZE * 16 * 4000) / (DISPLAY_FREQ / 1000)) static inline uint16_t readBoop(void) { uint16_t counter = 0; pinMode(boopPin, OUTPUT); digitalWrite(boopPin, HIGH); pinMode(boopPin, INPUT); while(digitalRead(boopPin) && (++counter < 1000)); return counter; } // Crude error handler. Prints message to Serial Monitor, blinks LED. void fatal(const char *message, uint16_t blinkDelay) { Serial.begin(9600); Serial.println(message); for(bool ledState = HIGH;; ledState = !ledState) { digitalWrite(LED_BUILTIN, ledState); delay(blinkDelay); } } #include // sbrk() function uint32_t availableRAM(void) { char top; // Local variable pushed on stack return &top - (char *)sbrk(0); // Top of stack minus end of heap } // SETUP FUNCTION - CALLED ONCE AT PROGRAM START --------------------------- void setup() { if(!arcada.arcadaBegin()) fatal(""Arcada init fail!"", 100); #if defined(USE_TINYUSB) if(!arcada.filesysBeginMSD()) fatal(""No filesystem found!"", 250); #else if(!arcada.filesysBegin()) fatal(""No filesystem found!"", 250); #endif user_setup(); arcada.displayBegin(); // Backlight(s) off ASAP, they'll switch on after screen(s) init & clear arcada.setBacklight(0); DISPLAY_SIZE = min(ARCADA_TFT_WIDTH, ARCADA_TFT_HEIGHT); Serial.begin(115200); //while(!Serial) yield(); Serial.printf(""Available RAM at start: %d\\n"", availableRAM()); Serial.printf(""Available flash at start: %d\\n"", arcada.availableFlash()); yield(); // Periodic yield() makes sure mass storage filesystem stays alive // No file selector yet. In the meantime, you can override the default // config file by holding one of the 3 edge buttons at startup (loads // config1.eye, config2.eye or config3.eye instead). Keep fingers clear // of the nose booper when doing this...it self-calibrates on startup. // DO THIS BEFORE THE SPLASH SO IT DOESN'T REQUIRE A LENGTHY HOLD. char *filename = (char *)""config.eye""; uint32_t buttonState = arcada.readButtons(); if((buttonState & ARCADA_BUTTONMASK_UP) && arcada.exists(""config1.eye"")) { filename = (char *)""config1.eye""; } else if((buttonState & ARCADA_BUTTONMASK_A) && arcada.exists(""config2.eye"")) { filename = (char *)""config2.eye""; } else if((buttonState & ARCADA_BUTTONMASK_DOWN) && arcada.exists(""config3.eye"")) { filename = (char *)""config3.eye""; } yield(); // Initialize display(s) #if (NUM_EYES > 1) eye[0].display = arcada._display; eye[1].display = arcada.display2; #else eye[0].display = arcada.display; #endif // Initialize DMAs yield(); uint8_t e; for(e=0; esetClockSource(DISPLAY_CLKSRC); // Accelerate SPI! #endif eye[e].display->fillScreen(0); eye[e].dma.allocate(); eye[e].dma.setTrigger(eye[e].spi->getDMAC_ID_TX()); eye[e].dma.setAction(DMA_TRIGGER_ACTON_BEAT); eye[e].dptr = eye[e].dma.addDescriptor(NULL, NULL, 42, DMA_BEAT_SIZE_BYTE, false, false); eye[e].dma.setCallback(dma_callback); eye[e].dma.setPriority(DMA_PRIORITY_0); uint32_t spi_data_reg = (uint32_t)eye[e].spi->getDataRegister(); for(int i=0; i<2; i++) { // For each of 2 scanlines... for(int j=0; j 1) { // Load on other eye too, ignore status yield(); arcada.drawBMP((char *)""/splash.bmp"", 0, 0, eye[1].display); } // Ramp up backlight over 1/2 sec duration startTime = millis(); while ((elapsed = (millis() - startTime)) <= 500) { yield(); arcada.setBacklight(255 * elapsed / 500); } arcada.setBacklight(255); // To the max startTime = millis(); // Note current time for backlight hold later } } // If no splash, or load failed, turn backlight on early so user gets a // little feedback, that the board is not locked up, just thinking. if (!showSplashScreen) arcada.setBacklight(255); // LOAD CONFIGURATION FILE ----------------------------------------------- loadConfig(filename); // LOAD EYELIDS AND TEXTURE MAPS ----------------------------------------- // Experiencing a problem with MEMORY FRAGMENTATION when loading texture // maps. These images only occupy RAM temporarily -- they're copied to // internal flash memory and then freed. However, something is preventing // the freed memory from restoring to a contiguous block. For example, // if a texture image equal to about 50% of RAM is loaded/copied/freed, // following this with a larger texture (or trying to allocate a larger // polar lookup array) fails because RAM is fragmented into two segments. // I've been through this code, Adafruit_ImageReader and Adafruit_GFX // pretty carefully and they appear to be freeing RAM in the reverse order // that they allocate (which should avoid fragmentation), but I'm likely // overlooking something there or additional allocations are occurring // in other libraries -- perhaps the filesystem and/or mass storage code. // SO, here is the DIRTY WORKAROUND... // Adafruit_ImageReader provides a bmpDimensions() function to determine // the pixel size of an image without actually loading it. We can use this // to estimate the RAM requirements for loading the image, then allocate // a ""booster seat"" which makes the subsequent image load occur in higher // memory, and the fragmenting part a bit beyond that. When the image and // booster are both freed, that should restore a large contiguous chunk, // leaving the fragments in high memory. Not TOO high though, we need to // leave some RAM for the stack to operate over the lifetime of this // program and to handle small heap allocations. uint32_t maxRam = availableRAM() - stackReserve; // Load texture maps for eyes uint8_t e2; for(e=0; e= e)) { // If first eye, or no match found... // If no iris filename was specified, or if file fails to load... if((eye[e].iris.filename == NULL) || (loadTexture(eye[e].iris.filename, &eye[e].iris.data, &eye[e].iris.width, &eye[e].iris.height, maxRam) != IMAGE_SUCCESS)) { // Point iris data at the color variable and set image size to 1px eye[e].iris.data = &eye[e].iris.color; eye[e].iris.width = eye[e].iris.height = 1; } // Huh. The booster seat idea STILL doesn't always work right, // something leaking in upper memory. Keep shrinking down the // booster seat size a bit each time we load a texture. Feh. maxRam -= 20; } // Repeat for sclera... for(e2=0; e2= e)) { // If first eye, or no match found... // If no sclera filename was specified, or if file fails to load... if((eye[e].sclera.filename == NULL) || (loadTexture(eye[e].sclera.filename, &eye[e].sclera.data, &eye[e].sclera.width, &eye[e].sclera.height, maxRam) != IMAGE_SUCCESS)) { // Point sclera data at the color variable and set image size to 1px eye[e].sclera.data = &eye[e].sclera.color; eye[e].sclera.width = eye[e].sclera.height = 1; } maxRam -= 20; // See note above } } // Load eyelid graphics. yield(); ImageReturnCode status; status = loadEyelid(upperEyelidFilename ? upperEyelidFilename : (char *)""upper.bmp"", upperClosed, upperOpen, DISPLAY_SIZE-1, maxRam); status = loadEyelid(lowerEyelidFilename ? lowerEyelidFilename : (char *)""lower.bmp"", lowerOpen, lowerClosed, 0, maxRam); // Filenames are no longer needed... for(e=0; eVAL + analogRead(A2)); eyeOldX = eyeNewX = eyeOldY = eyeNewY = mapRadius; // Start in center for(e=0; esetRotation(eye[e].rotation); eye[e].eyeX = eyeOldX; // Set up initial position eye[e].eyeY = eyeOldY; } if (showSplashScreen) { // Image(s) loaded above? // Hold backlight on for up to 2 seconds (minus other initialization time) if ((elapsed = (millis() - startTime)) < 2000) { delay(2000 - elapsed); } // Ramp down backlight over 1/2 sec duration startTime = millis(); while ((elapsed = (millis() - startTime)) <= 500) { yield(); arcada.setBacklight(255 - (255 * elapsed / 500)); } arcada.setBacklight(0); for(e=0; efillScreen(0); } } #if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS) if(voiceOn) { if(!voiceSetup((waveform > 0))) { Serial.println(""Voice init fail, continuing without""); voiceOn = false; } else { voiceGain(gain); currentPitch = voicePitch(currentPitch); if(waveform) voiceMod(modulate, waveform); arcada.enableSpeaker(true); } } #endif arcada.setBacklight(255); // Back on, impending graphics yield(); if(boopPin >= 0) { boopThreshold = 0; for(int i=0; i= NUM_EYES) eyeNum = 0; // Cycle through eyes... uint8_t x = eye[eyeNum].colNum; uint32_t t = micros(); // If next column for this eye is not yet rendered... if(!eye[eyeNum].column_ready) { if(!x) { // If it's the first column... // ONCE-PER-FRAME EYE ANIMATION LOGIC HAPPENS HERE ------------------- // Eye movement float eyeX, eyeY; if(moveEyesRandomly) { int32_t dt = t - eyeMoveStartTime; // uS elapsed since last eye event if(eyeInMotion) { // Eye currently moving? if(dt >= eyeMoveDuration) { // Time up? Destination reached. eyeInMotion = false; // Stop moving // The ""move"" duration temporarily becomes a hold duration... // Normally this is 35 ms to 1 sec, but don't exceed gazeMax setting uint32_t limit = min(1000000, gazeMax); eyeMoveDuration = random(35000, limit); // Time between microsaccades if(!saccadeInterval) { // Cleared when ""big"" saccade finishes lastSaccadeStop = t; // Time when saccade stopped saccadeInterval = random(eyeMoveDuration, gazeMax); // Next in 30ms to 3sec } // Similarly, the ""move"" start time becomes the ""stop"" starting time... eyeMoveStartTime = t; // Save time of event eyeX = eyeOldX = eyeNewX; // Save position eyeY = eyeOldY = eyeNewY; } else { // Move time's not yet fully elapsed -- interpolate position float e = (float)dt / float(eyeMoveDuration); // 0.0 to 1.0 during move e = 3 * e * e - 2 * e * e * e; // Easing function: 3*e^2-2*e^3 0.0 to 1.0 eyeX = eyeOldX + (eyeNewX - eyeOldX) * e; // Interp X eyeY = eyeOldY + (eyeNewY - eyeOldY) * e; // and Y } } else { // Eye is currently stopped eyeX = eyeOldX; eyeY = eyeOldY; if(dt > eyeMoveDuration) { // Time up? Begin new move. if((t - lastSaccadeStop) > saccadeInterval) { // Time for a ""big"" saccade // r is the radius in X and Y that the eye can go, from (0,0) in the center. float r = ((float)mapDiameter - (float)DISPLAY_SIZE * M_PI_2) * 0.75; eyeNewX = random(-r, r); float h = sqrt(r * r - eyeNewX * eyeNewX); eyeNewY = random(-h, h); // Set the duration for this move, and start it going. eyeMoveDuration = random(83000, 166000); // ~1/12 - ~1/6 sec saccadeInterval = 0; // Calc next interval when this one stops } else { // Microsaccade // r is possible radius of motion, ~1/10 size of full saccade. // We don't bother with clipping because if it strays just a little, // that's okay, it'll get put in-bounds on next full saccade. float r = (float)mapDiameter - (float)DISPLAY_SIZE * M_PI_2; r *= 0.07; float dx = random(-r, r); eyeNewX = eyeX - mapRadius + dx; float h = sqrt(r * r - dx * dx); eyeNewY = eyeY - mapRadius + random(-h, h); eyeMoveDuration = random(7000, 25000); // 7-25 ms microsaccade } eyeNewX += mapRadius; // Translate new point into map space eyeNewY += mapRadius; eyeMoveStartTime = t; // Save initial time of move eyeInMotion = true; // Start move on next frame } } } else { // Allow user code to control eye position (e.g. IR sensor, joystick, etc.) float r = ((float)mapDiameter - (float)DISPLAY_SIZE * M_PI_2) * 0.9; eyeX = mapRadius + eyeTargetX * r; eyeY = mapRadius + eyeTargetY * r; } // Eyes fixate (are slightly crossed) -- amount is filtered for boops int nufix = booped ? 90 : 7; fixate = ((fixate * 15) + nufix) / 16; // save eye position to this eye's struct so it's same throughout render if(eyeNum & 1) eyeX += fixate; // Eyes converge slightly toward center else eyeX -= fixate; eye[eyeNum].eyeX = eyeX; eye[eyeNum].eyeY = eyeY; // pupilFactor? irisValue? TO DO: pick a name and stick with it eye[eyeNum].pupilFactor = irisValue; // Also note - irisValue is calculated at the END of this function // for the next frame (because the sensor must be read when there's // no SPI traffic to the left eye) // Similar to the autonomous eye movement above -- blink start times // and durations are random (within ranges). if((t - timeOfLastBlink) >= timeToNextBlink) { // Start new blink? timeOfLastBlink = t; uint32_t blinkDuration = random(36000, 72000); // ~1/28 - ~1/14 sec // Set up durations for both eyes (if not already winking) for(uint8_t e=0; e upperOpen[ix]) { uq = 1.0; } else if(iy < upperClosed[ix]) { uq = 0.0; } else { uq = (float)(iy - upperClosed[ix]) / (float)(upperOpen[ix] - upperClosed[ix]); } if(booped) { uq = 0.9; lq = 0.7; } else { lq = 1.0 - uq; } } else { // If no tracking, eye is FULLY OPEN when not blinking uq = 1.0; lq = 1.0; } // Dampen eyelid movements slightly // SAVE upper & lower lid factors per eye, // they need to stay consistent across frame eye[eyeNum].upperLidFactor = (eye[eyeNum].upperLidFactor * 0.6) + (uq * 0.4); eye[eyeNum].lowerLidFactor = (eye[eyeNum].lowerLidFactor * 0.6) + (lq * 0.4); // Process blinks if(eye[eyeNum].blink.state) { // Eye currently blinking? // Check if current blink state time has elapsed if((t - eye[eyeNum].blink.startTime) >= eye[eyeNum].blink.duration) { if(++eye[eyeNum].blink.state > DEBLINK) { // Deblinking finished? eye[eyeNum].blink.state = NOBLINK; // No longer blinking eye[eyeNum].blinkFactor = 0.0; } else { // Advancing from ENBLINK to DEBLINK mode eye[eyeNum].blink.duration *= 2; // DEBLINK is 1/2 ENBLINK speed eye[eyeNum].blink.startTime = t; eye[eyeNum].blinkFactor = 1.0; } } else { eye[eyeNum].blinkFactor = (float)(t - eye[eyeNum].blink.startTime) / (float)eye[eyeNum].blink.duration; if(eye[eyeNum].blink.state == DEBLINK) eye[eyeNum].blinkFactor = 1.0 - eye[eyeNum].blinkFactor; } } // Periodically report frame rate. Really this is ""total number of // eyeballs drawn."" If there are two eyes, the overall refresh rate // of both screens is about 1/2 this. frames++; if(((t - lastFrameRateReportTime) >= 1000000) && t) { // Once per sec. Serial.println((frames * 1000) / (t / 1000)); lastFrameRateReportTime = t; } // Once per frame (of eye #0), reset boopSum... if((eyeNum == 0) && (boopPin >= 0)) { boopSumFiltered = ((boopSumFiltered * 3) + boopSum) / 4; if(boopSumFiltered > boopThreshold) { if(!booped) { Serial.println(""BOOP!""); } booped = true; } else { booped = false; } boopSum = 0; } float mins = (float)millis() / 60000.0; if(eye[eyeNum].iris.iSpin) { // Spin works in fixed amount per frame (eyes may lose sync, but ""wagon wheel"" tricks work) eye[eyeNum].iris.angle += eye[eyeNum].iris.iSpin; } else { // Keep consistent timing in spin animation (eyes stay in sync, no ""wagon wheel"" effects) eye[eyeNum].iris.angle = (int)((float)eye[eyeNum].iris.startAngle + eye[eyeNum].iris.spin * mins + 0.5); } if(eye[eyeNum].sclera.iSpin) { eye[eyeNum].sclera.angle += eye[eyeNum].sclera.iSpin; } else { eye[eyeNum].sclera.angle = (int)((float)eye[eyeNum].sclera.startAngle + eye[eyeNum].sclera.spin * mins + 0.5); } // END ONCE-PER-FRAME EYE ANIMATION ---------------------------------- } // end first-scanline check // PER-COLUMN RENDERING ------------------------------------------------ // Should be possible for these to be local vars, // but the animation becomes super chunky then, what gives? xPositionOverMap = (int)(eye[eyeNum].eyeX - (DISPLAY_SIZE/2.0)); yPositionOverMap = (int)(eye[eyeNum].eyeY - (DISPLAY_SIZE/2.0)); // These are constant across frame and could be stored in eye struct float upperLidFactor = (1.0 - eye[eyeNum].blinkFactor) * eye[eyeNum].upperLidFactor, lowerLidFactor = (1.0 - eye[eyeNum].blinkFactor) * eye[eyeNum].lowerLidFactor; iPupilFactor = (int)((float)eye[eyeNum].iris.height * 256 * (1.0 / eye[eyeNum].pupilFactor)); int y1, y2; int lidColumn = (eyeNum & 1) ? (DISPLAY_SIZE - 1 - x) : x; // Reverse eyelid columns for left eye DmacDescriptor *d = &eye[eyeNum].column[eye[eyeNum].colIdx].descriptor[0]; if(upperOpen[lidColumn] == 255) { // No eyelid data for this line; eyelid image is smaller than screen. // Great! Make a full scanline of nothing, no rendering needed: d->BTCTRL.bit.SRCINC = 0; d->BTCNT.reg = DISPLAY_SIZE * 2; d->SRCADDR.reg = (uint32_t)&eyelidIndex; d->DESCADDR.reg = 0; // No linked descriptor } else { y1 = lowerClosed[lidColumn] + (int)(0.5 + lowerLidFactor * (float)((int)lowerOpen[lidColumn] - (int)lowerClosed[lidColumn])); y2 = upperClosed[lidColumn] + (int)(0.5 + upperLidFactor * (float)((int)upperOpen[lidColumn] - (int)upperClosed[lidColumn])); if(y1 > DISPLAY_SIZE-1) y1 = DISPLAY_SIZE-1; // Clip results in case lidfactor else if(y1 < 0) y1 = 0; // is beyond the usual 0.0 to 1.0 range if(y2 > DISPLAY_SIZE-1) y2 = DISPLAY_SIZE-1; else if(y2 < 0) y2 = 0; if(y1 >= y2) { // Eyelid is fully or partially closed, enough that there are no // pixels to be rendered for this line. Make ""nothing,"" as above. d->BTCTRL.bit.SRCINC = 0; d->BTCNT.reg = DISPLAY_SIZE * 2; d->SRCADDR.reg = (uint32_t)&eyelidIndex; d->DESCADDR.reg = 0; // No linked descriptors } else { // If single eye, dynamically build descriptor list as needed, // else use a single descriptor & fully buffer each line. #if NUM_DESCRIPTORS > 1 DmacDescriptor *next; int renderlen; if(y1 > 0) { // Do upper eyelid unless at top of image d->BTCTRL.bit.SRCINC = 0; d->BTCNT.reg = y1 * 2; d->SRCADDR.reg = (uint32_t)&eyelidIndex; next = &eye[eyeNum].column[eye[eyeNum].colIdx].descriptor[1]; d->DESCADDR.reg = (uint32_t)next; // Link to next descriptor d = next; // Advance to next descriptor } // Partial column will be rendered renderlen = y2 - y1 + 1; d->BTCTRL.bit.SRCINC = 1; d->BTCNT.reg = renderlen * 2; d->SRCADDR.reg = (uint32_t)eye[eyeNum].column[eye[eyeNum].colIdx].renderBuf + renderlen * 2; // Point to END of data! #else // Full column will be rendered; DISPLAY_SIZE pixels, point source to end of // renderBuf and enable source increment. d->BTCTRL.bit.SRCINC = 1; d->BTCNT.reg = DISPLAY_SIZE * 2; d->SRCADDR.reg = (uint32_t)eye[eyeNum].column[eye[eyeNum].colIdx].renderBuf + DISPLAY_SIZE * 2; d->DESCADDR.reg = 0; // No linked descriptors #endif // Render column 'x' into eye's next available renderBuf uint16_t *ptr = eye[eyeNum].column[eye[eyeNum].colIdx].renderBuf; int xx = xPositionOverMap + x; int y; #if NUM_DESCRIPTORS == 1 // Render lower eyelid if needed for(y=0; y= 0) && (mx < mapDiameter) && (my >= 0) && (my < mapDiameter)) { // Inside polar angle/dist map int angle, dist, moff; if(my >= mapRadius) { if(mx >= mapRadius) { // Quadrant 1 // Use angle & dist directly mx -= mapRadius; my -= mapRadius; moff = my * mapRadius + mx; // Offset into map arrays angle = polarAngle[moff]; dist = polarDist[moff]; } else { // Quadrant 2 // ROTATE angle by 90 degrees (270 degrees clockwise; 768) // MIRROR dist on X axis mx = mapRadius - 1 - mx; my -= mapRadius; angle = polarAngle[mx * mapRadius + my] + 768; dist = polarDist[ my * mapRadius + mx]; } } else { if(mx < mapRadius) { // Quadrant 3 // ROTATE angle by 180 degrees // MIRROR dist on X & Y axes mx = mapRadius - 1 - mx; my = mapRadius - 1 - my; moff = my * mapRadius + mx; angle = polarAngle[moff] + 512; dist = polarDist[ moff]; } else { // Quadrant 4 // ROTATE angle by 270 degrees (90 degrees clockwise; 256) // MIRROR dist on Y axis mx -= mapRadius; my = mapRadius - 1 - my; angle = polarAngle[mx * mapRadius + my] + 256; dist = polarDist[ my * mapRadius + mx]; } } // Convert angle/dist to texture map coords if(dist >= 0) { // Sclera angle = ((angle + eye[eyeNum].sclera.angle) & 1023) ^ eye[eyeNum].sclera.mirror; int tx = angle * eye[eyeNum].sclera.width / 1024; // Texture map x/y int ty = dist * eye[eyeNum].sclera.height / 128; *ptr++ = eye[eyeNum].sclera.data[ty * eye[eyeNum].sclera.width + tx]; } else if(dist > -128) { // Iris or pupil int ty = dist * iPupilFactor / -32768; if(ty >= eye[eyeNum].iris.height) { // Pupil *ptr++ = eye[eyeNum].pupilColor; } else { // Iris angle = ((angle + eye[eyeNum].iris.angle) & 1023) ^ eye[eyeNum].iris.mirror; int tx = angle * eye[eyeNum].iris.width / 1024; *ptr++ = eye[eyeNum].iris.data[ty * eye[eyeNum].iris.width + tx]; } } else { *ptr++ = eye[eyeNum].backColor; // Back of eye } } else { *ptr++ = eye[eyeNum].backColor; // Off map, use back-of-eye color } } else { // Outside eyeball area *ptr++ = eyelidColor; } } #if NUM_DESCRIPTORS == 1 // Render upper eyelid if needed for(; y= (DISPLAY_SIZE-1)) { // No third descriptor; close it off d->DESCADDR.reg = 0; } else { next = &eye[eyeNum].column[eye[eyeNum].colIdx].descriptor[(y1 > 0) ? 2 : 1]; d->DESCADDR.reg = (uint32_t)next; // link to next descriptor d = next; // Increment descriptor d->BTCTRL.bit.SRCINC = 0; d->BTCNT.reg = ((DISPLAY_SIZE-1) - y2) * 2; d->SRCADDR.reg = (uint32_t)&eyelidIndex; d->DESCADDR.reg = 0; // end of descriptor list } #endif } } eye[eyeNum].column_ready = true; // Line is rendered! } // If DMA for this eye is currently busy, don't block, try next eye... if(eye[eyeNum].dma_busy) { if((micros() - eye[eyeNum].dmaStartTime) < DMA_TIMEOUT) return; // If we reach this point in the code, an SPI DMA transfer has taken // noticably longer than expected and is probably stalled (see comments // in the DMAbuddy.h file and above the DMA_TIMEOUT declaration earlier // in this code). Take action! // digitalWrite(13, HIGH); Serial.printf(""Eye #%d stalled, resetting DMA channel...\\n"", eyeNum); eye[eyeNum].dma.fix(); // If this somehow proves to be inadequate, we still have the Nuclear // Option of just completely restarting the sketch from the beginning, // though this stalls animation for several seconds during startup. // DO NOT enable this line unless the fix() function isn't fixing! //NVIC_SystemReset(); } // At this point, above checks confirm that column is ready and DMA is free if(!x) { // If it's the first column... // End prior SPI transaction... digitalWrite(eye[eyeNum].cs, HIGH); // Deselect eye[eyeNum].spi->endTransaction(); // Initialize new SPI transaction & address window... eye[eyeNum].spi->beginTransaction(settings); digitalWrite(eye[eyeNum].cs, LOW); // Chip select eye[eyeNum].display->setAddrWindow((eye[eyeNum].display->width() - DISPLAY_SIZE) / 2, (eye[eyeNum].display->height() - DISPLAY_SIZE) / 2, DISPLAY_SIZE, DISPLAY_SIZE); delayMicroseconds(1); digitalWrite(eye[eyeNum].dc, HIGH); // Data mode if(eyeNum == (NUM_EYES-1)) { // Handle pupil scaling if(lightSensorPin >= 0) { // Read light sensor, but not too often (Seesaw hates that) #define LIGHT_INTERVAL (1000000 / 10) // 10 Hz, don't poll Seesaw too often if((t - lastLightReadTime) >= LIGHT_INTERVAL) { // Fun fact: eyes have a ""consensual response"" to light -- both // pupils will react even if the opposite eye is stimulated. // Meaning we can get away with using a single light sensor for // both eyes. This comment has nothing to do with the code. uint16_t rawReading = arcada.readLightSensor(); if(rawReading <= 1023) { if(rawReading < lightSensorMin) rawReading = lightSensorMin; // Clamp light sensor range else if(rawReading > lightSensorMax) rawReading = lightSensorMax; // to within usable range float v = (float)(rawReading - lightSensorMin) / (float)(lightSensorMax - lightSensorMin); // 0.0 to 1.0 v = pow(v, lightSensorCurve); lastLightValue = irisMin + v * irisRange; lastLightReadTime = t; lightSensorFailCount = 0; } else { // I2C error if(++lightSensorFailCount >= 25) { // If repeated errors in succession... lightSensorPin = -1; // Stop trying to use the light sensor } else { lastLightReadTime = t - LIGHT_INTERVAL + 30000; // Try again in 30 ms } } } irisValue = (irisValue * 0.97) + (lastLightValue * 0.03); // Filter response for smooth reaction } else { // Not light responsive. Use autonomous iris w/fractal subdivision float n, sum = 0.5; for(uint16_t i=0; i iris min/max if((++iris_frame) >= (1 << IRIS_LEVELS)) iris_frame = 0; } #if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS) if(voiceOn) { // Read buttons, change pitch arcada.readButtons(); uint32_t buttonState = arcada.justPressedButtons(); if( buttonState & ARCADA_BUTTONMASK_UP) { currentPitch *= 1.05; } else if(buttonState & ARCADA_BUTTONMASK_A) { currentPitch = defaultPitch; } else if(buttonState & ARCADA_BUTTONMASK_DOWN) { currentPitch *= 0.95; } if(buttonState & (ARCADA_BUTTONMASK_UP | ARCADA_BUTTONMASK_A | ARCADA_BUTTONMASK_DOWN)) { currentPitch = voicePitch(currentPitch); if(waveform) voiceMod(modulate, waveform); Serial.print(""Voice pitch: ""); Serial.println(currentPitch); } } #endif user_loop(); } } // end first-column check // MUST read the booper when there’s no SPI traffic across the nose! if((eyeNum == (NUM_EYES-1)) && (boopPin >= 0)) { boopSum += readBoop(); } memcpy(eye[eyeNum].dptr, &eye[eyeNum].column[eye[eyeNum].colIdx].descriptor[0], sizeof(DmacDescriptor)); eye[eyeNum].dma_busy = true; eye[eyeNum].dma.startJob(); eye[eyeNum].dmaStartTime = micros(); if(++eye[eyeNum].colNum >= DISPLAY_SIZE) { // If last line sent... eye[eyeNum].colNum = 0; // Wrap to beginning } eye[eyeNum].colIdx ^= 1; // Alternate 0/1 line structs eye[eyeNum].column_ready = false; // OK to render next line } ",12471,False,2297.9908366291547,median "#include #include #include #include #include using namespace std::chrono_literals; namespace { void add_callback_stats (nano::node & node) { node.observers.blocks.add ([& stats = node.stats](nano::election_status const & status_a, nano::account const &, nano::amount const &, bool) { stats.inc (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out); }); } } TEST (confirmation_height, single) { auto amount (std::numeric_limits::max ()); nano::system system; auto node = system.add_node (); nano::keypair key1; system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest1 (node->latest (nano::test_genesis_key.pub)); auto send1 (std::make_shared (nano::test_genesis_key.pub, latest1, nano::test_genesis_key.pub, amount - 100, key1.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest1))); // Check confirmation heights before, should be uninitialized (1 for genesis). nano::confirmation_height_info confirmation_height_info; add_callback_stats (*node); auto transaction = node->store.tx_begin_read (); ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (1, confirmation_height_info.height); ASSERT_EQ (nano::genesis ().hash (), confirmation_height_info.frontier); node->process_active (send1); node->block_processor.flush (); system.deadline_set (10s); while (true) { auto transaction = node->store.tx_begin_read (); if (node->ledger.block_confirmed (transaction, send1->hash ())) { break; } ASSERT_NO_ERROR (system.poll ()); } { auto transaction = node->store.tx_begin_write (); ASSERT_TRUE (node->ledger.block_confirmed (transaction, send1->hash ())); ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (2, confirmation_height_info.height); ASSERT_EQ (send1->hash (), confirmation_height_info.frontier); // Rollbacks should fail as these blocks have been cemented ASSERT_TRUE (node->ledger.rollback (transaction, latest1)); ASSERT_TRUE (node->ledger.rollback (transaction, send1->hash ())); ASSERT_EQ (1, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (1, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); } } TEST (confirmation_height, multiple_accounts) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); nano::keypair key1; nano::keypair key2; nano::keypair key3; system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest1 (system.nodes[0]->latest (nano::test_genesis_key.pub)); system.wallet (0)->insert_adhoc (key1.prv); system.wallet (0)->insert_adhoc (key2.prv); system.wallet (0)->insert_adhoc (key3.prv); // Send to all accounts nano::send_block send1 (latest1, key1.pub, system.nodes.front ()->config.online_weight_minimum.number () + 300, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest1)); nano::send_block send2 (send1.hash (), key2.pub, system.nodes.front ()->config.online_weight_minimum.number () + 200, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send1.hash ())); nano::send_block send3 (send2.hash (), key3.pub, system.nodes.front ()->config.online_weight_minimum.number () + 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send2.hash ())); // Open all accounts nano::open_block open1 (send1.hash (), nano::genesis_account, key1.pub, key1.prv, key1.pub, *system.work.generate (key1.pub)); nano::open_block open2 (send2.hash (), nano::genesis_account, key2.pub, key2.prv, key2.pub, *system.work.generate (key2.pub)); nano::open_block open3 (send3.hash (), nano::genesis_account, key3.pub, key3.prv, key3.pub, *system.work.generate (key3.pub)); // Send and receive various blocks to these accounts nano::send_block send4 (open1.hash (), key2.pub, 50, key1.prv, key1.pub, *system.work.generate (open1.hash ())); nano::send_block send5 (send4.hash (), key2.pub, 10, key1.prv, key1.pub, *system.work.generate (send4.hash ())); nano::receive_block receive1 (open2.hash (), send4.hash (), key2.prv, key2.pub, *system.work.generate (open2.hash ())); nano::send_block send6 (receive1.hash (), key3.pub, 10, key2.prv, key2.pub, *system.work.generate (receive1.hash ())); nano::receive_block receive2 (send6.hash (), send5.hash (), key2.prv, key2.pub, *system.work.generate (send6.hash ())); add_callback_stats (*node); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send4).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send5).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send6).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive2).code); // Check confirmation heights of all the accounts are uninitialized (0), // as we have any just added them to the ledger and not processed any live transactions yet. nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (1, confirmation_height_info.height); ASSERT_EQ (nano::genesis ().hash (), confirmation_height_info.frontier); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key1.pub, confirmation_height_info)); ASSERT_EQ (0, confirmation_height_info.height); ASSERT_EQ (nano::block_hash (0), confirmation_height_info.frontier); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key2.pub, confirmation_height_info)); ASSERT_EQ (0, confirmation_height_info.height); ASSERT_EQ (nano::block_hash (0), confirmation_height_info.frontier); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key3.pub, confirmation_height_info)); ASSERT_EQ (0, confirmation_height_info.height); ASSERT_EQ (nano::block_hash (0), confirmation_height_info.frontier); } // The nodes process a live receive which propagates across to all accounts auto receive3 = std::make_shared (open3.hash (), send6.hash (), key3.prv, key3.pub, *system.work.generate (open3.hash ())); node->process_active (receive3); node->block_processor.flush (); system.deadline_set (10s); while (true) { auto transaction = node->store.tx_begin_read (); if (node->ledger.block_confirmed (transaction, receive3->hash ())) { break; } ASSERT_NO_ERROR (system.poll ()); } nano::account_info account_info; nano::confirmation_height_info confirmation_height_info; auto & store = node->store; auto transaction = node->store.tx_begin_read (); ASSERT_FALSE (store.account_get (transaction, nano::test_genesis_key.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (4, confirmation_height_info.height); ASSERT_EQ (send3.hash (), confirmation_height_info.frontier); ASSERT_EQ (4, account_info.block_count); ASSERT_FALSE (store.account_get (transaction, key1.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key1.pub, confirmation_height_info)); ASSERT_EQ (2, confirmation_height_info.height); ASSERT_EQ (send4.hash (), confirmation_height_info.frontier); ASSERT_EQ (3, account_info.block_count); ASSERT_FALSE (store.account_get (transaction, key2.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key2.pub, confirmation_height_info)); ASSERT_EQ (3, confirmation_height_info.height); ASSERT_EQ (send6.hash (), confirmation_height_info.frontier); ASSERT_EQ (4, account_info.block_count); ASSERT_FALSE (store.account_get (transaction, key3.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key3.pub, confirmation_height_info)); ASSERT_EQ (2, confirmation_height_info.height); ASSERT_EQ (receive3->hash (), confirmation_height_info.frontier); ASSERT_EQ (2, account_info.block_count); // The accounts for key1 and key2 have 1 more block in the chain than is confirmed. // So this can be rolled back, but the one before that cannot. Check that this is the case { auto transaction = node->store.tx_begin_write (); ASSERT_FALSE (node->ledger.rollback (transaction, node->latest (key2.pub))); ASSERT_FALSE (node->ledger.rollback (transaction, node->latest (key1.pub))); } { // These rollbacks should fail auto transaction = node->store.tx_begin_write (); ASSERT_TRUE (node->ledger.rollback (transaction, node->latest (key1.pub))); ASSERT_TRUE (node->ledger.rollback (transaction, node->latest (key2.pub))); // Confirm the other latest can't be rolled back either ASSERT_TRUE (node->ledger.rollback (transaction, node->latest (key3.pub))); ASSERT_TRUE (node->ledger.rollback (transaction, node->latest (nano::test_genesis_key.pub))); // Attempt some others which have been cemented ASSERT_TRUE (node->ledger.rollback (transaction, open1.hash ())); ASSERT_TRUE (node->ledger.rollback (transaction, send2.hash ())); } ASSERT_EQ (10, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (10, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); } TEST (confirmation_height, gap_bootstrap) { nano::system system (1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair destination; auto send1 (std::make_shared (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto send2 (std::make_shared (nano::genesis_account, send1->hash (), nano::genesis_account, nano::genesis_amount - 2 * nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send2); auto send3 (std::make_shared (nano::genesis_account, send2->hash (), nano::genesis_account, nano::genesis_amount - 3 * nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send3); auto open1 (std::make_shared (send1->hash (), destination.pub, destination.pub, destination.prv, destination.pub, 0)); node1.work_generate_blocking (*open1); // Receive auto receive1 (std::make_shared (open1->hash (), send2->hash (), destination.prv, destination.pub, 0)); node1.work_generate_blocking (*receive1); auto receive2 (std::make_shared (receive1->hash (), send3->hash (), destination.prv, destination.pub, 0)); node1.work_generate_blocking (*receive2); node1.block_processor.add (send1); node1.block_processor.add (send2); node1.block_processor.add (send3); node1.block_processor.add (receive1); node1.block_processor.flush (); add_callback_stats (node1); // Receive 2 comes in on the live network, however the chain has not been finished so it gets added to unchecked node1.process_active (receive2); node1.block_processor.flush (); // Confirmation heights should not be updated { auto transaction (node1.store.tx_begin_read ()); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 2); nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node1.store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (1, confirmation_height_info.height); ASSERT_EQ (genesis.hash (), confirmation_height_info.frontier); } // Now complete the chain where the block comes in on the bootstrap network. node1.block_processor.add (open1); node1.block_processor.flush (); // Confirmation height should be unchanged and unchecked should now be 0 { auto transaction (node1.store.tx_begin_read ()); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 0); nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node1.store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (1, confirmation_height_info.height); ASSERT_EQ (genesis.hash (), confirmation_height_info.frontier); ASSERT_FALSE (node1.store.confirmation_height_get (transaction, destination.pub, confirmation_height_info)); ASSERT_EQ (0, confirmation_height_info.height); ASSERT_EQ (nano::block_hash (0), confirmation_height_info.frontier); } ASSERT_EQ (0, node1.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (0, node1.stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); } TEST (confirmation_height, gap_live) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node1 = system.add_node (node_config); node_config.peering_port = nano::get_available_port (); system.add_node (node_config); nano::keypair destination; system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); system.wallet (1)->insert_adhoc (destination.prv); nano::genesis genesis; auto send1 (std::make_shared (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1->work_generate_blocking (*send1); auto send2 (std::make_shared (nano::genesis_account, send1->hash (), nano::genesis_account, nano::genesis_amount - 2 * nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1->work_generate_blocking (*send2); auto send3 (std::make_shared (nano::genesis_account, send2->hash (), nano::genesis_account, nano::genesis_amount - 3 * nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1->work_generate_blocking (*send3); auto open1 (std::make_shared (send1->hash (), destination.pub, destination.pub, destination.prv, destination.pub, 0)); node1->work_generate_blocking (*open1); auto receive1 (std::make_shared (open1->hash (), send2->hash (), destination.prv, destination.pub, 0)); node1->work_generate_blocking (*receive1); auto receive2 (std::make_shared (receive1->hash (), send3->hash (), destination.prv, destination.pub, 0)); node1->work_generate_blocking (*receive2); for (auto & node : system.nodes) { node->block_processor.add (send1); node->block_processor.add (send2); node->block_processor.add (send3); node->block_processor.add (receive1); node->block_processor.flush (); add_callback_stats (*node); // Receive 2 comes in on the live network, however the chain has not been finished so it gets added to unchecked node->process_active (receive2); node->block_processor.flush (); // Confirmation heights should not be updated { auto transaction = node->store.tx_begin_read (); nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (1, confirmation_height_info.height); ASSERT_EQ (nano::genesis ().hash (), confirmation_height_info.frontier); } // Now complete the chain where the block comes in on the live network node->process_active (open1); node->block_processor.flush (); system.deadline_set (10s); while (true) { auto transaction = node->store.tx_begin_read (); if (node->ledger.block_confirmed (transaction, receive2->hash ())) { break; } ASSERT_NO_ERROR (system.poll ()); } // This should confirm the open block and the source of the receive blocks auto transaction (node->store.tx_begin_read ()); auto unchecked_count (node->store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 0); nano::confirmation_height_info confirmation_height_info; ASSERT_TRUE (node->ledger.block_confirmed (transaction, receive2->hash ())); ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (4, confirmation_height_info.height); ASSERT_EQ (send3->hash (), confirmation_height_info.frontier); ASSERT_FALSE (node->store.confirmation_height_get (transaction, destination.pub, confirmation_height_info)); ASSERT_EQ (3, confirmation_height_info.height); ASSERT_EQ (receive2->hash (), confirmation_height_info.frontier); ASSERT_EQ (6, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (6, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); } } TEST (confirmation_height, send_receive_between_2_accounts) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); nano::keypair key1; system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest (node->latest (nano::test_genesis_key.pub)); system.wallet (0)->insert_adhoc (key1.prv); nano::send_block send1 (latest, key1.pub, node->config.online_weight_minimum.number () + 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest)); nano::open_block open1 (send1.hash (), nano::genesis_account, key1.pub, key1.prv, key1.pub, *system.work.generate (key1.pub)); nano::send_block send2 (open1.hash (), nano::genesis_account, 1000, key1.prv, key1.pub, *system.work.generate (open1.hash ())); nano::send_block send3 (send2.hash (), nano::genesis_account, 900, key1.prv, key1.pub, *system.work.generate (send2.hash ())); nano::send_block send4 (send3.hash (), nano::genesis_account, 500, key1.prv, key1.pub, *system.work.generate (send3.hash ())); nano::receive_block receive1 (send1.hash (), send2.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send1.hash ())); nano::receive_block receive2 (receive1.hash (), send3.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (receive1.hash ())); nano::receive_block receive3 (receive2.hash (), send4.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (receive2.hash ())); nano::send_block send5 (receive3.hash (), key1.pub, node->config.online_weight_minimum.number () + 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (receive3.hash ())); auto receive4 = std::make_shared (send4.hash (), send5.hash (), key1.prv, key1.pub, *system.work.generate (send4.hash ())); // Unpocketed send nano::keypair key2; nano::send_block send6 (send5.hash (), key2.pub, node->config.online_weight_minimum.number (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send5.hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send4).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send5).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send6).code); } add_callback_stats (*node); node->process_active (receive4); node->block_processor.flush (); system.deadline_set (10s); while (true) { auto transaction = node->store.tx_begin_read (); if (node->ledger.block_confirmed (transaction, receive4->hash ())) { break; } ASSERT_NO_ERROR (system.poll ()); } auto transaction (node->store.tx_begin_read ()); nano::account_info account_info; nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node->store.account_get (transaction, nano::test_genesis_key.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (6, confirmation_height_info.height); ASSERT_EQ (send5.hash (), confirmation_height_info.frontier); ASSERT_EQ (7, account_info.block_count); ASSERT_FALSE (node->store.account_get (transaction, key1.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key1.pub, confirmation_height_info)); ASSERT_EQ (5, confirmation_height_info.height); ASSERT_EQ (receive4->hash (), confirmation_height_info.frontier); ASSERT_EQ (5, account_info.block_count); ASSERT_EQ (10, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (10, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); ASSERT_EQ (11, node->ledger.cache.cemented_count); } TEST (confirmation_height, send_receive_self) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest (node->latest (nano::test_genesis_key.pub)); nano::send_block send1 (latest, nano::test_genesis_key.pub, nano::genesis_amount - 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest)); nano::receive_block receive1 (send1.hash (), send1.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send1.hash ())); nano::send_block send2 (receive1.hash (), nano::test_genesis_key.pub, nano::genesis_amount - 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (receive1.hash ())); nano::send_block send3 (send2.hash (), nano::test_genesis_key.pub, nano::genesis_amount - 3, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send2.hash ())); nano::receive_block receive2 (send3.hash (), send2.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send3.hash ())); auto receive3 = std::make_shared (receive2.hash (), send3.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (receive2.hash ())); // Send to another account to prevent automatic receiving on the genesis account nano::keypair key1; nano::send_block send4 (receive3->hash (), key1.pub, node->config.online_weight_minimum.number (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (receive3->hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *receive3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send4).code); } add_callback_stats (*node); node->block_confirm (receive3); system.deadline_set (10s); while (true) { auto transaction = node->store.tx_begin_read (); if (node->ledger.block_confirmed (transaction, receive3->hash ())) { break; } ASSERT_NO_ERROR (system.poll ()); } auto transaction (node->store.tx_begin_read ()); nano::account_info account_info; ASSERT_FALSE (node->store.account_get (transaction, nano::test_genesis_key.pub, account_info)); nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (7, confirmation_height_info.height); ASSERT_EQ (receive3->hash (), confirmation_height_info.frontier); ASSERT_EQ (8, account_info.block_count); ASSERT_EQ (6, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (6, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); ASSERT_EQ (confirmation_height_info.height, node->ledger.cache.cemented_count); } TEST (confirmation_height, all_block_types) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest (node->latest (nano::test_genesis_key.pub)); nano::keypair key1; nano::keypair key2; auto & store = node->store; nano::send_block send (latest, key1.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest)); nano::send_block send1 (send.hash (), key2.pub, nano::genesis_amount - nano::Gxrb_ratio * 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send.hash ())); nano::open_block open (send.hash (), nano::test_genesis_key.pub, key1.pub, key1.prv, key1.pub, *system.work.generate (key1.pub)); nano::state_block state_open (key2.pub, 0, 0, nano::Gxrb_ratio, send1.hash (), key2.prv, key2.pub, *system.work.generate (key2.pub)); nano::send_block send2 (open.hash (), key2.pub, 0, key1.prv, key1.pub, *system.work.generate (open.hash ())); nano::state_block state_receive (key2.pub, state_open.hash (), 0, nano::Gxrb_ratio * 2, send2.hash (), key2.prv, key2.pub, *system.work.generate (state_open.hash ())); nano::state_block state_send (key2.pub, state_receive.hash (), 0, nano::Gxrb_ratio, key1.pub, key2.prv, key2.pub, *system.work.generate (state_receive.hash ())); nano::receive_block receive (send2.hash (), state_send.hash (), key1.prv, key1.pub, *system.work.generate (send2.hash ())); nano::change_block change (receive.hash (), key2.pub, key1.prv, key1.pub, *system.work.generate (receive.hash ())); nano::state_block state_change (key2.pub, state_send.hash (), nano::test_genesis_key.pub, nano::Gxrb_ratio, 0, key2.prv, key2.pub, *system.work.generate (state_send.hash ())); nano::state_block epoch (key2.pub, state_change.hash (), nano::test_genesis_key.pub, nano::Gxrb_ratio, node->ledger.epoch_link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (state_change.hash ())); nano::state_block epoch1 (key1.pub, change.hash (), key2.pub, nano::Gxrb_ratio, node->ledger.epoch_link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (change.hash ())); nano::state_block state_send1 (key1.pub, epoch1.hash (), 0, nano::Gxrb_ratio - 1, key2.pub, key1.prv, key1.pub, *system.work.generate (epoch1.hash ())); nano::state_block state_receive2 (key2.pub, epoch.hash (), 0, nano::Gxrb_ratio + 1, state_send1.hash (), key2.prv, key2.pub, *system.work.generate (epoch.hash ())); auto state_send2 = std::make_shared (key2.pub, state_receive2.hash (), 0, nano::Gxrb_ratio, key1.pub, key2.prv, key2.pub, *system.work.generate (state_receive2.hash ())); nano::state_block state_send3 (key2.pub, state_send2->hash (), 0, nano::Gxrb_ratio - 1, key1.pub, key2.prv, key2.pub, *system.work.generate (state_send2->hash ())); nano::state_block state_send4 (key1.pub, state_send1.hash (), 0, nano::Gxrb_ratio - 2, nano::test_genesis_key.pub, key1.prv, key1.pub, *system.work.generate (state_send1.hash ())); nano::state_block state_receive3 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio * 2 + 1, state_send4.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send1.hash ())); { auto transaction (store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_open).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_receive).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_send).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, change).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_change).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, epoch).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, epoch1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_receive2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *state_send2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_send3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_send4).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, state_receive3).code); } add_callback_stats (*node); node->block_confirm (state_send2); system.deadline_set (10s); while (true) { auto transaction = node->store.tx_begin_read (); if (node->ledger.block_confirmed (transaction, state_send2->hash ())) { break; } ASSERT_NO_ERROR (system.poll ()); } auto transaction (node->store.tx_begin_read ()); nano::account_info account_info; nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node->store.account_get (transaction, nano::test_genesis_key.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::test_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (3, confirmation_height_info.height); ASSERT_EQ (send1.hash (), confirmation_height_info.frontier); ASSERT_LE (4, account_info.block_count); ASSERT_FALSE (node->store.account_get (transaction, key1.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key1.pub, confirmation_height_info)); ASSERT_EQ (state_send1.hash (), confirmation_height_info.frontier); ASSERT_EQ (6, confirmation_height_info.height); ASSERT_LE (7, account_info.block_count); ASSERT_FALSE (node->store.account_get (transaction, key2.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key2.pub, confirmation_height_info)); ASSERT_EQ (7, confirmation_height_info.height); ASSERT_EQ (state_send2->hash (), confirmation_height_info.frontier); ASSERT_LE (8, account_info.block_count); ASSERT_EQ (15, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (15, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); ASSERT_EQ (16, node->ledger.cache.cemented_count); } /* Bulk of the this test was taken from the node.fork_flip test */ TEST (confirmation_height, conflict_rollback_cemented) { boost::iostreams::stream_buffer sb; sb.open (nano::stringstream_mt_sink{}); nano::boost_log_cerr_redirect redirect_cerr (&sb); nano::system system (2); auto node1 (system.nodes[0]); auto node2 (system.nodes[1]); ASSERT_EQ (1, node1->network.size ()); nano::keypair key1; nano::genesis genesis; auto send1 (std::make_shared (genesis.hash (), key1.pub, nano::genesis_amount - 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (genesis.hash ()))); nano::publish publish1 (send1); nano::keypair key2; auto send2 (std::make_shared (genesis.hash (), key2.pub, nano::genesis_amount - 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (genesis.hash ()))); nano::publish publish2 (send2); auto channel1 (node1->network.udp_channels.create (node1->network.endpoint ())); node1->network.process_message (publish1, channel1); node1->block_processor.flush (); auto channel2 (node2->network.udp_channels.create (node1->network.endpoint ())); node2->network.process_message (publish2, channel2); node2->block_processor.flush (); ASSERT_EQ (1, node1->active.size ()); ASSERT_EQ (1, node2->active.size ()); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); node1->network.process_message (publish2, channel1); node1->block_processor.flush (); node2->network.process_message (publish1, channel2); node2->block_processor.flush (); nano::unique_lock lock (node2->active.mutex); auto conflict (node2->active.roots.find (nano::qualified_root (genesis.hash (), genesis.hash ()))); ASSERT_NE (node2->active.roots.end (), conflict); auto votes1 (conflict->election); ASSERT_NE (nullptr, votes1); ASSERT_EQ (1, votes1->last_votes.size ()); lock.unlock (); // Force blocks to be cemented on both nodes { auto transaction (node1->store.tx_begin_write ()); ASSERT_TRUE (node1->store.block_exists (transaction, publish1.block->hash ())); node1->store.confirmation_height_put (transaction, nano::genesis_account, nano::confirmation_height_info{ 2, send2->hash () }); } { auto transaction (node2->store.tx_begin_write ()); ASSERT_TRUE (node2->store.block_exists (transaction, publish2.block->hash ())); node2->store.confirmation_height_put (transaction, nano::genesis_account, nano::confirmation_height_info{ 2, send2->hash () }); } auto rollback_log_entry = boost::str (boost::format (""Failed to roll back %1%"") % send2->hash ().to_string ()); system.deadline_set (20s); auto done (false); while (!done) { ASSERT_NO_ERROR (system.poll ()); done = (sb.component ()->str ().find (rollback_log_entry) != std::string::npos); } auto transaction1 (node1->store.tx_begin_read ()); auto transaction2 (node2->store.tx_begin_read ()); lock.lock (); auto winner (*votes1->tally ().begin ()); ASSERT_EQ (*publish1.block, *winner.second); ASSERT_EQ (nano::genesis_amount - 100, winner.first); ASSERT_TRUE (node1->store.block_exists (transaction1, publish1.block->hash ())); ASSERT_TRUE (node2->store.block_exists (transaction2, publish2.block->hash ())); ASSERT_FALSE (node2->store.block_exists (transaction2, publish1.block->hash ())); } TEST (confirmation_height, observers) { auto amount (std::numeric_limits::max ()); nano::system system (1); auto node1 (system.nodes[0]); nano::keypair key1; system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest1 (node1->latest (nano::test_genesis_key.pub)); auto send1 (std::make_shared (latest1, key1.pub, amount - node1->config.receive_minimum.number (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest1))); add_callback_stats (*node1); node1->process_active (send1); node1->block_processor.flush (); bool confirmed (false); system.deadline_set (10s); while (!confirmed) { auto transaction = node1->store.tx_begin_read (); confirmed = node1->ledger.block_confirmed (transaction, send1->hash ()); ASSERT_NO_ERROR (system.poll ()); } ASSERT_EQ (1, node1->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (1, node1->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); } // This tests when a read has been done and the block no longer exists by the time a write is done TEST (confirmation_height, modified_chain) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest (node->latest (nano::test_genesis_key.pub)); nano::keypair key1; auto & store = node->store; auto send = std::make_shared (latest, key1.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest)); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send).code); } node->confirmation_height_processor.add (send->hash ()); { // The write guard prevents the confirmation height processor doing any writes auto write_guard = node->write_database_queue.wait (nano::writer::testing); while (!node->write_database_queue.contains (nano::writer::confirmation_height)) ; store.block_del (store.tx_begin_write (), send->hash (), send->type ()); } while (node->write_database_queue.contains (nano::writer::confirmation_height)) ; ASSERT_EQ (1, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::invalid_block, nano::stat::dir::in)); } namespace nano { TEST (confirmation_height, pending_observer_callbacks) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest (node->latest (nano::test_genesis_key.pub)); nano::keypair key1; nano::send_block send (latest, key1.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest)); auto send1 = std::make_shared (send.hash (), key1.pub, nano::genesis_amount - nano::Gxrb_ratio * 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send.hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send1).code); } add_callback_stats (*node); node->confirmation_height_processor.add (send1->hash ()); while (true) { if (node->pending_confirmation_height.size () == 0) { break; } } node->confirmation_height_processor.add (send.hash ()); system.deadline_set (5s); while (node->ledger.cache.cemented_count < 3) { ASSERT_NO_ERROR (system.poll ()); } // Confirm the callback is not called under this circumstance ASSERT_EQ (2, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (0, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); } TEST (confirmation_height, prioritize_frontiers) { nano::system system; // Prevent frontiers being confirmed as it will affect the priorization checking nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); nano::keypair key1; nano::keypair key2; nano::keypair key3; nano::keypair key4; nano::block_hash latest1 (node->latest (nano::test_genesis_key.pub)); // Send different numbers of blocks all accounts nano::send_block send1 (latest1, key1.pub, node->config.online_weight_minimum.number () + 10000, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest1)); nano::send_block send2 (send1.hash (), key1.pub, node->config.online_weight_minimum.number () + 8500, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send1.hash ())); nano::send_block send3 (send2.hash (), key1.pub, node->config.online_weight_minimum.number () + 8000, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send2.hash ())); nano::send_block send4 (send3.hash (), key2.pub, node->config.online_weight_minimum.number () + 7500, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send3.hash ())); nano::send_block send5 (send4.hash (), key3.pub, node->config.online_weight_minimum.number () + 6500, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send4.hash ())); nano::send_block send6 (send5.hash (), key4.pub, node->config.online_weight_minimum.number () + 6000, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send5.hash ())); // Open all accounts and add other sends to get different uncemented counts (as well as some which are the same) nano::open_block open1 (send1.hash (), nano::genesis_account, key1.pub, key1.prv, key1.pub, *system.work.generate (key1.pub)); nano::send_block send7 (open1.hash (), nano::test_genesis_key.pub, 500, key1.prv, key1.pub, *system.work.generate (open1.hash ())); nano::open_block open2 (send4.hash (), nano::genesis_account, key2.pub, key2.prv, key2.pub, *system.work.generate (key2.pub)); nano::open_block open3 (send5.hash (), nano::genesis_account, key3.pub, key3.prv, key3.pub, *system.work.generate (key3.pub)); nano::send_block send8 (open3.hash (), nano::test_genesis_key.pub, 500, key3.prv, key3.pub, *system.work.generate (open3.hash ())); nano::send_block send9 (send8.hash (), nano::test_genesis_key.pub, 200, key3.prv, key3.pub, *system.work.generate (send8.hash ())); nano::open_block open4 (send6.hash (), nano::genesis_account, key4.pub, key4.prv, key4.pub, *system.work.generate (key4.pub)); nano::send_block send10 (open4.hash (), nano::test_genesis_key.pub, 500, key4.prv, key4.pub, *system.work.generate (open4.hash ())); nano::send_block send11 (send10.hash (), nano::test_genesis_key.pub, 200, key4.prv, key4.pub, *system.work.generate (send10.hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send4).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send5).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send6).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send7).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open2).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open3).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send8).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send9).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open4).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send10).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send11).code); } auto transaction = node->store.tx_begin_read (); constexpr auto num_accounts = 5; auto priority_orders_match = [](auto const & cementable_frontiers, auto const & desired_order) { return std::equal (desired_order.begin (), desired_order.end (), cementable_frontiers.template get<1> ().begin (), cementable_frontiers.template get<1> ().end (), [](nano::account const & account, nano::cementable_account const & cementable_account) { return (account == cementable_account.account); }); }; { node->active.prioritize_frontiers_for_confirmation (transaction, std::chrono::seconds (1), std::chrono::seconds (1)); ASSERT_EQ (node->active.priority_cementable_frontiers_size (), num_accounts); // Check the order of accounts is as expected (greatest number of uncemented blocks at the front). key3 and key4 have the same value, the order is unspecified so check both std::array desired_order_1{ nano::genesis_account, key3.pub, key4.pub, key1.pub, key2.pub }; std::array desired_order_2{ nano::genesis_account, key4.pub, key3.pub, key1.pub, key2.pub }; ASSERT_TRUE (priority_orders_match (node->active.priority_cementable_frontiers, desired_order_1) || priority_orders_match (node->active.priority_cementable_frontiers, desired_order_2)); } { // Add some to the local node wallets and check ordering of both containers system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); system.wallet (0)->insert_adhoc (key1.prv); system.wallet (0)->insert_adhoc (key2.prv); node->active.prioritize_frontiers_for_confirmation (transaction, std::chrono::seconds (1), std::chrono::seconds (1)); ASSERT_EQ (node->active.priority_cementable_frontiers_size (), num_accounts - 3); ASSERT_EQ (node->active.priority_wallet_cementable_frontiers_size (), num_accounts - 2); std::array local_desired_order{ nano::genesis_account, key1.pub, key2.pub }; ASSERT_TRUE (priority_orders_match (node->active.priority_wallet_cementable_frontiers, local_desired_order)); std::array desired_order_1{ key3.pub, key4.pub }; std::array desired_order_2{ key4.pub, key3.pub }; ASSERT_TRUE (priority_orders_match (node->active.priority_cementable_frontiers, desired_order_1) || priority_orders_match (node->active.priority_cementable_frontiers, desired_order_2)); } { // Add the remainder of accounts to node wallets and check size/ordering is correct system.wallet (0)->insert_adhoc (key3.prv); system.wallet (0)->insert_adhoc (key4.prv); node->active.prioritize_frontiers_for_confirmation (transaction, std::chrono::seconds (1), std::chrono::seconds (1)); ASSERT_EQ (node->active.priority_cementable_frontiers_size (), 0); ASSERT_EQ (node->active.priority_wallet_cementable_frontiers_size (), num_accounts); std::array desired_order_1{ nano::genesis_account, key3.pub, key4.pub, key1.pub, key2.pub }; std::array desired_order_2{ nano::genesis_account, key4.pub, key3.pub, key1.pub, key2.pub }; ASSERT_TRUE (priority_orders_match (node->active.priority_wallet_cementable_frontiers, desired_order_1) || priority_orders_match (node->active.priority_wallet_cementable_frontiers, desired_order_2)); } // Check that accounts which already exist have their order modified when the uncemented count changes. nano::send_block send12 (send9.hash (), nano::test_genesis_key.pub, 100, key3.prv, key3.pub, *system.work.generate (send9.hash ())); nano::send_block send13 (send12.hash (), nano::test_genesis_key.pub, 90, key3.prv, key3.pub, *system.work.generate (send12.hash ())); nano::send_block send14 (send13.hash (), nano::test_genesis_key.pub, 80, key3.prv, key3.pub, *system.work.generate (send13.hash ())); nano::send_block send15 (send14.hash (), nano::test_genesis_key.pub, 70, key3.prv, key3.pub, *system.work.generate (send14.hash ())); nano::send_block send16 (send15.hash (), nano::test_genesis_key.pub, 60, key3.prv, key3.pub, *system.work.generate (send15.hash ())); nano::send_block send17 (send16.hash (), nano::test_genesis_key.pub, 50, key3.prv, key3.pub, *system.work.generate (send16.hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send12).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send13).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send14).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send15).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send16).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send17).code); } transaction.refresh (); node->active.prioritize_frontiers_for_confirmation (transaction, std::chrono::seconds (1), std::chrono::seconds (1)); ASSERT_TRUE (priority_orders_match (node->active.priority_wallet_cementable_frontiers, std::array{ key3.pub, nano::genesis_account, key4.pub, key1.pub, key2.pub })); node->active.search_frontiers (transaction); // Check that the active transactions roots contains the frontiers system.deadline_set (std::chrono::seconds (10)); while (node->active.size () != num_accounts) { ASSERT_NO_ERROR (system.poll ()); } std::array frontiers{ send17.qualified_root (), send6.qualified_root (), send7.qualified_root (), open2.qualified_root (), send11.qualified_root () }; for (auto & frontier : frontiers) { ASSERT_NE (node->active.roots.find (frontier), node->active.roots.end ()); } } } TEST (confirmation_height, frontiers_confirmation_mode) { nano::genesis genesis; nano::keypair key; // Always mode { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::always; auto node = system.add_node (node_config); nano::state_block send (nano::test_genesis_key.pub, genesis.hash (), nano::test_genesis_key.pub, nano::genesis_amount - nano::Gxrb_ratio, key.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *node->work_generate_blocking (genesis.hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); } system.deadline_set (5s); while (node->active.size () != 1) { ASSERT_NO_ERROR (system.poll ()); } } // Auto mode { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::automatic; auto node = system.add_node (node_config); nano::state_block send (nano::test_genesis_key.pub, genesis.hash (), nano::test_genesis_key.pub, nano::genesis_amount - nano::Gxrb_ratio, key.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *node->work_generate_blocking (genesis.hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); } system.deadline_set (5s); while (node->active.size () != 1) { ASSERT_NO_ERROR (system.poll ()); } } // Disabled mode { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); nano::state_block send (nano::test_genesis_key.pub, genesis.hash (), nano::test_genesis_key.pub, nano::genesis_amount - nano::Gxrb_ratio, key.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *node->work_generate_blocking (genesis.hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); } system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); std::this_thread::sleep_for (std::chrono::seconds (1)); ASSERT_EQ (0, node->active.size ()); } } // The callback and confirmation history should only be updated after confirmation height is set (and not just after voting) TEST (confirmation_height, callback_confirmed_history) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest (node->latest (nano::test_genesis_key.pub)); nano::keypair key1; auto send = std::make_shared (latest, key1.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest)); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send).code); } auto send1 = std::make_shared (send->hash (), key1.pub, nano::genesis_amount - nano::Gxrb_ratio * 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send->hash ())); add_callback_stats (*node); node->process_active (send1); node->block_processor.flush (); { node->process_active (send); node->block_processor.flush (); // The write guard prevents the confirmation height processor doing any writes auto write_guard = node->write_database_queue.wait (nano::writer::testing); system.deadline_set (10s); while (node->active.size () > 0) { ASSERT_NO_ERROR (system.poll ()); } ASSERT_EQ (0, node->active.list_confirmed ().size ()); { nano::lock_guard guard (node->active.mutex); ASSERT_EQ (0, node->active.blocks.size ()); } auto transaction = node->store.tx_begin_read (); ASSERT_FALSE (node->ledger.block_confirmed (transaction, send->hash ())); system.deadline_set (10s); while (!node->write_database_queue.contains (nano::writer::confirmation_height)) { ASSERT_NO_ERROR (system.poll ()); } // Confirm that no inactive callbacks have been called when the confirmation height processor has already iterated over it, waiting to write ASSERT_EQ (0, node->stats.count (nano::stat::type::observer, nano::stat::detail::observer_confirmation_inactive, nano::stat::dir::out)); } system.deadline_set (10s); while (node->write_database_queue.contains (nano::writer::confirmation_height)) { ASSERT_NO_ERROR (system.poll ()); } auto transaction = node->store.tx_begin_read (); ASSERT_TRUE (node->ledger.block_confirmed (transaction, send->hash ())); ASSERT_EQ (1, node->active.list_confirmed ().size ()); ASSERT_EQ (0, node->active.blocks.size ()); // Confirm the callback is not called under this circumstance ASSERT_EQ (2, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); ASSERT_EQ (2, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); ASSERT_EQ (1, node->stats.count (nano::stat::type::observer, nano::stat::detail::observer_confirmation_active_quorum, nano::stat::dir::out)); ASSERT_EQ (1, node->stats.count (nano::stat::type::observer, nano::stat::detail::observer_confirmation_inactive, nano::stat::dir::out)); nano::lock_guard guard (node->active.mutex); ASSERT_EQ (0, node->active.pending_conf_height.size ()); } namespace nano { TEST (confirmation_height, dependent_election) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest (node->latest (nano::test_genesis_key.pub)); nano::keypair key1; auto send = std::make_shared (latest, key1.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest)); auto send1 = std::make_shared (send->hash (), key1.pub, nano::genesis_amount - nano::Gxrb_ratio * 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send->hash ())); auto send2 = std::make_shared (send1->hash (), key1.pub, nano::genesis_amount - nano::Gxrb_ratio * 3, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send1->hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send2).code); } add_callback_stats (*node); // Prevent the confirmation height processor from doing any processing node->confirmation_height_processor.pause (); // Wait until it has been processed node->block_confirm (send2); system.deadline_set (10s); while (node->active.size () > 0) { ASSERT_NO_ERROR (system.poll ()); } system.deadline_set (10s); while (node->pending_confirmation_height.size () != 1) { ASSERT_NO_ERROR (system.poll ()); } { nano::lock_guard guard (node->pending_confirmation_height.mutex); ASSERT_EQ (*node->pending_confirmation_height.pending.begin (), send2->hash ()); } // Now put the other block in active so it can be confirmed as a dependent election node->block_confirm (send1); node->confirmation_height_processor.unpause (); system.deadline_set (10s); while (node->stats.count (nano::stat::type::observer, nano::stat::detail::observer_confirmation_active_quorum, nano::stat::dir::out) != 1 && node->stats.count (nano::stat::type::observer, nano::stat::detail::observer_confirmation_active_conf_height, nano::stat::dir::out) != 1) { ASSERT_NO_ERROR (system.poll ()); } ASSERT_EQ (3, node->stats.count (nano::stat::type::http_callback, nano::stat::detail::http_callback, nano::stat::dir::out)); ASSERT_EQ (1, node->stats.count (nano::stat::type::observer, nano::stat::detail::observer_confirmation_inactive, nano::stat::dir::out)); ASSERT_EQ (3, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in)); nano::lock_guard guard (node->active.mutex); ASSERT_EQ (0, node->active.pending_conf_height.size ()); } TEST (confirmation_height, dependent_election_after_already_cemented) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::block_hash latest (node->latest (nano::test_genesis_key.pub)); nano::keypair key1; auto send = std::make_shared (latest, key1.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (latest)); auto send1 = std::make_shared (send->hash (), key1.pub, nano::genesis_amount - nano::Gxrb_ratio * 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *system.work.generate (send->hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send1).code); } add_callback_stats (*node); { node->block_confirm (send1); auto write_guard = node->write_database_queue.wait (nano::writer::testing); system.deadline_set (10s); while (node->active.size () > 0) { ASSERT_NO_ERROR (system.poll ()); } ASSERT_EQ (0, node->active.list_confirmed ().size ()); { nano::lock_guard guard (node->active.mutex); ASSERT_EQ (0, node->active.blocks.size ()); } auto transaction = node->store.tx_begin_read (); ASSERT_FALSE (node->ledger.block_confirmed (transaction, send->hash ())); system.deadline_set (10s); while (!node->write_database_queue.contains (nano::writer::confirmation_height)) { ASSERT_NO_ERROR (system.poll ()); } node->block_confirm (send); system.deadline_set (10s); while (node->active.size () > 0) { ASSERT_NO_ERROR (system.poll ()); } } system.deadline_set (10s); while (node->pending_confirmation_height.size () != 0) { ASSERT_NO_ERROR (system.poll ()); } system.deadline_set (10s); nano::unique_lock lk (node->active.mutex); while (node->active.pending_conf_height.size () > 0) { lk.unlock (); ASSERT_NO_ERROR (system.poll ()); lk.lock (); } } } ",16334,True,3753.8836125036746,median "*&---------------------------------------------------------------------* *& Include ZCL_DOCX_CLASS *& *& Author: Sikidin A.P. anton.sikidin@gmail.com *& *& ZCL_DOCX is replasement of zwww_openform for docx *& *&---------------------------------------------------------------------* CLASS lcl_recursive_data DEFINITION DEFERRED. TYPES : BEGIN OF t_key_value , key TYPE string , value TYPE string , END OF t_key_value , tt_key_value TYPE TABLE OF t_key_value , BEGIN OF t_key_table , key TYPE string , value TYPE REF TO data , END OF t_key_table , tt_key_table TYPE TABLE OF t_key_table , t_lcl TYPE REF TO lcl_recursive_data , tt_lcl TYPE TABLE OF t_lcl , tt_keys TYPE TABLE OF string . *----------------------------------------------------------------------* * CLASS lcl_recursive_data DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_recursive_data DEFINITION. PUBLIC SECTION. DATA : key_value TYPE tt_key_value , key_table TYPE tt_key_table , key TYPE string , keys TYPE tt_keys , key_lcl TYPE tt_lcl . METHODS append_key_value IMPORTING value(iv_key) TYPE string !iv_value TYPE any . METHODS append_key_table IMPORTING value(iv_key) TYPE string !iv_table TYPE ANY TABLE. METHODS create_document IMPORTING value(iv_key) TYPE string RETURNING value(r_data) TYPE REF TO lcl_recursive_data . ENDCLASS. ""lcl_recursive_data DEFINITION *----------------------------------------------------------------------* * CLASS lcl_recursive_data IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_recursive_data IMPLEMENTATION. METHOD append_key_value. FIELD-SYMBOLS : TYPE t_key_value . TRANSLATE iv_key TO UPPER CASE. APPEND INITIAL LINE TO key_value ASSIGNING . DATA : lv_str TYPE string . CONCATENATE '{' iv_key '}' INTO lv_str. -key = lv_str . -value = iv_value. ENDMETHOD. ""append_key_value METHOD append_key_table. TRANSLATE iv_key TO UPPER CASE. FIELD-SYMBOLS : TYPE t_key_table , TYPE ANY TABLE . APPEND INITIAL LINE TO key_table ASSIGNING . -key = iv_key. CREATE DATA -value LIKE iv_table. ASSIGN -value->* TO . = iv_table. ENDMETHOD. ""append_key_table METHOD create_document . TRANSLATE iv_key TO UPPER CASE. CREATE OBJECT r_data. r_data->key = iv_key. COLLECT iv_key INTO keys. APPEND r_data TO key_lcl. ENDMETHOD. ""create_document ENDCLASS. ""lcl_recursive_data IMPLEMENTATION *----------------------------------------------------------------------* * CLASS lcl_docx DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_docx DEFINITION. PUBLIC SECTION. TYPES : t_ref_node TYPE REF TO if_ixml_node , tt_node TYPE STANDARD TABLE OF t_ref_node , BEGIN OF t_bookmark , id TYPE string , start_node TYPE t_ref_node , end_node TYPE t_ref_node , in_table TYPE xfeld , name TYPE string , start_height TYPE i , end_height TYPE i , END OF t_bookmark , BEGIN OF t_stack_data , start TYPE xfeld , id TYPE string , node TYPE t_ref_node , position TYPE i , length TYPE i , collision TYPE i , END OF t_stack_data , BEGIN OF t_collision , collision TYPE string , count TYPE i , END OF t_collision . METHODS load_smw0 IMPORTING !i_w3objid TYPE w3objid . METHODS add_file IMPORTING !iv_path TYPE string !iv_data TYPE xstring. METHODS get_raw IMPORTING !iv_protect TYPE xfeld DEFAULT '' RETURNING value(rv_content) TYPE xstring. METHODS save IMPORTING !on_desktop TYPE xfeld DEFAULT 'X' !iv_folder TYPE string DEFAULT 'report' !iv_path TYPE string DEFAULT '' !iv_file_name TYPE string DEFAULT 'report.docx' !no_execute TYPE xfeld DEFAULT '' !iv_protect TYPE xfeld DEFAULT '' RETURNING value(rv_path_out) TYPE string. METHODS map_data IMPORTING !ir_xml_node TYPE REF TO if_ixml_document OPTIONAL !ir_data TYPE REF TO lcl_recursive_data. METHODS check_flag IMPORTING !it_keys TYPE tt_keys. PROTECTED SECTION. CONSTANTS c_document TYPE string VALUE 'word/document.xml' ##no_text. METHODS map_values IMPORTING !ir_xml_node TYPE REF TO if_ixml_node OPTIONAL !it_key_value TYPE tt_key_value . METHODS map_table IMPORTING !ir_xml_node TYPE REF TO if_ixml_document OPTIONAL !iv_key TYPE string !it_data TYPE ANY TABLE . METHODS append_node IMPORTING !ir_source TYPE REF TO if_ixml_node OPTIONAL !ir_dest TYPE REF TO if_ixml_node OPTIONAL !iv_key TYPE string. METHODS get_fragment IMPORTING !ir_xml_node TYPE REF TO if_ixml_document OPTIONAL !iv_key TYPE string RETURNING value(rr_fragment) TYPE REF TO if_ixml_document. METHODS normalize_key. METHODS protect. METHODS get_from_zip_archive IMPORTING !i_filename TYPE string RETURNING value(r_content) TYPE xstring . METHODS get_ixml_from_zip_archive IMPORTING !i_filename TYPE string RETURNING value(r_ixml) TYPE REF TO if_ixml_document . METHODS normalize_space IMPORTING !iv_content TYPE xstring RETURNING value(r_content) TYPE xstring. PRIVATE SECTION. DATA zip TYPE REF TO cl_abap_zip . DATA document TYPE REF TO if_ixml_document . METHODS upper_case IMPORTING !iv_str TYPE string RETURNING value(rv_str) TYPE string. METHODS dump_data IMPORTING !node TYPE REF TO if_ixml_document OPTIONAL !node_node TYPE REF TO if_ixml_node OPTIONAL !fname TYPE string. METHODS create_document RETURNING value(rp_content) TYPE xstring . METHODS map_line IMPORTING !node TYPE REF TO if_ixml_document !components TYPE abap_compdescr_tab !data TYPE any . ENDCLASS. ""lcl_docx DEFINITION *----------------------------------------------------------------------* * CLASS lcl_docx IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_docx IMPLEMENTATION. METHOD load_smw0. DATA : lv_templ_xstr TYPE xstring , lt_mime TYPE TABLE OF w3mime . DATA : ls_key TYPE wwwdatatab . ls_key-relid = 'MI'. ls_key-objid = i_w3objid . CALL FUNCTION 'WWWDATA_IMPORT' EXPORTING key = ls_key TABLES mime = lt_mime EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0. RETURN. ENDIF. TRY. lv_templ_xstr = cl_bcs_convert=>solix_to_xstring( lt_mime ). CATCH cx_bcs. RETURN. ENDTRY. IF zip IS INITIAL. CREATE OBJECT zip. ENDIF. zip->load( lv_templ_xstr ). document = me->get_ixml_from_zip_archive( me->c_document ). normalize_key( ). * align_bookmark( ). ENDMETHOD. ""load_smw0 METHOD normalize_key. DATA : lt_nodes TYPE TABLE OF t_ref_node , lv_in TYPE c , lv_regex_open TYPE string VALUE '\\{[^\\}]*$' , lv_regex_close TYPE string VALUE '\\}[^\\{]*' , lv_tmp_str TYPE string . * dump_data( node = document * fname = 'before' ). DATA : iterator TYPE REF TO if_ixml_node_iterator , node TYPE REF TO if_ixml_node . iterator = document->create_iterator( ). DO. node = iterator->get_next( ). IF node IS INITIAL. EXIT. ENDIF. CHECK node->get_type( ) = if_ixml_node=>co_node_element. CHECK node->get_name( ) = 'p'. REFRESH lt_nodes. CLEAR lv_in. DATA : nodes TYPE REF TO if_ixml_node_list . nodes = node->get_children( ). DO nodes->get_length( ) TIMES. DATA : child TYPE REF TO if_ixml_node . child = nodes->get_item( sy-index - 1 ). DATA : nodes_2 TYPE REF TO if_ixml_node_list . nodes_2 = child->get_children( ). DO nodes_2->get_length( ) TIMES. DATA : child_2 TYPE REF TO if_ixml_node . child_2 = nodes_2->get_item( sy-index - 1 ). CHECK child_2->get_name( ) = 't'. DATA : child_2_value TYPE string . child_2_value = child_2->get_value( ). child_2_value = child_2->get_value( ). child_2->set_value( upper_case( child_2_value ) ). IF lv_in IS NOT INITIAL. APPEND child_2 TO lt_nodes. FIND REGEX lv_regex_close IN child_2_value. CHECK sy-subrc = 0. FIND REGEX lv_regex_open IN child_2_value. CHECK sy-subrc NE 0. CLEAR lv_tmp_str . FIELD-SYMBOLS : TYPE t_ref_node . LOOP AT lt_nodes ASSIGNING . child_2_value = ->get_value( ). CONCATENATE lv_tmp_str child_2_value INTO lv_tmp_str. ->set_value( '' ). ENDLOOP. READ TABLE lt_nodes ASSIGNING INDEX 1. ->set_value( upper_case( lv_tmp_str ) ). DATA : lo_element TYPE REF TO if_ixml_element . lo_element ?= . lo_element->set_attribute( name = 'space' namespace = 'xml' value = 'preserve' ). CLEAR lv_in. REFRESH lt_nodes. ELSE. FIND REGEX lv_regex_open IN child_2_value. CHECK sy-subrc = 0. lv_in = 'X'. APPEND child_2 TO lt_nodes. ENDIF. ENDDO. ENDDO. ENDDO. * dump_data( node = document * fname = 'after' ). ENDMETHOD. ""normalize_key METHOD protect. DATA: lv_content TYPE xstring, lo_ixml TYPE REF TO if_ixml, lo_streamfactory TYPE REF TO if_ixml_stream_factory, lo_istream TYPE REF TO if_ixml_istream, lo_parser TYPE REF TO if_ixml_parser, lr_element TYPE REF TO if_ixml_element . DATA : lr_settings TYPE REF TO if_ixml_document . *--------------------------------------------------------------------* * Load XML file from archive into an input stream, * and parse that stream into an ixml object *--------------------------------------------------------------------* lv_content = me->get_from_zip_archive( 'word/settings.xml' ). lo_ixml = cl_ixml=>create( ). lo_streamfactory = lo_ixml->create_stream_factory( ). lo_istream = lo_streamfactory->create_istream_xstring( lv_content ). lr_settings = lo_ixml->create_document( ). lo_parser = lo_ixml->create_parser( stream_factory = lo_streamfactory istream = lo_istream document = lr_settings ). * lo_parser->set_normalizing( 'X' ). lo_parser->set_validating( mode = if_ixml_parser=>co_no_validation ). lo_parser->parse( ). DATA : iterator TYPE REF TO if_ixml_node_iterator , lr_node TYPE REF TO if_ixml_node . iterator = lr_settings->create_iterator( ). DO. lr_node = iterator->get_next( ). IF lr_node IS INITIAL. EXIT. ENDIF. CHECK lr_node->get_type( ) = if_ixml_node=>co_node_element. DATA : lv_node_name TYPE string . lv_node_name = lr_node->get_name( ). CHECK lv_node_name = 'settings'. * DATA(lv_xz) = lr_node->get_namespace_prefix( ). lr_element = lr_settings->create_element_ns( name = 'documentProtection' prefix = 'w' ). lr_element->set_attribute_ns( name = 'edit' prefix = 'w' value = 'readOnly' ). lr_element->set_attribute_ns( name = 'enforcement' prefix = 'w' value = '1' ). lr_element->set_attribute_ns( name = 'cryptProviderType' prefix = 'w' value = 'rsaFull' ). lr_element->set_attribute_ns( name = 'cryptAlgorithmClass' prefix = 'w' value = 'hash' ). lr_element->set_attribute_ns( name = 'cryptAlgorithmType' prefix = 'w' value = 'typeAny' ). lr_element->set_attribute_ns( name = 'cryptAlgorithmSid' prefix = 'w' value = '4' ). lr_element->set_attribute_ns( name = 'cryptSpinCount' prefix = 'w' value = '100000' ). lr_element->set_attribute_ns( name = 'hash' prefix = 'w' value = 'zApjmCLBrWyDDRNiRAmxszP+gYc=' ). lr_element->set_attribute_ns( name = 'salt' prefix = 'w' value = 'erqLP912rJurhcV4a1bb8A==' ). lr_node->append_child( lr_element ) . EXIT. ENDDO. DATA : lo_ostream TYPE REF TO if_ixml_ostream , lo_renderer TYPE REF TO if_ixml_renderer . * STEP 1: Create [Content_Types].xml into the root of the ZIP lo_ixml = cl_ixml=>create( ). CLEAR lv_content. lo_streamfactory = lo_ixml->create_stream_factory( ). lo_ostream = lo_streamfactory->create_ostream_xstring( string = lv_content ). lo_renderer = lo_ixml->create_renderer( ostream = lo_ostream document = lr_settings ). lo_renderer->render( ). zip->delete( name = 'word/settings.xml' ). zip->add( name = 'word/settings.xml' content = lv_content ). ENDMETHOD. ""protect METHOD add_file. zip->delete( name = iv_path ). zip->add( name = iv_path content = iv_data ). ENDMETHOD. ""add_file METHOD get_raw. CLEAR rv_content. rv_content = me->create_document( ). DATA : lv_string TYPE string , lt_content_source TYPE TABLE OF string , lt_content_dest TYPE TABLE OF string , lt_string TYPE TABLE OF string , lt_data TYPE TABLE OF text255 . DATA : converter TYPE REF TO cl_abap_conv_in_ce . CALL METHOD cl_abap_conv_in_ce=>create EXPORTING input = rv_content encoding = 'UTF-8' replacement = '?' ignore_cerr = abap_true RECEIVING conv = converter. TRY. CALL METHOD converter->read IMPORTING data = lv_string. CATCH cx_sy_conversion_codepage. *-- Should ignore errors in code conversions CATCH cx_sy_codepage_converter_init. *-- Should ignore errors in code conversions CATCH cx_parameter_invalid_type. CATCH cx_parameter_invalid_range. ENDTRY. SPLIT lv_string AT '[SPACE]' INTO TABLE lt_string. DATA : lv_len TYPE i , lv_buf TYPE text255 , lv_pos TYPE i , lv_rem TYPE i . lv_pos = 0. lv_rem = 255. FIELD-SYMBOLS : TYPE string . LOOP AT lt_string ASSIGNING . lv_len = strlen( ). WHILE lv_len > 0. IF lv_len > lv_rem. lv_buf+lv_pos(lv_rem) = (lv_rem). APPEND lv_buf TO lt_data. = +lv_rem. lv_pos = 0. lv_rem = 255. CLEAR lv_buf. ELSE. lv_buf+lv_pos = . lv_pos = lv_pos + lv_len. lv_rem = lv_rem - lv_len. CLEAR . ENDIF. lv_len = strlen( ). ENDWHILE. IF lv_pos < 254. lv_pos = lv_pos + 1. lv_rem = lv_rem - 1. ELSEIF lv_pos = 254. APPEND lv_buf TO lt_data. lv_pos = 0. lv_rem = 255. CLEAR lv_buf. ELSE. APPEND lv_buf TO lt_data. lv_pos = 1. lv_rem = 254. CLEAR lv_buf. ENDIF. ENDLOOP. APPEND lv_buf TO lt_data. FIELD-SYMBOLS : TYPE x . DATA : lv_x1(1) TYPE x , lv_i TYPE i , lv_i2 TYPE i , lv_str TYPE string . FIELD-SYMBOLS : TYPE text255 . LOOP AT lt_data ASSIGNING . CONCATENATE lv_str INTO lv_str RESPECTING BLANKS. ENDLOOP. DATA : lr_conv_out TYPE REF TO cl_abap_conv_out_ce , lv_echo_xstring TYPE xstring . lr_conv_out = cl_abap_conv_out_ce=>create( encoding = 'UTF-8' ). lr_conv_out->convert( EXPORTING data = lv_str IMPORTING buffer = rv_content ). zip->delete( name = me->c_document ). zip->add( name = me->c_document content = rv_content ). IF iv_protect IS NOT INITIAL . protect( ). ENDIF. rv_content = zip->save( ). ENDMETHOD. ""get_raw METHOD save. DATA : lv_content TYPE xstring. lv_content = me->get_raw( iv_protect ). DATA : lt_file_tab TYPE solix_tab , lv_bytecount TYPE i , lv_path TYPE string . lt_file_tab = cl_bcs_convert=>xstring_to_solix( iv_xstring = lv_content ). lv_bytecount = xstrlen( lv_content ). IF iv_path IS INITIAL. IF on_desktop IS NOT INITIAL. cl_gui_frontend_services=>get_desktop_directory( CHANGING desktop_directory = lv_path ). ELSE. cl_gui_frontend_services=>get_temp_directory( CHANGING temp_dir = lv_path ). ENDIF. cl_gui_cfw=>flush( ). ELSE. lv_path = iv_path. ENDIF. CONCATENATE lv_path '\\' iv_folder '\\' iv_file_name INTO lv_path. rv_path_out = lv_path. cl_gui_frontend_services=>gui_download( EXPORTING bin_filesize = lv_bytecount filename = lv_path filetype = 'BIN' CHANGING data_tab = lt_file_tab EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 not_supported_by_gui = 22 error_no_gui = 23 OTHERS = 24 ). CHECK no_execute IS INITIAL. cl_gui_frontend_services=>execute( document = lv_path ). ENDMETHOD. ""save METHOD map_values. CHECK it_key_value IS NOT INITIAL. DATA : iterator TYPE REF TO if_ixml_node_iterator . IF ir_xml_node IS BOUND. iterator = ir_xml_node->create_iterator( ). ELSE. iterator = document->create_iterator( ). ENDIF. DO. DATA : node TYPE REF TO if_ixml_node . node = iterator->get_next( ). IF node IS INITIAL. EXIT. ENDIF. CHECK node->get_type( ) = if_ixml_node=>co_node_element. CHECK node->get_name( ) = 't'. DATA : value TYPE string . value = node->get_value( ). FIELD-SYMBOLS : TYPE t_key_value . LOOP AT it_key_value ASSIGNING . REPLACE ALL OCCURRENCES OF -key IN value WITH -value. CHECK sy-subrc = 0. node->set_value( value ). ENDLOOP. ENDDO. ENDMETHOD. ""map_values METHOD get_fragment. DATA : lv_found TYPE c , lv_id TYPE string , lr_start TYPE REF TO if_ixml_node , lt_node TYPE tt_node , lv_first_run TYPE c , lv_start TYPE c . DATA : iterator TYPE REF TO if_ixml_node_iterator . iterator = ir_xml_node->create_iterator( ). DATA : ixmlfactory TYPE REF TO if_ixml . ixmlfactory = cl_ixml=>create( ). rr_fragment = ixmlfactory->create_document( ). DO. DATA : node TYPE REF TO if_ixml_node . node = iterator->get_next( ). IF node IS INITIAL. EXIT. ENDIF. CHECK node->get_type( ) = if_ixml_node=>co_node_element. CHECK node->get_name( ) = 'bookmarkStart'. DATA : attributes TYPE REF TO if_ixml_named_node_map . attributes = node->get_attributes( ). DO attributes->get_length( ) TIMES. DATA : attribute TYPE REF TO if_ixml_node . attribute = attributes->get_item( sy-index - 1 ). CASE attribute->get_name( ). WHEN 'id'. lv_id = attribute->get_value( ). WHEN 'name'. IF attribute->get_value( ) = iv_key . lv_found = 'X'. lv_first_run = 'X'. lr_start = node. ENDIF. ENDCASE. ENDDO. CHECK lv_first_run IS NOT INITIAL. CLEAR lv_first_run . EXIT. ENDDO. CHECK lr_start IS NOT INITIAL. DATA : parent TYPE REF TO if_ixml_node . parent = lr_start->get_parent( ). DATA : children TYPE REF TO if_ixml_node_list . children = parent->get_children( ). DO children->get_length( ) TIMES. DATA : child TYPE REF TO if_ixml_node . child = children->get_item( sy-index - 1 ). DATA : name TYPE string . name = child->get_name( ). IF name = 'bookmarkEnd' AND lv_found IS NOT INITIAL. attributes = child->get_attributes( ). DO attributes->get_length( ) TIMES. attribute = attributes->get_item( sy-index - 1 ). CHECK attribute->get_name( ) = 'id'. CHECK lv_id = attribute->get_value( ). CLEAR lv_start. ENDDO. ENDIF. IF lv_start IS NOT INITIAL. APPEND child TO lt_node. ENDIF. IF name = 'bookmarkStart' AND lv_found IS NOT INITIAL. attributes = child->get_attributes( ). DO attributes->get_length( ) TIMES. attribute = attributes->get_item( sy-index - 1 ). CHECK attribute->get_name( ) = 'id'. CHECK lv_id = attribute->get_value( ). lv_start = 'X'. ENDDO. ENDIF. ENDDO. FIELD-SYMBOLS : TYPE t_ref_node . LOOP AT lt_node ASSIGNING . DATA : clone_node TYPE t_ref_node . clone_node = ->clone( ) . name = clone_node->get_name( ). rr_fragment->append_child( clone_node ). ->remove_node( ). ENDLOOP. ENDMETHOD. ""get_fragment METHOD append_node . DATA : lv_node_name TYPE string . DATA : iterator TYPE REF TO if_ixml_node_iterator . iterator = ir_dest->create_iterator( ). DO. DATA : node TYPE REF TO if_ixml_node . node = iterator->get_next( ). IF node IS INITIAL. EXIT. ENDIF. CHECK node->get_type( ) = if_ixml_node=>co_node_element. CHECK node->get_name( ) = 'bookmarkStart'. DATA : attributes TYPE REF TO if_ixml_named_node_map . attributes = node->get_attributes( ). DO attributes->get_length( ) TIMES. DATA : attribute TYPE REF TO if_ixml_node . attribute = attributes->get_item( sy-index - 1 ). CHECK attribute->get_name( ) = 'name'. CHECK attribute->get_value( ) = iv_key . DATA : parent TYPE REF TO if_ixml_node . parent = node->get_parent( ). DATA : children TYPE REF TO if_ixml_node_list . children = ir_source->get_children( ). DATA : ch_count TYPE i . ch_count = children->get_length( ). DO ch_count TIMES. DATA : child TYPE REF TO if_ixml_node . child = children->get_item( sy-index - 1 ). DATA : clone_child TYPE REF TO if_ixml_node . clone_child = child->clone( ). parent->insert_child( new_child = clone_child ref_child = node ). ENDDO. RETURN. ENDDO. ENDDO. ENDMETHOD. ""append_node METHOD map_data . DATA : lr_node TYPE REF TO if_ixml_document , lr_document TYPE REF TO if_ixml_document , lr_clone TYPE REF TO if_ixml_document . FIELD-SYMBOLS : TYPE ANY TABLE . IF ir_xml_node IS BOUND. lr_node = ir_xml_node. ELSE. lr_node = document. ENDIF. map_values( ir_xml_node = lr_node it_key_value = ir_data->key_value ) . FIELD-SYMBOLS : TYPE t_key_table . LOOP AT ir_data->key_table ASSIGNING . ASSIGN -value->* TO . map_table( ir_xml_node = lr_node iv_key = -key it_data = ). ENDLOOP. FIELD-SYMBOLS : TYPE string . LOOP AT ir_data->keys ASSIGNING . lr_document = get_fragment( ir_xml_node = lr_node iv_key = ). FIELD-SYMBOLS : TYPE t_lcl . LOOP AT ir_data->key_lcl ASSIGNING . CHECK ->key = . CHECK ->key_value IS NOT INITIAL OR ->key_table IS NOT INITIAL OR ->keys IS NOT INITIAL. lr_clone ?= lr_document->clone( ). map_data( ir_xml_node = lr_clone ir_data = ). append_node( ir_source = lr_clone ir_dest = lr_node iv_key = ). ENDLOOP. ENDLOOP. ENDMETHOD. ""map_data METHOD check_flag. DATA : iterator TYPE REF TO if_ixml_node_iterator . iterator = document->create_iterator( ). DO. DATA : node TYPE REF TO if_ixml_node . node = iterator->get_next( ). IF node IS INITIAL. EXIT. ENDIF. IF node->get_type( ) <> if_ixml_node=>co_node_element. CONTINUE. ENDIF. DATA : name TYPE string . name = node->get_name( ). IF name = 'fldChar'. DATA : checkbox_iterator TYPE REF TO if_ixml_node_iterator . checkbox_iterator = node->create_iterator( ). DATA : lv_found TYPE c . CLEAR lv_found. DO . DATA : check_box_node TYPE REF TO if_ixml_node . check_box_node = checkbox_iterator->get_next( ). IF check_box_node IS INITIAL. EXIT. ENDIF. IF check_box_node->get_type( ) <> if_ixml_node=>co_node_element. CONTINUE. ENDIF. DATA : check_box_name TYPE string . check_box_name = check_box_node->get_name( ). IF check_box_name = 'name'. DATA : attributes TYPE REF TO if_ixml_named_node_map . attributes = check_box_node->get_attributes( ). DO attributes->get_length( ) TIMES. DATA : attribute TYPE REF TO if_ixml_node . attribute = attributes->get_item( sy-index - 1 ). IF attribute->get_name( ) = 'val'. DATA : atribute_value TYPE string . atribute_value = attribute->get_value( ) . READ TABLE it_keys TRANSPORTING NO FIELDS WITH KEY table_line = atribute_value. IF sy-subrc = 0. lv_found = 'X'. EXIT. ENDIF. ENDIF. ENDDO. ENDIF. IF lv_found IS NOT INITIAL AND check_box_name = 'default'. attributes = check_box_node->get_attributes( ). DO attributes->get_length( ) TIMES. attribute = attributes->get_item( sy-index - 1 ). IF attribute->get_name( ) = 'val'. attribute->set_value( '1' ) . EXIT. ENDIF. ENDDO. ENDIF. ENDDO. ENDIF. ENDDO. ENDMETHOD. ""check_flag METHOD map_table. DATA : lr_node TYPE REF TO if_ixml_document , lr_document TYPE REF TO if_ixml_document , lr_clone TYPE REF TO if_ixml_document , l_r_structdescr TYPE REF TO cl_abap_structdescr . IF ir_xml_node IS BOUND. lr_node = ir_xml_node. ELSE. lr_node = document. ENDIF. lr_document = get_fragment( ir_xml_node = lr_node iv_key = iv_key ). FIELD-SYMBOLS : TYPE any . LOOP AT it_data ASSIGNING . lr_clone ?= lr_document->clone( ). IF l_r_structdescr IS NOT BOUND. l_r_structdescr ?= cl_abap_structdescr=>describe_by_data( ). ENDIF. map_line( node = lr_clone components = l_r_structdescr->components data = ). append_node( ir_source = lr_clone ir_dest = lr_node iv_key = iv_key ). ENDLOOP. ENDMETHOD. ""map_table METHOD get_from_zip_archive. ASSERT zip IS BOUND. "" zip object has to exist at this point zip->get( EXPORTING name = i_filename IMPORTING content = r_content ). ENDMETHOD. ""get_from_zip_archive METHOD normalize_space. DATA : lv_string TYPE string , lt_content_source TYPE TABLE OF string , lt_content_dest TYPE TABLE OF string . DATA : converter TYPE REF TO cl_abap_conv_in_ce . CALL METHOD cl_abap_conv_in_ce=>create EXPORTING input = iv_content encoding = 'UTF-8' replacement = '?' ignore_cerr = abap_true RECEIVING conv = converter. TRY. CALL METHOD converter->read IMPORTING data = lv_string. CATCH cx_sy_conversion_codepage. *-- Should ignore errors in code conversions CATCH cx_sy_codepage_converter_init. *-- Should ignore errors in code conversions CATCH cx_parameter_invalid_type. CATCH cx_parameter_invalid_range. ENDTRY. *CALL FUNCTION 'Z_CNV_XSTRING_TO_STRING' * EXPORTING * iv_xstring = iv_content * IMPORTING * EV_STRING = lv_string * . * CALL FUNCTION 'SSFH_XSTRINGUTF8_TO_STRING' * EXPORTING * ostr_output_data = iv_content * CODEPAGE = 'UTF8' * IMPORTING * cstr_output_data = lv_string * EXCEPTIONS * conversion_error = 1 * internal_error = 2 * OTHERS = 3. * IF sy-subrc <> 0. * MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno * WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. * ENDIF. * CALL FUNCTION 'CRM_IC_XML_XSTRING2STRING' * EXPORTING * inxstring = iv_content * IMPORTING * outstring = lv_string. SPLIT lv_string AT '<' INTO TABLE lt_content_source. FIELD-SYMBOLS : TYPE string . LOOP AT lt_content_source ASSIGNING . IF IS NOT INITIAL. = '<' && . ENDIF. ENDLOOP. * DATA * : moff TYPE i * , lv_start TYPE string * , lv_end TYPE string * , lt_buf TYPE TABLE OF string * * , lv_head TYPE string * * , lv_need_append(1) * , lv_flag_in(1) * , lv_flag_first_was(1) * * , lv_flag_joined(1) * . * * LOOP AT lt_content_source ASSIGNING . * ** FIND '. ** IF sy-subrc = 0. ** ** ENDIF. * * IF = ''. * APPEND lv_start TO lt_content_dest. * * * APPEND LINES OF lt_buf TO lt_content_dest. * REFRESH lt_buf. * * APPEND TO lt_content_dest. * * CLEAR * : lv_need_append * , lv_flag_in * , lv_start * , lv_flag_first_was * . * * CONTINUE . * ENDIF. * * FIND REGEX ')' IN . * IF sy-subrc NE 0. * * IF lv_flag_in IS INITIAL and lv_start is INITIAL. * APPEND TO lt_content_dest. * ELSE. * APPEND TO lt_buf. * ENDIF. * * CONTINUE . * ENDIF. * * IF lv_flag_first_was IS INITIAL. * lv_flag_first_was = 'X'. * ELSE. * lv_flag_in = 'X'. * ENDIF. * * SPLIT AT '>' INTO lv_head lv_end. * * lv_head = lv_head && '>'. * * IF lv_flag_in IS INITIAL . * APPEND lv_head TO lt_content_dest. * ELSE. * APPEND lv_head TO lt_buf. * ENDIF. * * CLEAR * : lv_flag_joined * . * * IF lv_flag_in IS NOT INITIAL. * * IF lv_need_append IS NOT INITIAL. * lv_start = lv_start && lv_end. * lv_flag_joined = 'X'. * ELSE. * FIND REGEX '^\\s' IN lv_end. * * IF sy-subrc = 0. * lv_start = lv_start && lv_end. * lv_flag_joined = 'X'. * ENDIF. * * ENDIF. * * ENDIF. * * IF lv_flag_joined IS INITIAL. * APPEND lv_start TO lt_content_dest. * APPEND LINES OF lt_buf TO lt_content_dest. * REFRESH lt_buf. * * lv_start = lv_end. * * ENDIF. * * * FIND REGEX '\\s$' IN lv_start . * IF sy-subrc = 0. * lv_need_append = 'X'. * ELSE. * CLEAR lv_need_append. * ENDIF. * * * ENDLOOP. DATA : lv_str1 TYPE string , lv_str2 TYPE string . FIELD-SYMBOLS : TYPE string . LOOP AT lt_content_source ASSIGNING . FIND REGEX ')' IN . IF sy-subrc NE 0. APPEND TO lt_content_dest. ELSE. SPLIT AT '>' INTO lv_str1 lv_str2. lv_str1 = lv_str1 && '>'. APPEND lv_str1 TO lt_content_dest. REPLACE ALL OCCURRENCES OF REGEX '\\s' IN lv_str2 WITH '[SPACE]'. APPEND lv_str2 TO lt_content_dest. ENDIF. ENDLOOP. * lt_content_dest = lt_content_source. CLEAR lv_string. FIELD-SYMBOLS : TYPE string . LOOP AT lt_content_dest ASSIGNING . lv_string = lv_string && . ENDLOOP. CALL FUNCTION 'SSFH_STRING_TO_XSTRINGUTF8' EXPORTING cstr_input_data = lv_string * CODEPAGE = 'UTF8' IMPORTING ostr_input_data = r_content EXCEPTIONS conversion_error = 1 internal_error = 2 OTHERS = 3. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. * CALL FUNCTION 'CRM_IC_XML_STRING2XSTRING' * EXPORTING * instring = lv_string * IMPORTING * outxstring = r_content. ENDMETHOD. ""normalize_space METHOD get_ixml_from_zip_archive. DATA: lv_content TYPE xstring, lo_ixml TYPE REF TO if_ixml, lo_streamfactory TYPE REF TO if_ixml_stream_factory, lo_istream TYPE REF TO if_ixml_istream, lo_parser TYPE REF TO if_ixml_parser. *--------------------------------------------------------------------* * Load XML file from archive into an input stream, * and parse that stream into an ixml object *--------------------------------------------------------------------* lv_content = me->get_from_zip_archive( i_filename ). lv_content = normalize_space( lv_content ). lo_ixml = cl_ixml=>create( ). lo_streamfactory = lo_ixml->create_stream_factory( ). lo_istream = lo_streamfactory->create_istream_xstring( lv_content ). r_ixml = lo_ixml->create_document( ). lo_parser = lo_ixml->create_parser( stream_factory = lo_streamfactory istream = lo_istream document = r_ixml ). * lo_parser->set_normalizing( 'X' ). lo_parser->set_validating( mode = if_ixml_parser=>co_no_validation ). lo_parser->parse( ). ENDMETHOD. ""get_ixml_from_zip_archive METHOD upper_case. DATA : result_tab TYPE match_result_tab , lv_search TYPE string , lv_replace TYPE string . rv_str = iv_str. * replace all occurrences of regex '^\\{' in rv_str with ' {' . * find regex '\\}$' in rv_str. * if sy-subrc = 0. * concatenate rv_str space into rv_str respecting blanks. * endif. FIND ALL OCCURRENCES OF REGEX '\\{[^\\}]*\\}' IN iv_str RESULTS result_tab. FIELD-SYMBOLS: TYPE match_result . LOOP AT result_tab ASSIGNING . lv_search = iv_str+-offset(-length). lv_replace = lv_search. TRANSLATE lv_replace TO UPPER CASE. REPLACE ALL OCCURRENCES OF lv_search IN rv_str WITH lv_replace. ENDLOOP. ENDMETHOD. ""upper_case METHOD dump_data . DATA : lo_ixml TYPE REF TO if_ixml , lo_streamfactory TYPE REF TO if_ixml_stream_factory , lo_ostream TYPE REF TO if_ixml_ostream , lo_renderer TYPE REF TO if_ixml_renderer , lv_xstring TYPE xstring . * STEP 1: Create [Content_Types].xml into the root of the ZIP lo_ixml = cl_ixml=>create( ). lo_streamfactory = lo_ixml->create_stream_factory( ). lo_ostream = lo_streamfactory->create_ostream_xstring( string = lv_xstring ). IF node_node IS SUPPLIED. DATA : document TYPE REF TO if_ixml_document . document = lo_ixml->create_document( ). document->append_child( node_node ). lo_renderer = lo_ixml->create_renderer( ostream = lo_ostream document = document ). ELSE. lo_renderer = lo_ixml->create_renderer( ostream = lo_ostream document = node ). ENDIF. lo_renderer->render( ). DATA : lt_file_tab TYPE solix_tab , lv_bytecount TYPE i , lv_path TYPE string . lt_file_tab = cl_bcs_convert=>xstring_to_solix( iv_xstring = lv_xstring ). lv_bytecount = xstrlen( lv_xstring ). cl_gui_frontend_services=>get_desktop_directory( CHANGING desktop_directory = lv_path ). cl_gui_cfw=>flush( ). CONCATENATE lv_path '\\report\\' fname '.txt' INTO lv_path. cl_gui_frontend_services=>gui_download( EXPORTING bin_filesize = lv_bytecount filename = lv_path filetype = 'BIN' CHANGING data_tab = lt_file_tab EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 not_supported_by_gui = 22 error_no_gui = 23 OTHERS = 24 ). ENDMETHOD. ""dump_data METHOD create_document. DATA : lo_ixml TYPE REF TO if_ixml , lo_streamfactory TYPE REF TO if_ixml_stream_factory , lo_ostream TYPE REF TO if_ixml_ostream , lo_renderer TYPE REF TO if_ixml_renderer . * STEP 1: Create [Content_Types].xml into the root of the ZIP lo_ixml = cl_ixml=>create( ). lo_streamfactory = lo_ixml->create_stream_factory( ). lo_ostream = lo_streamfactory->create_ostream_xstring( string = rp_content ). lo_renderer = lo_ixml->create_renderer( ostream = lo_ostream document = me->document ). lo_renderer->render( ). ENDMETHOD. ""create_document METHOD map_line. DATA : lv_key TYPE string , lv_value TYPE string , lv_date TYPE datum , lv_uzeit TYPE sy-uzeit , lv_type TYPE c , lv_node_value TYPE string . DATA : iterator TYPE REF TO if_ixml_node_iterator . iterator = node->create_iterator( ). DO. DATA : lr_node TYPE REF TO if_ixml_node . lr_node = iterator->get_next( ). IF lr_node IS INITIAL. EXIT. ENDIF. CHECK lr_node->get_type( ) = if_ixml_node=>co_node_element. CHECK lr_node->get_name( ) = 't'. lv_node_value = lr_node->get_value( ). FIELD-SYMBOLS : TYPE abap_compdescr , TYPE any . LOOP AT components ASSIGNING . ASSIGN COMPONENT -name OF STRUCTURE data TO . DESCRIBE FIELD TYPE lv_type. CONCATENATE '{' -name '}' INTO lv_key. CASE lv_type. WHEN 'D'. lv_date = . CONCATENATE lv_date+6(2) '.' lv_date+4(2) '.' lv_date(4) INTO lv_value. WHEN 'T'. lv_uzeit = . CONCATENATE lv_uzeit(2) ':' lv_uzeit+2(2) ':' lv_uzeit+4(2) INTO lv_value. WHEN OTHERS. lv_value = . ENDCASE. REPLACE ALL OCCURRENCES OF lv_key IN lv_node_value WITH lv_value. CHECK sy-subrc = 0. lr_node->set_value( lv_node_value ). ENDLOOP. ENDDO. ENDMETHOD. ""map_line ENDCLASS. ""lcl_docx IMPLEMENTATION ",11021,False,2481.783196871881,median "/////////////////// // Pv router by Cyril Poissonnier 2019 // Pv routeur pour détecter l'injection par mesure de volume et envoie d'information sur domoticz // pour réponse ( switch, dimmer ... ) // fait pour fonctionner avec le circuit imprimé v1.1 à 1.4 ///////////////////////// /////////////////// // ----- configuration // la prise de valeur est de 72 échantillons par cycles // ----- envoie vers serveur domotique // la programmation par défaut n'envoie pas vers domoticz ou jeedom, il faut l'activer sur l'interface et sauvegarder la configuration // pour le mode autonome, il est possible de spécifier directement l'ip du dimmer numérique distant ( dans le fichier de conf ). la communication doit aussi être active pour fonctionner. // // // ----- sauvegarde de la configuration --- // faire un /get?save pour sauver la configuration dans le fichier // sauvegarde du fichier de config : /Config.json // // /cosphi permet d'avoir des logs sur le calcul du middle et de la valeur retourné : // valeurs lu -- calcul du phi conseillé - calcul des sommes et de différent type de calcul de moyennes // // // Ajout de la fonction // /get?reset pour redémarrer le pv routeur // ///////////////////////// /************** * numeric Dimmer Information * ************** * * ---------------------- OUTPUT & INPUT Pin table --------------------- * +---------------+-------------------------+-------------------------+ * | Board | INPUT Pin | OUTPUT Pin | * | | Zero-Cross | | * +---------------+-------------------------+-------------------------+ * | ESP8266 | D1(IO5), D2(IO4), | D0(IO16), D1(IO5), | * | | D5(IO14), D6(IO12), | D2(IO4), D5(IO14), | * | | D7(IO13), D8(IO15), | D6(IO12), D7(IO13), | * | | | D8(IO15) | * +---------------+-------------------------+-------------------------+ */ //*********************************** //************* Déclaration des libraries //*********************************** // time librairy #include // Dimmer librairy #include /// the corrected librairy in RBDDimmer-master-corrected.rar , the original has a bug // Web services #include #include // https://github.com/alanswx/ESPAsyncWiFiManager #include /// https://github.com/me-no-dev/ESPAsyncTCP #include /// https://github.com/me-no-dev/ESPAsyncWebServer #include // File System #include #include // Only needed for Arduino 1.6.5 and earlier #include // ArduinoJson : https://github.com/bblanchon/ArduinoJson // Oled #include ""SSD1306Wire.h"" /// Oled ( https://github.com/ThingPulse/esp8266-oled-ssd1306 ) // ota mise à jour sans fil #include #include //mqtt #include #define mqtt_user ""pvrouter"" // Dallas 18b20 //#include //#include // Include custom images #include ""images.h"" const String VERSION = ""Version 2.9.1"" ; String logs; ////BETA // int freqmesure = 85; int freqmesure = 72; int readtime = ( 1000000/(50*freqmesure)); int goodcycle = freqmesure - 5; String rawdata = """"; //*********************************** //************* Gestion de la configuration //*********************************** struct Config { char hostname[15]; int port; char apiKey[64]; bool UseDomoticz; bool UseJeedom; String IDX; char otapassword[64]; int delta; int deltaneg; int cosphi; int readtime; int cycle; bool sending; bool autonome; char dimmer[15]; bool dimmerlocal; float facteur; int num_fuse; bool mqtt; char mqttserver[15]; String IDXdimmer; int tmax; int resistance; }; const char *filename_conf = ""/config.json""; Config config; //*********************************** //************* Gestion de la configuration - Lecture du fichier de configuration //*********************************** // Loads the configuration from a file void loadConfiguration(const char *filename, Config &config) { // Open file for reading File configFile = SPIFFS.open(filename_conf, ""r""); // Allocate a temporary JsonDocument // Don't forget to change the capacity to match your requirements. // Use arduinojson.org/v6/assistant to compute the capacity. StaticJsonDocument<1024> doc; // Deserialize the JSON document DeserializationError error = deserializeJson(doc, configFile); if (error) { Serial.println(F(""Failed to read file, using default configuration in function loadConfiguration"")); logs += ""Failed to read file, using default configuration in function loadConfiguration/r/n""; } // Copy values from the JsonDocument to the Config config.port = doc[""port""] | 8080; strlcpy(config.hostname, // <- destination doc[""hostname""] | ""192.168.1.20"", // <- source sizeof(config.hostname)); // <- destination's capacity strlcpy(config.apiKey, // <- destination doc[""apiKey""] | ""Myapikeystring"", // <- source sizeof(config.apiKey)); // <- destination's capacity config.UseDomoticz = doc[""UseDomoticz""] | false; config.UseJeedom = doc[""UseJeedom""] | false; config.IDX = doc[""IDX""] | 62; config.IDXdimmer = doc[""IDXdimmer""] | 60; strlcpy(config.otapassword, // <- destination doc[""otapassword""] | ""Pvrouteur2"", // <- source sizeof(config.otapassword)); // <- destination's capacity config.facteur = doc[""facteur""] | 0.86; config.delta = doc[""delta""] | 50; config.num_fuse = doc[""fuse""] | 70; config.deltaneg = doc[""deltaneg""] | -100; config.cosphi = doc[""cosphi""] | 23; config.readtime = doc[""readtime""] | 555; config.cycle = doc[""cycle""] | 25; config.tmax = doc[""tmax""] | 65; config.resistance = doc[""resistance""] | 1000; config.sending = doc[""sending""] | false; config.autonome = doc[""autonome""] | true; config.mqtt = doc[""mqtt""] | false; config.dimmerlocal = doc[""dimmerlocal""] | false; strlcpy(config.dimmer, // <- destination doc[""dimmer""] | ""192.168.1.20"", // <- source sizeof(config.dimmer)); // <- destination's capacity strlcpy(config.mqttserver, // <- destination doc[""mqttserver""] | ""192.168.1.20"", // <- source sizeof(config.mqttserver)); // <- destination's capacity configFile.close(); } //*********************************** //************* Gestion de la configuration - sauvegarde du fichier de configuration //*********************************** void saveConfiguration(const char *filename, const Config &config) { // Open file for writing File configFile = SPIFFS.open(filename_conf, ""w""); if (!configFile) { Serial.println(F(""Failed to open config file for writing in function Save configuration"")); logs += ""Failed to open config file for writing in function Save configuration/r/n""; return; } // Allocate a temporary JsonDocument // Don't forget to change the capacity to match your requirements. // Use arduinojson.org/assistant to compute the capacity. StaticJsonDocument<512> doc; // Set the values in the document doc[""hostname""] = config.hostname; doc[""port""] = config.port; doc[""apiKey""] = config.apiKey; doc[""UseDomoticz""] = config.UseDomoticz; doc[""UseJeedom""] = config.UseJeedom; doc[""IDX""] = config.IDX; doc[""IDXdimmer""] = config.IDXdimmer; doc[""otapassword""] = config.otapassword; doc[""delta""] = config.delta; doc[""deltaneg""] = config.deltaneg; doc[""cosphi""] = config.cosphi; doc[""readtime""] = config.readtime; doc[""cycle""] = config.cycle; doc[""sending""] = config.sending; doc[""autonome""] = config.autonome; doc[""dimmer""] = config.dimmer; doc[""dimmerlocal""] = config.dimmerlocal; doc[""facteur""] = config.facteur; doc[""fuse""] = config.num_fuse; doc[""mqtt""] = config.mqtt; doc[""mqttserver""] = config.mqttserver; doc[""tmax""] = config.tmax; doc[""resistance""] = config.resistance; // Serialize JSON to file if (serializeJson(doc, configFile) == 0) { Serial.println(F(""Failed to write to file in function Save configuration "")); logs += ""Failed to write to file in function Save configuration:r/n""; } // Close the file configFile.close(); } //*********************************** //************* dimmer //*********************************** #define outputPin D7 #define zerocross D6 // for boards with CHANGEBLE input pins dimmerLamp dimmer_hard(outputPin, zerocross); //initialase port for dimmer for ESP8266, ESP32, Arduino due boards int dimmer_security = 60; // coupe le dimmer toute les X minutes en cas de probleme externe. int dimmer_security_count = 0; //*********************************** //************* Dallas 18b20 //*********************************** #define ONE_WIRE_BUS 7 #define TEMPERATURE_PRECISION 10 //*********************************** //************* Time //*********************************** const long utcOffsetInSeconds = 3600; char daysOfTheWeek[7][12] = {""Sunday"", ""Monday"", ""Tuesday"", ""Wednesday"", ""Thursday"", ""Friday"", ""Saturday""}; WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, ""europe.pool.ntp.org"", utcOffsetInSeconds); int timesync = 0; int timesync_refresh = 120; void call_time() { if ( timesync_refresh >= timesync ) { timeClient.update(); timesync = 0; } else {timesync++;} } String getTime() { String state; state = timeClient.getHours() + "":"" + timeClient.getMinutes() ; return String(state); } //*********************************** //************* Afficheur Oled //*********************************** const int I2C_DISPLAY_ADDRESS = 0x3c; SSD1306Wire display(0x3c, D1, D2); //*********************************** //************* Constantes //*********************************** //constantes de mesure #define OLED 1 // activation de l'afficheur oled #define attente 2 /// nombre de 1/2 secondes entre chaque cycle de mesure. int middle ; //constantes de fonctionnement #define USE_SERIAL Serial #define linky A0 #define lcd_scd D1 // LCD et OLED #define lcd_scl D2 // LCD et OLED #define sens D5 /// niveau de la diode int dimmer_power = 0; int security=0; // envoie régulier de 0 vers le dimmer dans certains cas /// constantes de debug #define modeserial 0 //int inversion = 0 ; int phi; int somme, sigma ; int signe = 0; int temp = 0; int timer = 0 ; String retour; int nbtent=0; int moyenne, laststartvalue; String message; String configweb , memory, inputMessage; int inj_mode = 0 ; //int RMS = 0 ; bool change; //String serialmessage; bool middlevalue=0; int bypassfalse=0; //int resistance=1000; int bestcosphi, bestpuissance; //*********************************** //************* Gestion du serveur WEB //*********************************** // Create AsyncWebServer object on port 80 WiFiClient domotic_client; // mqtt PubSubClient client(domotic_client); AsyncWebServer server(80); DNSServer dns; HTTPClient http; // creation des fonctions de collect //*********************************** //************* retour des pages //*********************************** String getState() { String state ; if ( inj_mode == 0 ) { state = ""Linky""; } if ( inj_mode == 1 ) { state = ""Injection""; } if ( inj_mode == 2 ) { state = ""Stabilise""; } //int sigma = somme ; state = state + "";"" + sigma + "";"" + dimmer_power ; return String(state); } const char* PARAM_INPUT_1 = ""send""; /// paramettre de retour sendmode const char* PARAM_INPUT_2 = ""cycle""; /// paramettre de retour cycle const char* PARAM_INPUT_3 = ""readtime""; /// paramettre de retour readtime const char* PARAM_INPUT_4 = ""cosphi""; /// paramettre de retour cosphi const char* PARAM_INPUT_save = ""save""; /// paramettre de retour cosphi const char* PARAM_INPUT_dimmer = ""dimmer""; /// paramettre de retour cosphi const char* PARAM_INPUT_server = ""server""; /// paramettre de retour server domotique const char* PARAM_INPUT_IDX = ""idx""; /// paramettre de retour idx const char* PARAM_INPUT_IDXdimmer = ""idxdimmer""; /// paramettre de retour idx const char* PARAM_INPUT_port = ""port""; /// paramettre de retour port server domotique const char* PARAM_INPUT_delta = ""delta""; /// paramettre retour delta const char* PARAM_INPUT_deltaneg = ""deltaneg""; /// paramettre retour deltaneg const char* PARAM_INPUT_fuse = ""fuse""; /// paramettre retour fusible numérique const char* PARAM_INPUT_API = ""apiKey""; /// paramettre de retour apiKey const char* PARAM_INPUT_servermode = ""servermode""; /// paramettre de retour activation de mode server const char* PARAM_INPUT_dimmer_power = ""POWER""; /// paramettre de retour activation de mode server const char* PARAM_INPUT_facteur = ""facteur""; /// paramettre retour delta const char* PARAM_INPUT_tmax = ""tmax""; /// paramettre retour delta const char* PARAM_INPUT_mqttserver = ""mqttserver""; /// paramettre retour mqttserver const char* PARAM_INPUT_reset = ""reset""; /// paramettre retour mqttserver String stringbool(bool mybool){ String truefalse = ""true""; if (mybool == false ) {truefalse = """";} return String(truefalse); } String getSendmode() { String sendmode; if ( config.sending == 0 ) { sendmode = ""Off""; } else { sendmode = ""On""; } return String(sendmode); } String getServermode(String Servermode) { if ( Servermode == ""Domoticz"" ) { config.UseDomoticz = !config.UseDomoticz; } if ( Servermode == ""Jeedom"" ) { config.UseJeedom = !config.UseJeedom;} if ( Servermode == ""Autonome"" ) { config.autonome = !config.autonome; } if ( Servermode == ""Dimmer local"" ) { config.dimmerlocal = !config.dimmerlocal; } if ( Servermode == ""MQTT"" ) { config.mqtt = !config.mqtt; } return String(Servermode); } String getSigma() { return String(sigma); } String getcosphi() { return String(rawdata) ; } String getpuissance() { int tempvalue=15; return String(bestpuissance*config.facteur) ; } String getconfig() { configweb = String(config.hostname) + "";"" + config.port + "";"" + config.IDX + "";"" + VERSION +"";"" + middle +"";""+ config.delta +"";""+config.cycle+"";""+config.dimmer+"";""+config.cosphi+"";""+config.readtime +"";""+stringbool(config.UseDomoticz)+"";""+stringbool(config.UseJeedom)+"";""+stringbool(config.autonome)+"";""+config.apiKey+"";""+stringbool(config.dimmerlocal)+"";""+config.facteur+"";""+stringbool(config.mqtt)+"";""+config.mqttserver+"";""+config.deltaneg+"";""+config.resistance; return String(configweb); } String getchart() { oscilloscope() ; return String(retour); } String getdebug() { configweb = String(ESP.getFreeHeap())+ "";"" + String(laststartvalue) + "";"" + String(middle) + "";"" + phi +"";""+ config.resistance ; return String(configweb); } String getmemory() { memory = String(ESP.getFreeHeap()) + "";"" + String(ESP.getHeapFragmentation()) + "";"" + String(ESP.getMaxFreeBlockSize()); return String(memory); } String getlogs() { return String(logs); } String processor(const String& var){ Serial.println(var); if (var == ""SIGMA""){ return getSigma(); } else if (var == ""SENDMODE""){ return getSendmode(); } else if (var == ""STATE""){ return getState(); } } //*********************************** //************* Setup //*********************************** void setup() { // init port pinMode(linky, INPUT); Serial.begin(115200); Serial.println(); // Initialising OLED display.init(); display.flipScreenVertically(); display.setFont(ArialMT_Plain_10); display.clear(); //démarrage file system SPIFFS.begin(); Serial.println(""Demarrage file System""); // vérification de la présence d'index.html if(!SPIFFS.exists(""/index.html"")){ Serial.println(""Attention fichiers SPIFFS non chargé sur l'ESP, ça ne fonctionnera pas.""); logs += ""Attention fichiers SPIFFS non chargé sur l'ESP, ça ne fonctionnera pas.""; } //*********************************** //************* Setup - récupération du fichier de configuration //*********************************** // Should load default config if run for the first time Serial.println(F(""Loading configuration..."")); logs += ""Loading configuration.../r/n""; loadConfiguration(filename_conf, config); // Create configuration file Serial.println(F(""Saving configuration..."")); logs += ""Saving configuration... /r/n""; saveConfiguration(filename_conf, config); // configuration dimmer dimmer_hard.begin(NORMAL_MODE, ON); //dimmer initialisation: name.begin(MODE, STATE) dimmer_hard.setPower(0); USE_SERIAL.println(""Dimmer started...""); // configuration Wifi AsyncWiFiManager wifiManager(&server,&dns); wifiManager.autoConnect(""pvrouter"", ""pvrouter""); //*********************************** //************* Setup - Connexion Wifi //*********************************** // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("".""); } //Si connexion affichage info dans console Serial.println(""""); Serial.print(""Connection ok sur le reseau : ""); Serial.print(""IP address: ""); Serial.println(WiFi.localIP()); Serial.println(ESP.getResetReason()); // mqtt if (config.mqtt==1) { client.connect(""pvrouter""); } //*********************************** //************* Setup - OTA //*********************************** ArduinoOTA.setHostname(""PV Routeur""); //ArduinoOTA.setPassword(otapassword); ArduinoOTA.onStart([]() { Serial.println(""Start""); }); ArduinoOTA.onEnd([]() { Serial.println(""\\nEnd""); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf(""Progress: %u%%\\r"", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf(""Error[%u]: "", error); if (error == OTA_AUTH_ERROR) Serial.println(""Auth Failed""); else if (error == OTA_BEGIN_ERROR) Serial.println(""Begin Failed""); else if (error == OTA_CONNECT_ERROR) Serial.println(""Connect Failed""); else if (error == OTA_RECEIVE_ERROR) Serial.println(""Receive Failed""); else if (error == OTA_END_ERROR) Serial.println(""End Failed""); }); ArduinoOTA.begin(); //*********************************** //************* Setup - Web pages //*********************************** server.on(""/"",HTTP_ANY, [](AsyncWebServerRequest *request){ if(SPIFFS.exists(""/index.html"")){ request->send(SPIFFS, ""/index.html"", String(), false, processor); } else {request->send_P(200, ""text/plain"", ""fichiers SPIFFS non présent sur l ESP. "" ); } }); server.on(""/config.html"",HTTP_ANY, [](AsyncWebServerRequest *request){ request->send(SPIFFS, ""/config.html"", String(), false, processor); }); server.on(""/all.min.css"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send(SPIFFS, ""/all.min.css"", ""text/css""); }); server.on(""/favicon.ico"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send(SPIFFS, ""/favicon.ico"", ""image/png""); }); server.on(""/fa-solid-900.woff2"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send(SPIFFS, ""/fa-solid-900.woff2"", ""text/css""); }); server.on(""/sb-admin-2.js"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send(SPIFFS, ""/sb-admin-2.js"", ""text/javascript""); }); server.on(""/sb-admin-2.min.css"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send(SPIFFS, ""/sb-admin-2.min.css"", ""text/css""); }); server.on(""/chart.json"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""application/json"", getchart().c_str()); }); server.on(""/sendmode"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getSendmode().c_str()); }); server.on(""/state"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getState().c_str()); }); server.on(""/serial"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getState().c_str()); }); server.on(""/config"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getconfig().c_str()); }); server.on(""/memory"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getmemory().c_str()); }); server.on(""/debug"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getdebug().c_str()); }); server.on(""/log"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getlogs().c_str()); }); server.on(""/config.json"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send(SPIFFS, ""/config.json"", ""application/json""); }); server.on(""/doc.txt"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send(SPIFFS, ""/doc.txt"", ""text/plain""); }); /// beta server.on(""/cosphi"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getcosphi().c_str()); }); server.on(""/puissance"", HTTP_ANY, [](AsyncWebServerRequest *request){ request->send_P(200, ""text/plain"", getpuissance().c_str()); }); ///////////////////////// ////// mise à jour parametre d'envoie vers domoticz et récupération des modifications de configurations ///////////////////////// server.on(""/get"", HTTP_ANY, [] (AsyncWebServerRequest *request) { /// /get?send=on if (request->hasParam(PARAM_INPUT_1)) { inputMessage = request->getParam(PARAM_INPUT_1)->value(); config.sending = 0; if ( inputMessage != ""On"" ) { config.sending = 1; } request->send(200, ""text/html"", getSendmode().c_str()); } // /get?cycle=x if (request->hasParam(PARAM_INPUT_save)) { Serial.println(F(""Saving configuration..."")); saveConfiguration(filename_conf, config); } if (request->hasParam(PARAM_INPUT_2)) { config.cycle = request->getParam(PARAM_INPUT_2)->value().toInt(); } if (request->hasParam(PARAM_INPUT_3)) { config.readtime = request->getParam(PARAM_INPUT_3)->value().toInt();} if (request->hasParam(PARAM_INPUT_4)) { config.cosphi = request->getParam(PARAM_INPUT_4)->value().toInt(); } if (request->hasParam(PARAM_INPUT_dimmer)) { request->getParam(PARAM_INPUT_dimmer)->value().toCharArray(config.dimmer,15); } if (request->hasParam(PARAM_INPUT_server)) { request->getParam(PARAM_INPUT_server)->value().toCharArray(config.hostname,15); } if (request->hasParam(PARAM_INPUT_mqttserver)) { request->getParam(PARAM_INPUT_mqttserver)->value().toCharArray(config.mqttserver,15); } if (request->hasParam(PARAM_INPUT_delta)) { config.delta = request->getParam(PARAM_INPUT_delta)->value().toInt(); } if (request->hasParam(PARAM_INPUT_deltaneg)) { config.deltaneg = request->getParam(PARAM_INPUT_deltaneg)->value().toInt(); } if (request->hasParam(PARAM_INPUT_fuse)) { config.num_fuse = request->getParam(PARAM_INPUT_fuse)->value().toInt(); } if (request->hasParam(PARAM_INPUT_port)) { config.port = request->getParam(PARAM_INPUT_port)->value().toInt(); } if (request->hasParam(PARAM_INPUT_IDX)) { config.IDX = request->getParam(PARAM_INPUT_IDX)->value().toInt();} if (request->hasParam(PARAM_INPUT_IDXdimmer)) { config.IDXdimmer = request->getParam(PARAM_INPUT_IDXdimmer)->value().toInt();} if (request->hasParam(PARAM_INPUT_API)) { request->getParam(PARAM_INPUT_API)->value().toCharArray(config.apiKey,64);} if (request->hasParam(PARAM_INPUT_dimmer_power)) {dimmer_power = request->getParam( PARAM_INPUT_dimmer_power)->value().toInt(); change = 1 ; } if (request->hasParam(PARAM_INPUT_facteur)) { config.facteur = request->getParam(PARAM_INPUT_facteur)->value().toFloat();} if (request->hasParam(PARAM_INPUT_tmax)) { config.tmax = request->getParam(PARAM_INPUT_tmax)->value().toInt();} if (request->hasParam(""resistance"")) { config.resistance = request->getParam(""resistance"")->value().toInt();} //reset if (request->hasParam(PARAM_INPUT_reset)) {Serial.println(""Resetting ESP""); ESP.restart();} if (request->hasParam(PARAM_INPUT_servermode)) { inputMessage = request->getParam( PARAM_INPUT_servermode)->value(); getServermode(inputMessage); request->send(200, ""text/html"", getconfig().c_str()); } request->send(200, ""text/html"", getconfig().c_str()); }); //*********************************** //************* mise en route de Time //*********************************** timeClient.begin(); timeClient.update(); //*********************************** //************* Setup - demarrage du webserver et affichage de l'oled //*********************************** server.begin(); if (config.mqtt==1) { client.setServer(config.mqttserver, 1883); mqtt(config.IDXdimmer,""0""); } /// reset dimmer int httpCode; String baseurl; dimmer_power=0; baseurl = ""/?POWER="" + String(dimmer_power) ; http.begin(config.dimmer,80,baseurl); httpCode = http.GET(); http.end(); delay(5000); // récupération de la puissacen branchée //resistance = mesure_resistance (); affiche_info_main(); } //*********************************** //************* loop //*********************************** void loop() { /// preparation des mesures temp = 0; timer = 0 ; somme = 0; int i = 0; int validation = 0; // lecture de la valeur moyenne valeur_moyenne(); /// recherche d'un cycle stable if ( middlevalue == 1 || bypassfalse >= 5 ) { sigma = somme * config.facteur ; //************************** //// détection traitement des conso //************************** // production if ( sigma > config.delta ) { if ( modeserial == 1 ) {Serial.println(""prod""); } message = ""Mode Linky ""; inj_mode=0; if ( config.sending == 1 ) { SendToDomotic(String(sigma)); delay(2*attente*1000); } } //************************** // injection //************************** else if ( sigma < config.deltaneg ) { if ( modeserial == 1 ) {Serial.println(""inj""); } message = ""Correc injection ""; inj_mode=1; if ( config.sending == 1) { SendToDomotic(String(sigma)); delay(2*attente*1000); } } else { message = ""Mode stabilise "" ; inj_mode=2; if ( config.sending == 1 ) { security ++; if ( security >=6 ) { SendToDomotic(String(sigma)); delay(5*attente*1000); security =0; } } // envoie de l'info de temps en temps pour les logs } affiche_info_injection(inj_mode); affiche_info_volume(sigma); if (config.autonome == 1 ) {dimmer(inj_mode); } } else { bypassfalse++; } //pause de X s secondes avant prochaine mesure affiche_info_transmission(config.sending); delay (500*attente); ArduinoOTA.handle(); dimmer_security_count ++; if ( dimmer_security_count >= dimmer_security *120 ) { dimmer_security_count = 0; /// dimmer security cut every %dimmer_security% minutes dimmer_hard.setPower(0); } if ( config.dimmerlocal == 1 && change == 1 ) { dimmer_hard.setPower(5) ; delay ( 250 ) ; dimmer_hard.setPower(dimmer_power) ; change = 0 ; } delay (1000); } // *************** FIN DE LOOP ******************** // *********************************** // ************* Fonction interne // *********************************** // *********************************** // ** recherche de changement sur la diode. // *********************************** void front(int variation) { int Watchdog=0 ; int Watchdog_alert=0; while ( digitalRead(sens) == variation ) { delayMicroseconds (25); Watchdog++; if ( Watchdog > 10000 && Watchdog_alert == 0 ) { Serial.print(""Attention pas de porteuse, alimentation 12v AC ou pont redresseur débranché ? ""); Watchdog_alert =1 ; } } } // *********************************** // ************* Fonction d'affichage // *********************************** // *********************************** // ************* main // *********************************** void affiche_info_main() { display.clear(); display.drawXbm(0,0, 16, 16, antenne_logo); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_10); display.drawString(63, 0, String(WiFi.localIP().toString())); display.setTextAlignment(TEXT_ALIGN_LEFT); ////// affichage de l'état conf display.drawString(0,54, VERSION ); affiche_info_transmission(config.sending); display.drawString(0,43, String(config.resistance)+"" W"" ); display.display(); } // *********************************** // ************* affichage transmission // *********************************** void affiche_info_transmission (int transmission ){ display.setColor(BLACK); display.fillRect(0, 16, 50, 10); display.setColor(WHITE); display.setTextAlignment(TEXT_ALIGN_LEFT); display.setFont(ArialMT_Plain_10); if ( transmission == 0 ) { display.drawString(0,16, ""Trans Off""); } else { display.drawString(0,16, ""Trans On ""); } display.display(); } // *********************************** // ************* affichage du sigma et heure // *********************************** void affiche_info_volume(int volume ) { affiche_heure(); // Affichage de l'heure display.setColor(BLACK); display.fillRect(55, 30, 128, 64); display.setColor(WHITE); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_16); display.drawString(85,30, String(volume) + "" W""); display.drawString(85,47, String(dimmer_power) + "" %""); display.display(); } // *********************************** // ************* affichage mode de conso // *********************************** void affiche_info_injection(int injection_mode ) { display.setColor(BLACK); display.fillRect(75, 16, 128, 26); display.setColor(WHITE); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_10); display.drawString(100,16, "" ""); if ( injection_mode == 0 ) { display.drawString(100,16, ""Linky""); } else if ( injection_mode == 1 ) { display.drawString(100,16, ""Injection""); } else { display.drawString(100,16, ""Stabilise""); } display.display(); } // *********************************** // ************* affichage des delta // *********************************** void affiche_info_delat() { display.setColor(BLACK); display.fillRect(0, 27, 55, 28); display.setColor(WHITE); display.setTextAlignment(TEXT_ALIGN_LEFT); display.setFont(ArialMT_Plain_10); display.drawString(0,29, ""Delta : "" + String(config.delta)); display.drawString(0,41, ""Neg : "" + String(config.deltaneg)); display.display(); } // *********************************** // ************* affichage Heure // *********************************** void affiche_heure() { String ActualTime = timeClient.getFormattedTime(); //String ActualTime = timeClient.getHours()+"":""+timeClient.getMinutes() ; display.setColor(BLACK); display.fillRect(0, 27, 55, 28); display.setColor(WHITE); display.setTextAlignment(TEXT_ALIGN_LEFT); display.setFont(ArialMT_Plain_10); display.drawString(0,29, ActualTime); //display.drawString(0,41, ""Neg : "" + String(config.deltaneg)); display.display(); } // *********************************** // ************* affichage logo transmission // *********************************** void affiche_transmission(int actif) { if ( actif == 1 ) { display.drawXbm(111,0 , 16, 16, antenne_logo2); } else { display.setColor(BLACK); display.fillRect(111, 0, 127, 16); display.setColor(WHITE); } display.display(); } //*********************************** //** Oscillo mode creation du tableau de mesure pour le graph //*********************************** void oscilloscope() { int starttime,endtime; timer = 0; retour = ""[[""; front (0); front(1); delayMicroseconds (config.cosphi*config.readtime); // correction décalage while ( timer < ( freqmesure ) ) { temp = analogRead(linky); signe = digitalRead(sens); moyenne = middle - 25 + signe*50; //moyenne = moyenne + abs(temp - middle) ; /// mode oscillo graph retour += String(timer) + "","" + String(moyenne) + "","" + String(temp) + ""],["" ; timer ++ ; delayMicroseconds (config.readtime); } temp = analogRead(linky); signe = digitalRead(sens); moyenne = middle - 25 + signe*50; retour += String(timer) + "","" + String(moyenne) + "","" + String(temp) + ""]]"" ; } //*********************************** //************* Fonction mesure de la résistance ( à la louche ) //*********************************** int mesure_resistance () { // mise à 0 dimmer String baseurl; baseurl = ""/?POWER="" + String(0) ; http.begin(config.dimmer,80,baseurl); int httpCode = http.GET(); http.end(); delay (5000); int resistance; int boucle=0; int temp=0; int facteur_capteur=5; // 5watt par unité de lecture int min=1024; int max=0; int valup=0; int valdown=0; //lecture 0% while (boucle < freqmesure){ temp = analogRead(linky); if ( temp > max ) { max = temp ; } if ( temp < min ) { min = temp ; } delayMicroseconds (readtime); boucle++; } valdown = max-min; baseurl = ""/?POWER="" + String(50) ; http.begin(config.dimmer,80,baseurl); httpCode = http.GET(); http.end(); delay (5000); boucle=0; min=1024; max=0; //lecture 50% while (boucle < freqmesure){ temp = analogRead(linky); if ( temp > max ) { max = temp ; } if ( temp < min ) { min = temp ; } delayMicroseconds (readtime); boucle++; } valup = max-min; resistance = ( valup - valdown )*2*5 ; // dimmer à 0 baseurl = ""/?POWER="" + String(0) ; http.begin(config.dimmer,80,baseurl); httpCode = http.GET(); http.end(); return (resistance); } //*********************************** //************* Fonction valeur moyenne et calcul //*********************************** void valeur_moyenne() { String log=""""; float moyenne = 0; int temp = 0 ; int j = 0; int i = 0; int up = 0; middlevalue = 0; int sommetemp = 0; int sommeinverse = 0; int sommetotale = 0; int demicycle = freqmesure/2; int derive = 0 ; int min=1024; int max=0; int startvalue=0; unsigned long startMillis; //// attente du prochain cycle while (digitalRead(sens) != 1 ) { delayMicroseconds (100); } while (digitalRead(sens) != 0 ) { delayMicroseconds (10); } startMillis = micros(); //// calcul de la 1/2 onde //// rajout de la condition && j < (demicycle-20) pour éviter les rebonds while (digitalRead(sens) != 1 && j < (demicycle) ) { temp = analogRead(linky); if ( ( j >= config.cosphi && j < (demicycle+config.cosphi) )) { sommetemp += temp; i++; log += String(temp) + ""-"" ; } else { log += String(temp) + "" "" ; sommeinverse += temp; } if ( j == config.cosphi ) { startvalue = temp; } if ( temp > max ) { max =temp ; up = j; } if ( temp < min ) { min = temp ; } j ++; rt_loop( startMillis, readtime*j ) ; } log += + ""++"" ; /// calcul de la 2em 1/2 onde while (digitalRead(sens) != 0 && j != freqmesure ) { temp = analogRead(linky); if ( j < (demicycle+config.cosphi) ) { sommetemp += temp; i++; log += String(temp) + ""-"" ; } else { log += String(temp) + "" "" ; sommeinverse += temp; } if ( temp > max ) { max =temp ; up = j; } if ( temp < min ) { min = temp ; } j ++; rt_loop( startMillis, readtime*j ) ; } // affichage du temps pris startMillis = micros() - startMillis ; Serial.print(""temp: ""); Serial.print(startMillis); sommetotale = ( sommetemp + sommeinverse ) ; moyenne = float(sommetotale) / float(freqmesure) ; float moyenne2 = ((float(min) + float(max)) / 2.0) ; float moyenne3 = config.cycle; somme = (sommetemp - (moyenne*demicycle)) ; float somme2 = (sommetemp - (moyenne2*demicycle)) ; float somme3 = (sommetemp - (moyenne3*demicycle)) ; //sommeinverse = (sommeinverse - (moyenne*demicycle) ); //somme = (somme + sommeinverse)/2 ; float inverse1 = (sommeinverse - (moyenne*demicycle)); float inverse2 = (sommeinverse - (moyenne2*demicycle)) ; float inverse3 = (sommeinverse - (moyenne3*demicycle)) ; /* sommetotale = ( sommetemp + sommeinverse ) ; moyenne = float(sommetotale) / float(freqmesure); somme = (sommetemp - (moyenne*demicycle)) - (sommeinverse - (moyenne*demicycle)) ; somme = sommetemp - sommeinverse ; */ if ( j >=goodcycle || bypassfalse >= 5 ) { Serial.println(""-------------""); Serial.print(""valeur moyenne""); Serial.println(moyenne); Serial.print(""cycle : ""); Serial.println(j); Serial.print(""demi : ""); Serial.println(i); Serial.print(""cosphi :""); Serial.println(config.cosphi); Serial.print(""sommetemp :""); Serial.println(sommetemp); Serial.print(""somme :""); Serial.println(somme); Serial.print(""min max :""); Serial.print(min ); Serial.print("" ""); Serial.println(max); Serial.print(""START :""); Serial.println(startvalue ); laststartvalue = startvalue ; Serial.println(log); middle = moyenne ; middlevalue = 1; long rssi = WiFi.RSSI(); Serial.print(""RSSI:""); Serial.println(rssi); } else { Serial.println(""erreur cycle :""); Serial.println(j); } /// retrait de rowdata de la condition pour debug rawdata = log + "" \\r\\n -- phi : "" + ( up - (j/4) ) + "" somme : "" + sommetemp + "" -- somme inverse : "" + sommeinverse + ""\\r\\n -- middle : "" + moyenne + ""-- somme :"" + somme + ""-- inv :"" + inverse1 + "" \\r\\n -- moyenne 2 : "" + moyenne2 + "" : "" + somme2 + ""-- inv :"" + inverse2 + "" total "" + (somme2 - inverse2 )/2 + "" \\r\\n -- moyenne 3 : "" + moyenne3 + "" : "" + somme3 + ""-- inv :"" + inverse3 + "" total "" + (somme3 - inverse3 )/2 +"" temps"" + startMillis; } //////////////////////// RT loop void rt_loop (unsigned long startmicro, unsigned long timer ) { while ( micros() <= ( startmicro + timer ) ) { delayMicroseconds(1); } } //*********************************** //************* Fonction domotique //*********************************** boolean SendToDomotic(String Svalue){ String baseurl; Serial.print(""connecting to mqtt & dimmer""); Serial.println(config.hostname); //Serial.print(""Requesting URL: ""); //if ( config.UseDomoticz == 1 ) { baseurl = ""/json.htm?type=command¶m=udevice&idx=""+config.IDX+""&nvalue=0&svalue=""+Svalue; http.begin(config.hostname,config.port,baseurl); } //if ( config.UseJeedom == 1 ) { baseurl = ""/core/api/jeeApi.php?apikey="" + String(config.apiKey) + ""&type=virtual&id=""+ config.IDX + ""&value="" + Svalue; http.begin(config.hostname,config.port,baseurl); } if ( config.mqtt == 1 ) { mqtt(config.IDX,Svalue); } Serial.println(baseurl); // http.begin(config.hostname,config.port,baseurl); //int httpCode = http.GET(); //Serial.println(""closing connection""); //http.end(); if ( config.autonome == 1 && change == 1 ) { baseurl = ""/?POWER="" + String(dimmer_power) ; http.begin(config.dimmer,80,baseurl); int httpCode = http.GET(); http.end(); if ( config.mqtt == 1 ) { mqtt(config.IDXdimmer, String(dimmer_power)); } delay (3000); // delay de transmission réseau dimmer et application de la charge } valeur_moyenne(); } //*********************************** //************* Fonction aservissement autonome //*********************************** void dimmer(int commande){ change = 0; // 0 -> linky ; 1-> injection ; 2-> stabilisé if ( sigma >= 350 && dimmer_power != 0 ) { dimmer_power = 0 ; change = 1 ;} // si grosse puissance instantanée sur le réseau, coupure du dimmer. ( ici 350w environ ) else if (commande == 0 && dimmer_power != 0 && sigma >= (config.delta+10) ) { dimmer_power += -2*((sigma-config.delta)/(50*config.resistance/1000)) ; change = 1; } /// si gros mode linky on reduit la puissance par extrapolation else if (commande == 0 && dimmer_power != 0 ) { dimmer_power += -1 ; change = 1; } /// si mode linky on reduit la puissance else if (commande == 1 && sigma <= (config.deltaneg-10) ) { dimmer_power += 2*abs(sigma/(50*config.resistance/1000)) ; change = 1 ; } /// si grosse injection on augmente la puissance par extrapolation else if (commande == 1 ) { dimmer_power += 1 ; change = 1 ; } /// si injection legère on augmente la puissance doucement //else if (commande == 1 ) { dimmer_power += round(sigma/(bestpuissance * config.facteur)*100) ; change = 1 ; } /// si injection on augmente la puissance /// test puissance de sécurité if ( dimmer_power >= config.num_fuse ) {dimmer_power = config.num_fuse; change = 1 ; } if ( dimmer_power <= 0 && dimmer_power != 0 ) {dimmer_power = 0; change = 1 ; } if (commande == 2 ) { change = 1 ; } /// mode stabilisé, envoie de sigma de temps en temps security ++ ; if ( security >= 5 ) { if ( dimmer_power <= 0 ) {dimmer_power = 0; change = 1 ; security = 0; }} } void mqtt(String idx, String value) { String nvalue = ""0"" ; if ( value != ""0"" ) { nvalue = ""2"" ; } String message = "" { \\""idx\\"" : "" + idx +"" , \\""svalue\\"" : \\"""" + value + ""\\"", \\""nvalue\\"" : "" + nvalue + "" } ""; if (!client.connected()) { reconnect(); } client.loop(); client.publish(""domoticz/in"", String(message).c_str(), true); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print(""Attempting MQTT connection...""); // Create a random client ID String clientId = ""ESP8266Client-""; clientId += String(random(0xffff), HEX); // Attempt to connect if (client.connect(clientId.c_str())) { Serial.println(""connected""); // Once connected, publish an announcement... client.publish(""outTopic"", ""hello world it's me !! PvRouter ""); // ... and resubscribe client.subscribe(""inTopic""); } else { Serial.print(""failed, rc=""); Serial.print(client.state()); Serial.println("" try again in 5 seconds""); // Wait 5 seconds before retrying delay(5000); } } } /* int getBarsSignal(long rssi){ // 5. High quality: 90% ~= -55db // 4. Good quality: 75% ~= -65db // 3. Medium quality: 50% ~= -75db // 2. Low quality: 30% ~= -85db // 1. Unusable quality: 8% ~= -96db // 0. No signal int bars; if (rssi > -55) { bars = 5; } else if (rssi < -55 & rssi > -65) { bars = 4; } else if (rssi < -65 & rssi > -75) { bars = 3; } else if (rssi < -75 & rssi > -85) { bars = 2; } else if (rssi < -85 & rssi > -96) { bars = 1; } else { bars = 0; } return bars; } void affiche_heure() { String ActualTime = timeClient.getFormattedTime(); //String ActualTime = timeClient.getHours()+"":""+timeClient.getMinutes() ; display.setColor(BLACK); display.fillRect(28, 28, 38, 38); display.setColor(WHITE); display.setTextAlignment(TEXT_ALIGN_LEFT); display.setFont(ArialMT_Plain_10); display.drawString(0,28,ActualTime); display.display(); } */ ",12057,False,1925.4709745765529,median "// Talkie library // Copyright 2011 Peter Knight // This code is released under GPLv2 license. // // The following phrases are derived from those built into the // Acorn Computers Speech Synthesiser add-on from 1983. // // A male voice with an RP English accent, voiced by Kenneth Kendall. // // Due to the large vocabulary, this file takes up 16Kbytes of flash. // To save space, just copy and paste the words you need. #define ACORN #include #ifdef ACORN const uint8_t spPAUSE1[] PROGMEM = {0x08, 0x14, 0xC1, 0xDD, 0x45, 0x64, 0x03, 0x00, 0xFC, 0x4A, 0x56, 0x26, 0x3A, 0x06, 0x0A}; const uint8_t spPAUSE2[] PROGMEM = {0x08, 0x14, 0xC1, 0xDD, 0x45, 0x64, 0x03, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x4A, 0x46, 0x51, 0x39, 0x79, 0x15, 0x0A}; const uint8_t spTONE1[] PROGMEM = {0x8D, 0xF2, 0xDE, 0xDD, 0xDD, 0x93, 0x74, 0xAA, 0x53, 0x9D, 0xEA, 0x54, 0xA7, 0x3A, 0xD5, 0xA9, 0x4E, 0x75, 0xAA, 0x53, 0x9D, 0xEA, 0x54, 0xA7, 0x3A, 0xD5, 0xA9, 0x4E, 0x75, 0xAA, 0x53, 0x9D, 0xEA, 0x54, 0xA7, 0x3A, 0xD5, 0xA9, 0x4E, 0x75, 0xAA, 0x53, 0x9D, 0xEA, 0x54, 0xA7, 0x3A, 0xD5, 0xA9, 0x4E, 0x75, 0xAA, 0x53, 0x9D, 0xFA, 0x4A, 0x26, 0x51, 0x39, 0x79, 0x15, 0x0A}; const uint8_t spTONE2[] PROGMEM = {0x4D, 0xF1, 0xDE, 0xDD, 0xDD, 0x93, 0x74, 0xA5, 0x2B, 0x5D, 0xE9, 0x4A, 0x57, 0xBA, 0xD2, 0x95, 0xAE, 0x74, 0xA5, 0x2B, 0x5D, 0xE9, 0x4A, 0x57, 0xBA, 0xD2, 0x95, 0xAE, 0x74, 0xA5, 0x2B, 0x5D, 0xE9, 0x4A, 0x57, 0xBA, 0xD2, 0x95, 0xAE, 0x74, 0xA5, 0x2B, 0x5D, 0xE9, 0x4A, 0x57, 0xBA, 0xD2, 0x95, 0xAE, 0x74, 0xA5, 0x2B, 0x5D, 0xF9, 0x11, 0x5A}; const uint8_t spTHREE[] PROGMEM = {0x08, 0xA8, 0xC2, 0x8C, 0x02, 0x04, 0x68, 0x2A, 0xDC, 0xF9, 0x51, 0x5B, 0x96, 0x79, 0x8D, 0x10, 0xE5, 0xCA, 0x2E, 0x9A, 0x76, 0x72, 0xD0, 0xC2, 0x5C, 0x25, 0x21, 0x23, 0xCD, 0x0C, 0x4F, 0xD4, 0x22, 0x7A, 0x46, 0x34, 0x3E, 0xF1, 0x48, 0x86, 0xD2, 0xB1, 0xEA, 0x24, 0x33, 0x16, 0x62, 0xE7, 0xAA, 0x55, 0xAC, 0xD4, 0x04, 0xD5, 0x8D, 0x47, 0xB3, 0x53, 0x33, 0xE4, 0x2C, 0x69, 0xED, 0x4E, 0x81, 0x30, 0x53, 0xA7, 0xF5, 0xBB, 0x14, 0x43, 0xF4, 0x92, 0x36, 0xEC, 0x92, 0x04, 0xD5, 0x4B, 0xD2, 0xB8, 0xAB, 0x23, 0xF4, 0x34, 0xCE, 0x63, 0x19, 0x57, 0x73, 0x84, 0xAE, 0x26, 0x69, 0x9C, 0x8D, 0xC0, 0xAB, 0x6B, 0x87, 0xB1, 0x7B, 0x94, 0x99, 0x8A, 0xF2, 0x5A, 0x66}; const uint8_t spEIGH_[] PROGMEM = {0x23, 0x1E, 0xC5, 0x58, 0x33, 0xA7, 0x9E, 0xA0, 0x6A, 0xF1, 0xAD, 0x9E, 0xB2, 0xE2, 0xEE, 0x49, 0xAB, 0x3A, 0xCA, 0x2A, 0x66, 0x72, 0x94, 0xE9, 0xDA, 0xBB, 0x0A, 0xC3, 0x30, 0x8C, 0xB5, 0x1D, 0x5B, 0x4C, 0x42, 0xB9, 0xBB, 0x88, 0x6C, 0x00, 0x80, 0xFF, 0x4E}; const uint8_t spNINE_[] PROGMEM = {0xA1, 0x4A, 0x4C, 0xF4, 0x31, 0xDD, 0x85, 0x32, 0x71, 0xB6, 0xC7, 0x74, 0x57, 0xF2, 0x4C, 0x4D, 0x1F, 0x33, 0x79, 0xCB, 0x1A, 0x48, 0x3E, 0xD6, 0xFA, 0x27, 0xE9, 0xB2, 0xD5, 0xC4, 0x1B, 0x9D, 0xB8, 0xD9, 0x4B, 0x17, 0x4F, 0x74, 0xD2, 0xAE, 0x6E, 0x42, 0x3C, 0xD1, 0x29, 0xA7, 0xE9, 0xAA, 0x90, 0x54, 0xA7, 0x9A, 0xBE, 0x3D, 0x52, 0x5A, 0x9D, 0x66, 0xC5, 0x51, 0x49, 0x6B, 0x74, 0xDA, 0x95, 0x46, 0x30, 0xA2, 0xD1, 0xE8, 0x66, 0x2E, 0xE4, 0xCA, 0xCA, 0x6D, 0x58, 0x21, 0x89, 0x3A, 0x23, 0x87, 0x21, 0x73, 0xB5, 0x71, 0x4D, 0x6A, 0x86, 0x20, 0x2C, 0xCE, 0xCD, 0xC9, 0xFF, 0x41}; const uint8_t spACORN[] PROGMEM = {0x23, 0x9B, 0x35, 0x85, 0xD3, 0x96, 0x9C, 0x64, 0xD6, 0x12, 0x0A, 0x5F, 0x7C, 0xA2, 0x95, 0xD6, 0x30, 0x6C, 0xF1, 0x89, 0x56, 0x18, 0x86, 0xCC, 0x45, 0x2B, 0x5A, 0xA1, 0x11, 0x2B, 0x1B, 0xB7, 0x68, 0x34, 0x06, 0xCF, 0x9E, 0x94, 0xB2, 0x91, 0x19, 0x32, 0xAB, 0x96, 0x2A, 0x84, 0x72, 0x77, 0x11, 0xD9, 0x00, 0x0A, 0x08, 0x51, 0xC9, 0x02, 0x25, 0x8F, 0x6D, 0x54, 0x4D, 0x66, 0xB6, 0x22, 0x86, 0x09, 0x33, 0xDA, 0xD5, 0xDA, 0xE8, 0x2A, 0xD3, 0xB0, 0x4F, 0xEB, 0x92, 0xA9, 0xCA, 0xA0, 0xBC, 0x6D, 0x48, 0xA6, 0x2A, 0x83, 0xF2, 0x95, 0x29, 0xD9, 0xEC, 0x34, 0xEC, 0x9B, 0xE6, 0x90, 0xAA, 0x5D, 0x78, 0x73, 0x98, 0x63, 0xC9, 0x74, 0xD6, 0x57, 0x6E, 0x8E, 0xCB, 0x42, 0x6C, 0x66, 0xB9, 0x29, 0x0D, 0x4B, 0xE6, 0x8E, 0x1B, 0xC6, 0x94, 0x2C, 0x84, 0xA2, 0x73, 0x98, 0xB2, 0x71, 0x0B, 0xF0, 0xCC, 0x6E, 0x4E, 0x3A, 0xD4, 0xD8, 0xB3, 0xAA, 0xB9, 0x68, 0x33, 0x23, 0xD5, 0xF2, 0x25, 0x51, 0x15, 0x31, 0x41}; const uint8_t spCASSETTE[] PROGMEM = {0x06, 0x68, 0x86, 0x65, 0x84, 0x55, 0x8B, 0x74, 0xB9, 0xAD, 0x13, 0xB5, 0xEC, 0x1A, 0x16, 0x8D, 0x4F, 0xD6, 0xC3, 0x68, 0x98, 0xB4, 0x3A, 0x79, 0x77, 0xA5, 0x69, 0xB6, 0xBA, 0x14, 0xD5, 0xAB, 0xB9, 0x75, 0x29, 0x04, 0x2C, 0xA4, 0x86, 0x80, 0x83, 0x23, 0x10, 0x70, 0x99, 0x3B, 0x03, 0x3E, 0xCB, 0x64, 0xC0, 0x67, 0x91, 0x02, 0xB8, 0x2A, 0x42, 0x01, 0x4B, 0x95, 0x2D, 0xB7, 0x59, 0x97, 0xD2, 0x58, 0x7C, 0xA2, 0xEE, 0x52, 0xC2, 0x7D, 0xF1, 0xC9, 0xBA, 0x2F, 0x09, 0xB7, 0xD5, 0xA7, 0xEA, 0x3E, 0x25, 0xDC, 0x57, 0xA7, 0xA6, 0x19, 0x93, 0x8A, 0x98, 0x89, 0x1A, 0xA1, 0xDC, 0x5D, 0x44, 0x36, 0x80, 0x00, 0xAE, 0x48, 0x93, 0x00, 0x02, 0xAA, 0x6F, 0xF8, 0x25, 0x51, 0x15, 0x61, 0x41, 0x25, 0x41, 0x09, 0x61}; const uint8_t spCOMPUTER[] PROGMEM = {0x06, 0x28, 0x29, 0x68, 0x44, 0x29, 0xAA, 0xA6, 0xD6, 0xEC, 0x15, 0xE7, 0x9C, 0xE6, 0x64, 0xAB, 0x5A, 0x9E, 0xBD, 0x96, 0x41, 0xB6, 0x0D, 0x79, 0xB2, 0xDC, 0x48, 0xDD, 0xCD, 0x94, 0x49, 0x53, 0x15, 0x7B, 0x12, 0x54, 0x09, 0xE5, 0xEE, 0x22, 0xB2, 0x81, 0x01, 0xD5, 0x86, 0x97, 0xA0, 0x47, 0x22, 0xCF, 0xAA, 0xDC, 0xFC, 0x26, 0x8D, 0xB2, 0x7D, 0xF5, 0xF2, 0x33, 0x6D, 0xCD, 0xB0, 0xD7, 0x3B, 0xE8, 0x11, 0x2A, 0x84, 0x72, 0x77, 0x11, 0xD9, 0xA0, 0x80, 0x6D, 0x35, 0x1D, 0xB0, 0x89, 0xFB, 0x48, 0x8A, 0x35, 0x75, 0xED, 0xDA, 0xAB, 0xAA, 0xDE, 0x2D, 0x24, 0x57, 0xAF, 0xB6, 0xF9, 0xB6, 0x14, 0x5D, 0x5D, 0xA6, 0x52, 0xD3, 0x5C, 0x73, 0xB6, 0xDB, 0xB3, 0x4F, 0x4F, 0x89, 0x31, 0xFF, 0x15, 0x61, 0x51, 0x25, 0x25, 0x79, 0x61}; const uint8_t spFILE[] PROGMEM = {0x08, 0xE8, 0xD2, 0x95, 0x00, 0x4D, 0xA7, 0x09, 0xA0, 0xC8, 0xF0, 0xE6, 0xE5, 0x54, 0x9E, 0x4A, 0x8F, 0x4E, 0x50, 0xFC, 0x95, 0xB9, 0x36, 0xB8, 0xE1, 0x89, 0xAA, 0xB9, 0x52, 0xF3, 0x86, 0x27, 0x6E, 0xFA, 0xDA, 0xCD, 0x5A, 0x9E, 0xB4, 0xEA, 0x6B, 0x77, 0x6B, 0x79, 0x8A, 0xA6, 0xB7, 0x32, 0xA4, 0xD3, 0xA9, 0xBA, 0xDD, 0xC8, 0x94, 0x55, 0xA7, 0xEB, 0xA1, 0x3D, 0x83, 0x17, 0x9F, 0xBE, 0x87, 0x90, 0x08, 0x5B, 0x3C, 0x86, 0xEE, 0x4C, 0xB2, 0x6C, 0x71, 0x99, 0x8A, 0x97, 0x48, 0xAF, 0xD9, 0x61, 0xCE, 0x4E, 0x2B, 0xB4, 0xE6, 0x84, 0x25, 0x79, 0xCF, 0x22, 0x5F, 0xED, 0x67, 0x33, 0x85, 0xEE, 0x66, 0xD2, 0x8D, 0xDD, 0x18, 0x62, 0x64, 0x52, 0xAC, 0xB2, 0xE3, 0xFF, 0x15, 0x65, 0x25, 0x49, 0x31}; const uint8_t spFROM[] PROGMEM = {0x08, 0xE8, 0xDA, 0x84, 0x02, 0x0A, 0x68, 0x26, 0x54, 0x03, 0xAE, 0x88, 0x83, 0x2A, 0xC4, 0x73, 0x97, 0x2A, 0x2D, 0x8D, 0x90, 0xC8, 0xBD, 0xEA, 0x1C, 0xAD, 0x22, 0xA8, 0xF7, 0x69, 0xB2, 0xAF, 0x8A, 0xA4, 0x3E, 0xA7, 0xCD, 0xBE, 0x2A, 0x12, 0xF7, 0x9C, 0x2E, 0x9B, 0x6D, 0x0B, 0xEA, 0x72, 0xFA, 0x6C, 0x6E, 0x34, 0xB8, 0xF5, 0xEA, 0xB3, 0xBE, 0xB5, 0xE0, 0xD6, 0xA3, 0xCF, 0x7A, 0x5A, 0x43, 0x3D, 0xB7, 0x2E, 0xAB, 0xB6, 0x14, 0x52, 0x5D, 0xDA, 0x24, 0x5A, 0x43, 0x58, 0x4B, 0x6E, 0x43, 0x13, 0x9D, 0x85, 0x91, 0xB6, 0xF1, 0xCD, 0xFF, 0x71}; const uint8_t spILLEGAL[] PROGMEM = {0x25, 0x19, 0x4C, 0xA9, 0x6F, 0x42, 0xF7, 0x2C, 0x67, 0x21, 0x5F, 0x20, 0x38, 0xC3, 0x1E, 0x96, 0xE4, 0x70, 0x65, 0x4B, 0x5F, 0xDD, 0xA2, 0x43, 0x85, 0xAD, 0xA2, 0xF5, 0x08, 0xB6, 0x36, 0xD0, 0xD6, 0x26, 0x2B, 0x9A, 0xD6, 0x40, 0xBB, 0xAA, 0xAC, 0x64, 0x79, 0x03, 0xDD, 0xAE, 0x3D, 0xB2, 0x99, 0x08, 0x6A, 0xBA, 0x72, 0xA9, 0x56, 0x37, 0xE0, 0xE9, 0x46, 0xA6, 0x5A, 0xDD, 0x81, 0xAA, 0x67, 0x21, 0x50, 0x04, 0x77, 0x11, 0x91, 0x0D, 0xAE, 0x28, 0xA9, 0xC1, 0xD4, 0x6C, 0x97, 0x36, 0xC7, 0x46, 0xF7, 0x48, 0x34, 0xFA, 0xAA, 0xC3, 0x4A, 0x7D, 0xF1, 0x18, 0xB2, 0x8F, 0x0C, 0xCE, 0x35, 0x65, 0x8A, 0xB1, 0xDC, 0x39, 0x5B, 0x87, 0x39, 0x94, 0x72, 0xE3, 0x5E, 0x1C, 0xA6, 0x10, 0xDB, 0x83, 0xB2, 0xAB, 0x1B, 0xA3, 0x1B, 0x6B, 0xB4, 0xB5, 0x7E, 0xF8, 0x5A, 0x39, 0x49}; const uint8_t spIS[] PROGMEM = {0xC9, 0x5F, 0x3E, 0x90, 0xB2, 0x17, 0xDF, 0xE0, 0x04, 0xDB, 0x04, 0x72, 0xF5, 0xA2, 0x13, 0x6E, 0x1D, 0xC8, 0xD5, 0x8B, 0x4E, 0xB4, 0x5C, 0x23, 0x65, 0x2F, 0x3A, 0xE9, 0x76, 0x85, 0x1C, 0xB5, 0xE8, 0x94, 0x33, 0x24, 0x89, 0xD6, 0xA2, 0xD5, 0xCD, 0xD4, 0x24, 0x54, 0x8B, 0xC6, 0xD8, 0x0D, 0x4B, 0xF8, 0xD6, 0x29, 0x63, 0xE2, 0x6E, 0x9D, 0x1D, 0x3B, 0x8F, 0x66, 0x3C, 0xD0, 0xCD, 0xA3, 0x12, 0xDA, 0x89, 0x01, 0x13, 0xB0, 0x23, 0xE0, 0x61, 0x76, 0x04, 0x7C, 0x4A, 0xFA, 0x29}; const uint8_t spNEGATIVE[] PROGMEM = {0x26, 0x2E, 0x4C, 0x24, 0xCC, 0x13, 0xC5, 0x32, 0x14, 0x49, 0xD0, 0x9C, 0xA4, 0x9B, 0x92, 0x25, 0xC9, 0x33, 0x9C, 0x6E, 0x46, 0x32, 0x94, 0x91, 0x7B, 0x2C, 0x3E, 0xD1, 0x74, 0x21, 0x6E, 0xD1, 0xF8, 0x84, 0xCB, 0x26, 0x9B, 0x7B, 0xE3, 0x13, 0x4C, 0x93, 0xE8, 0x9D, 0xAB, 0x46, 0x30, 0x4A, 0x41, 0x44, 0xCE, 0x22, 0x49, 0xD7, 0x06, 0x16, 0xB5, 0x7A, 0x64, 0xDD, 0x15, 0x87, 0x8A, 0xE2, 0x95, 0x75, 0xA3, 0xD0, 0x13, 0xB5, 0x56, 0xDA, 0x94, 0x70, 0x75, 0xD4, 0x26, 0x9D, 0x50, 0xEE, 0x2E, 0x22, 0x1B, 0x0C, 0xB0, 0xA8, 0x85, 0x03, 0x16, 0x0B, 0x0D, 0xED, 0x16, 0x4E, 0x5A, 0x16, 0xBB, 0xB4, 0xC3, 0x2A, 0xA5, 0x57, 0x9D, 0x32, 0x74, 0x27, 0x1C, 0x59, 0x73, 0xC2, 0xD2, 0x8D, 0x70, 0x65, 0xCE, 0x76, 0x4B, 0x33, 0x22, 0xE5, 0x39, 0xCB, 0x2D, 0xD5, 0x93, 0xA5, 0xD5, 0x2C, 0x33, 0x67, 0x23, 0x5A, 0x5A, 0x35, 0xC5, 0x5C, 0x55, 0x88, 0xA9, 0x35, 0x36, 0xF3, 0x70, 0xA9, 0xA9, 0xAA, 0x98, 0x00, 0x4D, 0x9B, 0xFC, 0x75, 0x51, 0x39}; const uint8_t spNO[] PROGMEM = {0xAC, 0xEF, 0xCC, 0xD9, 0x25, 0x6C, 0xBB, 0xB6, 0x50, 0xD1, 0xC7, 0x74, 0x17, 0x9A, 0x42, 0xD9, 0x1E, 0xD3, 0x5D, 0xAA, 0x2B, 0x51, 0x7D, 0x2C, 0x77, 0x29, 0xAF, 0xC4, 0xF4, 0x31, 0x93, 0xB7, 0xAC, 0x81, 0xE4, 0x63, 0xAD, 0x7F, 0xD2, 0x2E, 0x5B, 0x4D, 0xBC, 0xD1, 0x89, 0x9B, 0x6E, 0x33, 0xF5, 0x4D, 0x27, 0x6B, 0x26, 0x3D, 0xD8, 0x56, 0x9F, 0xA2, 0xEA, 0x0E, 0x53, 0xDB, 0x74, 0xAA, 0xA6, 0x32, 0x42, 0xE5, 0xD3, 0xEE, 0xC7, 0xD8, 0x44, 0xA7, 0x19, 0x7E, 0x0E, 0x53, 0x32, 0xE3, 0x6C, 0xF6, 0x28, 0x8C, 0xC1, 0xB7, 0x19, 0xE5, 0x9C, 0x38, 0xDA, 0xF1, 0xFF, 0x15, 0x79, 0x39}; const uint8_t spNUMBER[] PROGMEM = {0xA6, 0x0A, 0x42, 0x72, 0xB9, 0xDC, 0x84, 0x32, 0x0A, 0x89, 0xA3, 0x72, 0x13, 0xF2, 0xC0, 0x35, 0x0E, 0xDB, 0x4D, 0x49, 0x13, 0x57, 0x3D, 0xAA, 0xA4, 0x27, 0xAE, 0xAE, 0xC3, 0x25, 0x12, 0x9F, 0xA8, 0xBA, 0x2D, 0x37, 0x4F, 0x74, 0x82, 0x62, 0xAF, 0xC3, 0x3C, 0xD5, 0xF1, 0x8B, 0xBD, 0x0E, 0xB5, 0x44, 0xCB, 0xAF, 0x72, 0xAD, 0x91, 0xDC, 0xAC, 0xA0, 0xCA, 0xB1, 0x46, 0x4A, 0x33, 0x82, 0x6C, 0x46, 0x03, 0xA4, 0x4B, 0x8A, 0xB2, 0x0C, 0x2B, 0x90, 0x2D, 0x2A, 0x33, 0xD2, 0xB2, 0xC4, 0x3E, 0x8B, 0xCA, 0xCA, 0xD2, 0x10, 0x5F, 0xD5, 0xAA, 0xE2, 0xDB, 0x8C, 0x65, 0x53, 0xAB, 0x73, 0x09, 0x57, 0xAE, 0xDB, 0x6D, 0x28, 0xB1, 0xDC, 0xC5, 0x1F, 0xB7, 0x29, 0x87, 0xF0, 0xD0, 0xBE, 0x94, 0xE7, 0xB0, 0x64, 0x1F, 0x16, 0x5A, 0x53, 0xEC, 0xFA, 0x79}; const uint8_t spPARAMETER[] PROGMEM = {0x04, 0xD0, 0xA2, 0x3D, 0xA5, 0xC5, 0xA7, 0x9B, 0x6B, 0xCD, 0x91, 0xE6, 0x21, 0x85, 0xE3, 0x71, 0x7B, 0xDA, 0xB2, 0x1C, 0xB8, 0x38, 0x3C, 0x6E, 0xCA, 0xD2, 0xC5, 0x32, 0xF5, 0xB6, 0x31, 0x6B, 0x69, 0x39, 0x6C, 0x61, 0xE9, 0x65, 0x45, 0xA5, 0x5B, 0x71, 0x45, 0xA3, 0x13, 0xD4, 0x9C, 0x11, 0x9A, 0x8D, 0x4E, 0xD0, 0xEC, 0x46, 0xBA, 0xD5, 0x5A, 0x49, 0x89, 0x9E, 0x42, 0x39, 0xB9, 0xE4, 0xC9, 0x49, 0x31, 0x74, 0xBB, 0x92, 0x67, 0x23, 0xA5, 0x50, 0xDD, 0x4A, 0x9E, 0x8C, 0xB4, 0x42, 0xAE, 0x3B, 0x65, 0x2D, 0x5E, 0xC6, 0x3E, 0xA5, 0xB5, 0xD5, 0x69, 0x28, 0xC7, 0x62, 0xD2, 0x0A, 0xE5, 0xEE, 0x22, 0xB2, 0x41, 0x01, 0x9B, 0x65, 0x1A, 0xA0, 0xE0, 0xF0, 0xD6, 0x24, 0xEF, 0x96, 0xDA, 0xB5, 0xCE, 0xD0, 0x82, 0x7B, 0xAA, 0xAE, 0x1E, 0x53, 0x4D, 0x15, 0xA1, 0xF2, 0xB8, 0x8D, 0x25, 0x57, 0x84, 0xEA, 0xE2, 0x32, 0x96, 0x9C, 0x11, 0xEC, 0x93, 0xFF, 0x51, 0x61, 0x39, 0x51, 0x05}; const uint8_t spPROGRAMME[] PROGMEM = {0x0C, 0x48, 0x2E, 0x95, 0x03, 0x2E, 0x0A, 0x8D, 0x3D, 0xDA, 0x13, 0xD5, 0x68, 0xF9, 0xA9, 0x73, 0x68, 0xC7, 0x94, 0x13, 0x94, 0x62, 0xA9, 0xC6, 0xAB, 0x4F, 0x50, 0x63, 0x84, 0x19, 0xAD, 0x3E, 0x41, 0x0B, 0xEE, 0x6E, 0xB8, 0xE9, 0x04, 0xD5, 0x69, 0x84, 0xF0, 0xAB, 0x11, 0x66, 0xE7, 0x66, 0x22, 0xAF, 0x5C, 0x14, 0xA3, 0x2B, 0xAB, 0x2E, 0x34, 0xA9, 0x54, 0x19, 0x1D, 0x96, 0x4A, 0xE5, 0x3E, 0xAB, 0xB8, 0x44, 0x9C, 0x50, 0xA7, 0x66, 0x21, 0xA4, 0x71, 0x52, 0x95, 0x33, 0x17, 0x66, 0xA7, 0x1D, 0x75, 0x69, 0x1A, 0x94, 0xE9, 0x75, 0xB5, 0xA5, 0xA9, 0x9B, 0xE7, 0x9A, 0x33, 0xB4, 0xD8, 0xE1, 0xC1, 0x5D, 0xCE, 0xD8, 0xFC, 0x44, 0x24, 0x75, 0x3E, 0x53, 0x8B, 0xE5, 0x19, 0xBC, 0x78, 0xCC, 0x35, 0x76, 0x64, 0xF2, 0xED, 0x36, 0xD7, 0x54, 0x51, 0xCE, 0xB3, 0xEB, 0x1C, 0xE6, 0xEC, 0x34, 0x0C, 0xAC, 0x89, 0x9F, 0xED, 0xF2, 0x45}; const uint8_t spTHIS[] PROGMEM = {0xAA, 0xF2, 0xD2, 0x6C, 0xA4, 0x2A, 0xAA, 0xCA, 0x4B, 0xB5, 0xB6, 0x6C, 0x18, 0xCA, 0xAA, 0x94, 0x53, 0xB4, 0xF1, 0x8A, 0x3B, 0x0B, 0xEC, 0xD2, 0x45, 0x27, 0xEC, 0xDC, 0x71, 0xCA, 0x67, 0x9D, 0x68, 0x48, 0xC7, 0xE9, 0x58, 0x74, 0xD2, 0x69, 0x13, 0x22, 0x63, 0xF1, 0xA9, 0x86, 0x35, 0xEC, 0xCC, 0xC5, 0xAD, 0xEE, 0x5E, 0x68, 0xE4, 0xE2, 0x2A, 0x20, 0xE3, 0x10, 0x01, 0x2C, 0x62, 0x66, 0x80, 0xC7, 0xDC, 0x15, 0xF0, 0x98, 0x94, 0x00, 0x3E, 0xB7, 0x10, 0xC0, 0xA3, 0x96, 0x0C, 0xF8, 0x42, 0x9D, 0x01, 0xDF, 0x09, 0x33, 0xE0, 0x1B, 0x31, 0x02, 0x7C, 0xA7, 0x42, 0x80, 0x6F, 0x94, 0x10, 0xF0, 0x95, 0x39, 0x02, 0x1A, 0x0E, 0xFD, 0x51, 0x59, 0x49, 0x15}; const uint8_t spYOUR[] PROGMEM = {0xA1, 0x69, 0x86, 0xD1, 0xA7, 0x2B, 0xE5, 0x3A, 0x55, 0x2D, 0x08, 0xDA, 0xC4, 0xCA, 0x56, 0x16, 0xA9, 0x5C, 0xA3, 0x3D, 0x4F, 0x99, 0x44, 0x59, 0x85, 0xF4, 0x5A, 0x65, 0x74, 0xE3, 0xA9, 0xDC, 0xFB, 0x96, 0xA7, 0x4A, 0x7A, 0xA2, 0x8C, 0x72, 0x9F, 0x2A, 0xDA, 0xC9, 0x54, 0xCE, 0xBD, 0xEA, 0x10, 0x26, 0x42, 0xB4, 0xF7, 0xAA, 0xA3, 0xDF, 0x08, 0xD1, 0xDE, 0xA3, 0x8E, 0x6E, 0x23, 0x44, 0x73, 0x8F, 0x3A, 0x9A, 0x8D, 0x54, 0xC9, 0x35, 0xEA, 0xE4, 0xBA, 0xD2, 0xB0, 0xF7, 0x68, 0x92, 0xDF, 0x74, 0x91, 0x9C, 0xA5, 0x89, 0xBD, 0xD3, 0x48, 0x3B, 0xF8, 0xF6, 0xFF, 0x2D}; const uint8_t * indexArray [] {spTHIS, spIS, spNO, spNEGATIVE, spPARAMETER, spPROGRAMME, spNUMBER, spILLEGAL, spCASSETTE, spPAUSE1, spPAUSE2}; #endif Talkie voice; #define qBlink() (digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) )) // This toggles the Teensy 3.2 Builtin LED pin 13 void setup() { while (!Serial && 5000 > millis()); Serial.println(""\\nSetting up""); pinMode(LED_BUILTIN, OUTPUT); qBlink(); pinMode(5, OUTPUT); digitalWrite(5, HIGH);//Enable Amplified PROP shield delay(10); voice.say( spACORN ); // This orignal function when used blocks until all queued sounds have played } int wordarray[] {0, 1, 2, 3, 6, 9, 0, 1, 2, 3, 4, 9, 7, 8, 10, 7, 8, 10}; int wordarraysize = sizeof (wordarray) / 4; void loop() { arrayInterface (wordarray, wordarraysize); uint8_t xx = voice.active(), yy; while ( (yy = voice.active()) > 15 ) { if ( xx != yy ) { qBlink(); xx = yy; Serial.print( ""."" ); } delay (5); } } uint8_t aI_cnt = 0; bool waitAcorn = true; void arrayInterface (int * wordArray, int wordArraySize) { Serial.print( ""Array Adding: Active="" ); Serial.print( voice.active() ); if ( 2 < ++aI_cnt ) { if ( waitAcorn ) voice.say( spACORN ); // This orignal function when used blocks until all queued sounds have played else voice.sayQ( 0 ); // Empty queue to test code waitAcorn = !waitAcorn; aI_cnt = 0; Serial.print( "" EMPTY QUEUE: "" ); while ( voice.active() ) Serial.print( ""^"" ); // Allow silence to come, a PAUSE is played to turn off synthesis Serial.print( "" :: Active="" ); Serial.println( voice.active() ); delay(1000); // Sweet Silence! } for (uint8_t i = 0; i < wordArraySize; i++) { qBlink(); Serial.print( "" Q="" ); Serial.print( voice.sayQ (indexArray[wordArray[i]]) ); } Serial.print( "":: Array Added: Active="" ); Serial.println( voice.active() ); } ",12209,True,3609.519993145927,median " float arr[1000] = {-194.7293734,-228.7205774,-241.1012313,-274.3287909,-258.4301079,-244.645154,-267.9013166,-246.6050094,-242.4746091,-262.6250468,-238.1975294,-221.7994023,-235.1426569,-242.8932457,-247.5878307,-218.1253556,-237.4591843,-229.5916635,-223.2165116,-205.5867448,-237.778965,-201.5138842,-197.2634399,-218.4651907,-226.9375835,-199.6628832,-240.0012574,-222.3782983,-204.4144371,-223.0221878,-215.5507942,-204.6482212,-222.0696607,-221.5406628,-233.7575657,-207.3931737,-213.1469816,-256.4251654,-248.644363,-238.4953193,-243.4652311,-206.2320692,-236.7459641,-259.4415915,-262.9389297,-203.4735393,-189.4905604,-150.4684017,-144.7423112,-108.8224312,-50.3437065,-42.48394314,-9.313541237,2.282074465,60.61253926,58.58308399,43.99462444,45.23633906,5.781279205,12.42652926,-6.064931748,-37.43559123,-73.84242875,-54.06086811,-103.7524177,-137.3311552,-154.8714495,-145.8669742,-163.164842,-213.1969349,-188.3772464,-180.3718886,-190.6680207,-182.8992434,-208.5555581,-227.0501279,-223.9086697,-203.6115081,-225.0068371,-249.7099086,-270.430942,-247.9083576,-221.4759624,-271.2626802,-256.0717227,-240.2203343,-211.4446914,-201.1415653,-198.7572259,-207.5827723,-233.1128712,-178.8934831,-190.8283584,-189.2946002,-194.2929802,-194.1054383,-198.4310706,-188.7845077,-210.9275443,-197.1196525,-185.5335141,-233.2417639,-222.0488999,-223.1010373,-237.2142258,-227.1844383,-224.8237316,-227.1231129,-225.6844486,-188.4712173,-212.9535228,-238.0921159,-246.9258376,-229.913049,-268.1904491,-257.5908872,-235.2382047,-196.0882206,-174.4861493,-144.3613337,-121.5747288,-89.66203045,-65.1663977,-40.2986104,24.53192862,53.25129558,69.48466659,46.26462118,54.09895211,16.29032903,5.228029817,-20.74642039,-40.2574299,-80.06059097,-85.14764361,-101.1609156,-130.8264169,-110.7740027,-172.6491102,-190.6556797,-150.7838331,-178.8338841,-209.2648121,-206.1178525,-210.4814517,-214.1269824,-222.1505692,-230.3364431,-229.1243872,-251.8032432,-250.9595267,-235.0004413,-232.6200981,-235.0745491,-204.5328354,-212.59826,-211.1507703,-207.7587466,-234.7991683,-192.0878764,-222.6905045,-202.4615363,-204.2220413,-225.1243183,-216.3029391,-191.6984828,-185.4856592,-182.9473139,-177.8998202,-183.2392524,-208.2415824,-212.0286206,-169.3541698,-210.5412575,-231.0118891,-249.5577641,-208.3705454,-204.5434279,-214.5228903,-228.7358685,-241.2009769,-235.1017173,-218.3852069,-213.7527006,-227.4889893,-223.6288157,-228.9916498,-207.5219466,-190.493554,-154.5865093,-116.0024558,-63.17772296,-51.8002069,-7.546116619,-14.39880211,32.98183203,63.20752025,64.41857886,59.71544681,32.10101235,-17.70912436,-7.631012085,-51.8776306,-55.95033776,-69.06182035,-111.8571389,-104.4989893,-126.9390643,-163.5667602,-151.7080535,-187.5999,-219.4481594,-206.2992725,-207.0990868,-222.7266564,-222.5792183,-210.542429,-238.9541618,-240.7254286,-243.3493466,-258.2009352,-241.234409,-225.2101582,-243.213891,-246.0856964,-238.4527187,-219.1768319,-227.3266325,-213.8079106,-225.8201055,-222.0041483,-210.3261814,-205.7475302,-206.0668604,-222.6182256,-200.8885429,-206.1334318,-218.22569,-186.0937162,-226.4895114,-221.4281832,-191.3548204,-200.6006756,-211.0800005,-213.9486458,-203.0680747,-190.9419471,-221.7923004,-201.7018474,-215.4770913,-246.7618175,-228.9328285,-232.0936364,-240.3352165,-230.6981949,-224.9568539,-199.9779163,-212.2616482,-173.7521828,-176.9408848,-119.7392093,-103.6798485,-89.81041289,-67.57551054,-10.67998311,9.749239444,32.13123786,16.27966092,34.40986469,15.91874671,13.97345217,3.402896188,5.590464863,-45.38323666,-65.65860722,-95.44303348,-98.91854576,-98.15341909,-131.3000653,-135.7003976,-192.0801184,-189.0861504,-164.4095092,-156.1325791,-193.5525884,-184.7028529,-229.651036,-223.1013635,-187.5059762,-190.6580371,-168.5168179,-171.8102238,-214.0656828,-206.2208193,-183.5450934,-190.8589567,-182.7666905,-178.6198467,-180.509724,-175.642094,-172.8580103,-167.8244064,-196.979952,-186.2138905,-168.0834867,-167.8570434,-169.5713098,-203.7577476,-173.624489,-189.6457655,-186.161929,-178.6140261,-186.2081834,-203.8580852,-174.0582505,-218.2507178,-214.4790238,-204.6601377,-193.1434548,-234.4722219,-246.5686757,-185.7564607,-217.201683,-225.3845411,-179.1924198,-162.6436219,-164.680583,-145.8246757,-131.3135381,-107.2424073,-96.60282967,-66.09455088,-39.12388801,-10.4655626,18.43708564,25.39622555,19.70363064,29.50104014,24.65377861,9.065353235,7.800289078,-9.481016435,-32.44722798,-8.425000643,-42.09591755,-84.85431968,-65.23416939,-83.26647469,-88.61872226,-94.31984595,-135.5122422,-96.24493259,-130.6101087,-164.2159095,-163.8014595,-161.2911478,-146.1628098,-143.8038188,-165.9456815,-162.9975622,-186.5376742,-163.928964,-208.4947079,-163.6350835,-143.1139405,-179.8374228,-161.6782426,-170.9720761,-153.9010512,-159.7300558,-169.2543883,-125.3209033,-166.0480624,-190.0647723,-164.8502403,-176.244536,-176.7593197,-141.0916485,-191.6808102,-175.8716194,-179.0655926,-213.334729,-157.4868359,-146.8128336,-176.2284353,-192.1630524,-171.753249,-184.7194487,-190.6521523,-176.2414561,-225.7463566,-181.2578951,-170.1268263,-168.2026363,-136.5319892,-137.8841734,-97.44384241,-96.24254779,-62.94615628,-3.930067195,8.360604156,30.9113395,57.224556,60.38299552,71.4775984,37.93360244,30.25482625,-10.96794785,43.9548974,8.275507057,-5.505276016,-42.18418284,-41.53852257,-38.19401138,-9.988135433,-73.23986505,-82.37523151,-92.49459774,-119.2384522,-117.1943554,-142.7418834,-134.5810715,-155.6807706,-170.4483921,-162.0791537,-121.3606511,-135.2956761,-158.4504113,-177.587806,-191.5341681,-170.2470434,-164.0494494,-169.9082233,-152.4201734,-138.1347796,-151.0786031,-145.2001118,-153.4814199,-183.4935886,-153.946237,-152.2658373,-185.4743658,-160.4133792,-149.8470445,-199.958043,-173.5824841,-170.6156591,-165.6102076,-151.9477062,-183.3851466,-189.1947611,-190.5126042,-178.451038,-232.1975489,-209.617863,-181.0558565,-195.2786295,-195.4491857,-191.063771,-209.1130301,-241.5632851,-171.2830079,-205.2558494,-199.4252494,-171.0996064,-135.2528671,-120.0398883,-86.35313349,-58.75543608,-31.63496181,15.61749277,21.53029518,52.80680223,37.94167304,38.60237186,39.1940536,41.07783215,29.45936977,20.05054327,-8.013389731,16.79412285,-7.969302978,-59.9582873,-64.72356939,-88.95088436,-76.4041469,-98.53033607,-99.11610762,-67.75720734,-95.97143121,-96.68185726,-126.6121091,-105.5375604,-102.3703775,-133.2714074,-131.1305721,-131.4514406,-111.0579924,-136.3332306,-117.5234052,-120.694585,-82.60431528,-108.3972289,-101.9762479,-132.7979261,-94.75065491,-124.2930794,-110.4378804,-138.6506348,-123.5289038,-131.5299734,-132.8438586,-122.8304073,-120.7581867,-100.7386637,-149.5780713,-161.4928199,-157.7717813,-152.1336241,-145.7094938,-159.1026831,-102.0334835,-160.1400191,-153.7176046,-171.7580939,-157.3400312,-166.8574939,-194.2379129,-177.1002617,-134.1092309,-161.9593411,-141.7789387,-142.6961662,-161.7180284,-108.7803143,-101.1193168,-118.6115166,-91.42120803,-70.22670377,-62.88077846,-31.97668856,-6.215203813,-5.233143328,-44.56281787,-21.68037513,-45.79143414,8.989530097,-33.15079614,-21.48894064,-33.49492773,-29.2493369,-41.52894652,-75.47306377,-68.38486974,-74.77386162,-115.0927022,-70.91988867,-114.6172291,-102.9498024,-106.6596287,-125.8687341,-130.0565056,-112.7060226,-114.066016,-144.0590352,-139.9082732,-79.15096988,-122.8808231,-123.1155945,-106.5493839,-95.2442839,-84.61336782,-91.78075471,-81.91146491,-86.01301159,-74.34770941,-57.81595852,-105.2189274,-89.36945358,-78.90219237,-86.36036927,-87.60490458,-82.61198278,-90.23936768,-111.8892024,-119.0173669,-99.10710747,-72.20035121,-105.0562126,-97.31112661,-108.4746315,-124.6542035,-85.76581803,-92.86040155,-109.1004347,-121.3621172,-100.9174347,-142.4731285,-130.0011933,-119.4201213,-139.370153,-121.6220649,-87.52025165,-60.4602173,-39.90009249,-14.47723731,28.08235515,47.0560563,120.2148031,107.0469654,115.7527706,136.7052646,118.2185203,121.9294065,84.74510753,96.10309817,64.47610982,38.05916544,13.27418373,-32.23912655,-36.78391247,-25.11066914,-61.15777398,-98.29203929,-68.59806904,-99.0657737,-87.29964824,-102.3767133,-125.4705793,-135.8394233,-148.0103686,-121.5531103,-140.2008691,-127.8816079,-142.15461,-130.3117346,-142.8451429,-136.1119731,-128.1150761,-181.7599915,-135.3870371,-129.2560956,-137.0686169,-112.1668674,-118.3244947,-88.19945937,-115.5759744,-137.0163441,-85.11711793,-121.9576238,-140.4228662,-144.3353992,-127.470473,-121.8499143,-155.2375142,-141.0241809,-137.4376575,-116.4224465,-156.3159578,-159.9703768,-153.0455255,-116.8784562,-158.7746494,-159.2404272,-146.5092559,-145.9024473,-135.9718693,-149.2638179,-136.4628664,-153.8788251,-138.2996744,-129.7350719,-122.8989196,-69.96569523,-42.6188645,-26.6727897,42.75270977,80.38748068,85.15990593,144.2246011,114.0285993,135.0663365,118.77368,108.4004485,79.29920395,53.47504442,51.4568911,15.51504004,2.820147023,-17.76931482,-29.5342018,-76.86515899,-93.52672611,-92.36201603,-106.8546262,-99.42868777,-128.2335362,-141.4652213,-149.7667769,-173.7089838,-162.7297406,-153.9823947,-157.7649799,-169.7695429,-136.117979,-190.0099192,-171.0138731,-153.8969602,-131.3825889,-132.4775054,-144.8328747,-119.4553937,-118.461819,-152.2870008,-123.99986,-109.9679708,-107.7218485,-134.425985,-108.5528276,-122.931492,-144.3043608,-123.9151892,-136.0427895,-138.2686626,-125.487269,-132.3539958,-138.2329971,-139.939367,-171.8562663,-119.2203833,-148.7311304,-130.8654556,-132.1708188,-140.651656,-146.8004431,-161.7175614,-141.8975887,-204.1681909,-181.4347946,-169.794193,-181.3817571,-163.1939391,-181.9440958,-141.4159902,-161.3779616,-142.8835639,-92.83279682,-87.82929402,-67.63583459,-45.72687899,-18.59988298,-23.8363,3.608611204,1.818248803,-8.739289403,-21.57494524,-41.33157434,-29.03713358,-20.99940689,-50.0813837,-21.99804201,-74.39428105,-76.39698718,-78.44490173,-98.33019493,-107.645843,-99.10440428,-124.3985889,-130.8573096,-163.2159422,-142.4553406,-159.944714,-148.9434037,-160.8869971,-184.5980749,-155.1405424,-146.5041614,-156.7679863,-182.9961263,-180.3384162,-141.9037962,-143.0601834,-164.0363091,-146.9603389,-152.7834731,-164.5475811,-127.676256,-157.8642206,-151.1628084,-166.7477876,-167.5465739,-154.2128082,-171.8941133,-168.0392262,-121.3123974,-145.018166,-204.3435584,-182.2026828,-149.4854941,-183.9677767,-183.512187,-166.1788482,-167.4555169,-173.1731897,-180.8263172,-170.8577042,-177.8208421,-180.3912373,-180.5553552,-195.928325,-196.1781535,-190.0243037,-184.3042068,-191.4410315,-151.0294216,-149.9720078,-127.1330296,-90.14556331,-34.01657424,-24.09053284,-19.20488983,10.32673427,26.05205325,15.75123511,41.96615392,14.59800579,-13.62332522,-21.03076268,-30.02105683,-41.17833452,-77.18028379,-96.99706135,-127.306131,-132.4580054,-134.9024561,-152.8904973,-176.0369535,-161.986251,-138.455779,-201.3283425,-208.3465867,-200.7438402,-205.9870668,-219.1445998,-192.2587361,-176.9577506,-210.0107858,-208.2073254,-174.0554183,-189.1968548,-168.2189224,-154.2706031,-126.5548643,-135.7245765,-173.113575,-139.4801769,-150.9201739,-157.1746172,-125.409453,-152.7137791,-170.3718494,-157.5132698,-166.5706996,-203.1650381,-182.003685,-160.8451871,-150.3803736,-156.9948784,-172.4977517,-201.7729783,-169.2198307,-186.9477502,-174.2955725,-174.2682879,-193.5521213,-164.0675421,-193.5597176,-180.4292896,-190.882491,-229.4133228,-207.9229962,-210.5044907,-176.0909394,-216.6674227,-143.3847579,-135.8177249,-94.8520075,-55.29308187,-8.596819711,7.964483205,28.48459718,44.78772264,17.27301549,25.115108,0.829013092,4.966635828,-32.97422792,-55.44387968,-38.01791022,-66.97019754,-80.10909905,-133.6043384,-122.9867923,-158.0198585,-168.7119192,-162.1761282,-193.2111663,-202.4715106,-215.1658819,-205.3750362,-182.2905731,-219.30705,-200.7479717,-204.8469231,-209.0812153,-211.6547947,-204.1270669,-226.8917176,-192.2647367,-192.0937077,-149.1202258,-178.2079718,-153.9820205,-160.0980568,-143.4038851,-160.9962075,-152.194965,-144.7864218,-152.6499076,-161.0921342,-146.3687844,-133.3138354,-157.2481451,-168.1529119,-177.2414936,-175.869606,-163.9159113,-167.8363622,-171.5562753,-176.8878957,-184.8272099,-173.231631,-189.1954342,-186.7880633,-198.419782,-198.4993576,-205.7931514,-225.0244529,-217.432668,-225.6304254,-208.4727153,-196.0858998,-179.7989551,-180.135508,-107.6521441,-84.49460718,-57.79385363,-5.432363826,-7.905866213,7.415821868,38.71482905,49.74463987,38.91135793,38.58460628,16.72865935,-6.29901565,-32.45669955,-70.16222148,-105.1041477,-100.6433214,-130.2641923,-128.9636693,-174.105794,-178.0473545,-205.6339688,-235.4556809,-201.4454861,-241.9226402,-217.5838268,-244.6654605,-264.975986,-235.3203644,-194.1459558,-224.5232334,-192.4564951,-196.1291018,-186.0265871,-162.9354431,-185.5400986,-178.1149615,-150.0574549,-160.1466649,-154.5837003,-137.2761693,-141.4914396,-123.2661691,-148.2682616,-144.4504403,-139.3705715,-155.2151228}; float x = 0; int num_of_data = 1000; void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: for (int i = 0; i< 1000; i++) { x = 0; // Moving Average if (i<8) {for(int k=0; k 0 #define FLEX_BETA #endif /* The c++ scanner is a mess. The FlexLexer.h header file relies on the * following macro. This is required in order to pass the c++-multiple-scanners * test in the regression suite. We get reports that it breaks inheritance. * We will address this in a future release of flex, or omit the C++ scanner * altogether. */ #define yyFlexLexer fsmyyFlexLexer /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ /* begin standard C++ headers. */ #include #include #include #include #include /* end standard C++ headers. */ #ifdef __cplusplus /* The ""const"" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning ""start processing a new file"". */ #define YY_NEW_FILE yyrestart( yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif extern int yyleng; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first ""n"" matched characters back to the input stream. */ #define yyless(n) \\ do \\ { \\ /* Undo effects of setting up yytext. */ \\ int yyless_macro_arg = (n); \\ YY_LESS_LINENO(yyless_macro_arg);\\ *yy_cp = (yy_hold_char); \\ YY_RESTORE_YY_MORE_OFFSET \\ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \\ YY_DO_BEFORE_ACTION; /* set up yytext again */ \\ } \\ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { std::istream* yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we ""own"" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an ""interactive"" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to ""new"" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * ""scanner state"". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \\ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \\ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] void *fsmyyalloc (yy_size_t ); void *fsmyyrealloc (void *,yy_size_t ); void fsmyyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \\ { \\ if ( ! YY_CURRENT_BUFFER ){ \\ yyensure_buffer_stack (); \\ YY_CURRENT_BUFFER_LVALUE = \\ yy_create_buffer( yyin, YY_BUF_SIZE ); \\ } \\ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \\ } #define yy_set_bol(at_bol) \\ { \\ if ( ! YY_CURRENT_BUFFER ){\\ yyensure_buffer_stack (); \\ YY_CURRENT_BUFFER_LVALUE = \\ yy_create_buffer( yyin, YY_BUF_SIZE ); \\ } \\ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \\ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ typedef unsigned char YY_CHAR; #define yytext_ptr yytext #define YY_INTERACTIVE #include /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \\ (yytext_ptr) = yy_bp; \\ yyleng = (size_t) (yy_cp - yy_bp); \\ (yy_hold_char) = *yy_cp; \\ *yy_cp = '\\0'; \\ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 25 #define YY_END_OF_BUFFER 26 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[61] = { 0, 0, 0, 26, 24, 1, 2, 24, 24, 11, 4, 5, 14, 24, 23, 23, 13, 12, 21, 21, 21, 21, 21, 21, 21, 21, 21, 6, 2, 0, 22, 0, 20, 23, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 18, 21, 15, 21, 16, 17, 21, 8, 21, 19, 9, 10, 21, 21, 7, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 5, 6, 1, 1, 1, 7, 8, 9, 1, 1, 10, 11, 1, 1, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 1, 1, 1, 15, 16, 7, 17, 18, 17, 17, 17, 17, 17, 17, 19, 17, 17, 20, 17, 21, 17, 22, 17, 23, 24, 17, 17, 17, 17, 17, 17, 17, 1, 1, 1, 1, 17, 1, 25, 17, 26, 17, 27, 17, 28, 17, 29, 17, 17, 30, 17, 31, 32, 17, 17, 33, 34, 35, 36, 17, 17, 17, 17, 17, 1, 37, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[38] = { 0, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 } ; static yyconst flex_int16_t yy_base[63] = { 0, 0, 0, 75, 76, 76, 76, 71, 68, 76, 76, 76, 76, 27, 76, 27, 76, 76, 0, 16, 41, 42, 45, 37, 41, 40, 31, 76, 76, 60, 76, 53, 76, 31, 0, 35, 30, 26, 26, 24, 24, 32, 21, 22, 76, 0, 24, 0, 18, 0, 0, 22, 0, 15, 0, 0, 0, 21, 11, 0, 76, 48, 43 } ; static yyconst flex_int16_t yy_def[63] = { 0, 60, 1, 60, 60, 60, 60, 60, 61, 60, 60, 60, 60, 60, 60, 60, 60, 60, 62, 62, 62, 62, 62, 62, 62, 62, 62, 60, 60, 61, 60, 60, 60, 60, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 60, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 0, 60, 60 } ; static yyconst flex_int16_t yy_nxt[114] = { 0, 4, 5, 6, 7, 8, 9, 4, 10, 11, 12, 13, 14, 15, 16, 4, 17, 18, 19, 20, 21, 22, 23, 24, 25, 18, 18, 18, 18, 18, 18, 18, 18, 18, 26, 18, 18, 27, 31, 33, 33, 35, 32, 33, 33, 34, 59, 58, 36, 29, 29, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 30, 43, 42, 41, 40, 39, 38, 37, 30, 28, 60, 3, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } ; static yyconst flex_int16_t yy_chk[114] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 13, 15, 15, 19, 13, 33, 33, 62, 58, 57, 19, 61, 61, 53, 51, 48, 46, 43, 42, 41, 40, 39, 38, 37, 36, 35, 31, 29, 26, 25, 24, 23, 22, 21, 20, 8, 7, 3, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } ; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 ""liblts_fsmlexer.ll"" #line 2 ""liblts_fsmlexer.ll"" // Author(s): Muck van Weerdenburg // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // /// \\file fsmlexer.ll #define YYSTYPE std::string #include #include // #include #include ""mcrl2/utilities/logger.h"" #include ""mcrl2/lts/lts.h"" #include ""liblts_fsmlexer.h"" #include ""liblts_fsmparser.h"" #include ""mcrl2/lts/detail/liblts_fsmparser.h"" //using namespace std; //fix for the broken cygwin versions of flex #ifdef __CYGWIN__ #include using std::cerr; using std::cin; using std::cout; #endif using namespace mcrl2::lts; //Global precondition: the aterm library has been initialised //external declarations int fsmyyparse(void); /* declared in fsmparser.cpp */ extern YYSTYPE fsmyylval; /* declared in fsmparser.cpp */ //global declarations, used by fsmparser.cpp int fsmyylex(void); /* lexer function */ void fsmyyerror(const char *s);/* error function */ //local declarations class concrete_fsm_lexer : public fsm_lexer, public fsmyyFlexLexer { public: concrete_fsm_lexer(void); /* constructor */ int yylex(void); /* the generated lexer function */ void yyerror(const char *s); /* error function */ bool parse_stream(std::istream &stream, lts_fsm_t &l); protected: void processId(); void processQuoted(); void processNumber(); }; //implement yylex in concrete_fsm_lexer instead of fsmyyFlexLexer //(this gets rid of global variables but is ugly in its own right) #define YY_DECL int concrete_fsm_lexer::yylex() int fsmyyFlexLexer::yylex(void) { return 1; } concrete_fsm_lexer *clexer = nullptr; /* lexer object, used by parse_stream */ fsm_lexer *fsm_lexer_obj = nullptr; /* lexer object, used by fsmparser */ int lineNo=1, posNo=1; extern void fsmyyerror(const char* s); void processId(); void processQuoted(); void processNumber(); #line 526 ""liblts_fsmlexer.cpp"" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for ""unistd.h"", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO #define ECHO LexerOutput( yytext, yyleng ) #endif /* Gets input and stuffs it into ""buf"". number of characters read, or YY_NULL, * is returned in ""result"". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \\ \\ if ( (result = LexerInput( (char *) buf, max_size )) < 0 ) \\ YY_FATAL_ERROR( ""input in flex scanner failed"" ); #endif /* No semi-colon after return; correct usage is to write ""yyterminate();"" - * we don't want an extra ';' after the ""return"" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) LexerError( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 #define YY_DECL int yyFlexLexer::yylex() #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \\ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; #line 77 ""liblts_fsmlexer.ll"" #line 634 ""liblts_fsmlexer.cpp"" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = & std::cin; if ( ! yyout ) yyout = & std::cout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE ); } yy_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 61 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 76 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 79 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); } YY_BREAK case 2: /* rule 2 can match eol */ YY_RULE_SETUP #line 80 ""liblts_fsmlexer.ll"" { lineNo++; posNo=1; return EOLN; } YY_BREAK case 3: YY_RULE_SETUP #line 81 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return SECSEP; } YY_BREAK case 4: YY_RULE_SETUP #line 82 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return LPAR; } YY_BREAK case 5: YY_RULE_SETUP #line 83 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return RPAR; } YY_BREAK case 6: YY_RULE_SETUP #line 84 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return BAR; } YY_BREAK case 7: YY_RULE_SETUP #line 85 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return KWSTRUCT; } YY_BREAK case 8: YY_RULE_SETUP #line 86 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return SET; } YY_BREAK case 9: YY_RULE_SETUP #line 87 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return LIST; } YY_BREAK case 10: YY_RULE_SETUP #line 88 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return REAL; } YY_BREAK case 11: YY_RULE_SETUP #line 89 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return HASH; } YY_BREAK case 12: YY_RULE_SETUP #line 90 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return QMARK; } YY_BREAK case 13: YY_RULE_SETUP #line 91 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return COLON; } YY_BREAK case 14: YY_RULE_SETUP #line 92 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return COMMA; } YY_BREAK case 15: YY_RULE_SETUP #line 93 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return INT; } YY_BREAK case 16: YY_RULE_SETUP #line 94 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return NAT; } YY_BREAK case 17: YY_RULE_SETUP #line 95 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return POS; } YY_BREAK case 18: YY_RULE_SETUP #line 96 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return BAG; } YY_BREAK case 19: YY_RULE_SETUP #line 97 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return BOOL; } YY_BREAK case 20: YY_RULE_SETUP #line 98 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); return ARROW; } YY_BREAK case 21: YY_RULE_SETUP #line 99 ""liblts_fsmlexer.ll"" { processId(); return ID; } YY_BREAK case 22: /* rule 22 can match eol */ YY_RULE_SETUP #line 100 ""liblts_fsmlexer.ll"" { processQuoted(); return QUOTED; } YY_BREAK case 23: YY_RULE_SETUP #line 101 ""liblts_fsmlexer.ll"" { processNumber(); return NUMBER; } YY_BREAK case 24: YY_RULE_SETUP #line 102 ""liblts_fsmlexer.ll"" { posNo += YYLeng(); fsmyyerror(""unknown character""); } YY_BREAK case 25: YY_RULE_SETUP #line 104 ""liblts_fsmlexer.ll"" ECHO; YY_BREAK #line 844 ""liblts_fsmlexer.cpp"" case YY_STATE_EOF(INITIAL): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p ""<="" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( ""fatal flex scanner internal error--no action found"" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* The contents of this function are C++ specific, so the () macro is not used. */ yyFlexLexer::yyFlexLexer( std::istream* arg_yyin, std::ostream* arg_yyout ) { yyin = arg_yyin; yyout = arg_yyout; yy_c_buf_p = nullptr; yy_init = 0; yy_start = 0; yy_flex_debug = 0; yylineno = 1; // this will only get updated if %option yylineno yy_did_buffer_switch_on_eof = 0; yy_looking_for_trail_begin = 0; yy_more_flag = 0; yy_more_len = 0; yy_more_offset = yy_prev_more_offset = 0; yy_start_stack_ptr = yy_start_stack_depth = 0; yy_start_stack = nullptr; yy_buffer_stack = nullptr; yy_buffer_stack_top = 0; yy_buffer_stack_max = 0; yy_state_buf = nullptr; } /* The contents of this function are C++ specific, so the () macro is not used. */ yyFlexLexer::~yyFlexLexer() { delete [] yy_state_buf; fsmyyfree(yy_start_stack ); yy_delete_buffer( YY_CURRENT_BUFFER ); fsmyyfree(yy_buffer_stack ); } /* The contents of this function are C++ specific, so the () macro is not used. */ void yyFlexLexer::switch_streams( std::istream* new_in, std::ostream* new_out ) { if ( new_in ) { yy_delete_buffer( YY_CURRENT_BUFFER ); yy_switch_to_buffer( yy_create_buffer( new_in, YY_BUF_SIZE ) ); } if ( new_out ) yyout = new_out; } #ifdef YY_INTERACTIVE int yyFlexLexer::LexerInput( char* buf, int /* max_size */ ) #else int yyFlexLexer::LexerInput( char* buf, int max_size ) #endif { if ( yyin->eof() || yyin->fail() ) return 0; #ifdef YY_INTERACTIVE yyin->get( buf[0] ); if ( yyin->eof() ) return 0; if ( yyin->bad() ) return -1; return 1; #else (void) yyin->read( buf, max_size ); if ( yyin->bad() ) return -1; else return yyin->gcount(); #endif } void yyFlexLexer::LexerOutput( const char* buf, int size ) { (void) yyout->write( buf, size ); } /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ int yyFlexLexer::yy_get_next_buffer() { char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = (yytext_ptr); int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( ""fatal flex scanner internal error--end of buffer missed"" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ fsmyyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = nullptr; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( ""fatal error - scanner input buffer overflow"" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart( yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) fsmyyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( ""out of dynamic memory in yy_get_next_buffer()"" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ yy_state_type yyFlexLexer::yy_get_previous_state() { yy_state_type yy_current_state; char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 61 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ yy_state_type yyFlexLexer::yy_try_NUL_trans( yy_state_type yy_current_state ) { int yy_is_jam; char *yy_cp = (yy_c_buf_p); YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 61 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 60); return yy_is_jam ? 0 : yy_current_state; } void yyFlexLexer::yyunput( int c, register char* yy_bp) { char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up yytext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ int number_to_move = (yy_n_chars) + 2; char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( ""flex scanner push-back overflow"" ); } *--yy_cp = (char) c; (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } int yyFlexLexer::yyinput() { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\\0'; else { /* need more input */ int offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart( yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); return c; } /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyFlexLexer::yyrestart( std::istream* input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE ); } yy_init_buffer( YY_CURRENT_BUFFER, input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yyFlexLexer::yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } void yyFlexLexer::yy_load_buffer_state() { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yyFlexLexer::yy_create_buffer( std::istream* file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) fsmyyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( ""out of dynamic memory in yy_create_buffer()"" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) fsmyyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( ""out of dynamic memory in yy_create_buffer()"" ); b->yy_is_our_buffer = 1; yy_init_buffer( b, file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yyFlexLexer::yy_delete_buffer( YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) nullptr; if ( b->yy_is_our_buffer ) fsmyyfree((void *) b->yy_ch_buf ); fsmyyfree((void *) b ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ void yyFlexLexer::yy_init_buffer( YY_BUFFER_STATE b, std::istream* file ) { int oerrno = errno; yy_flush_buffer( b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yyFlexLexer::yy_flush_buffer( YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yyFlexLexer::yypush_buffer_state (YY_BUFFER_STATE new_buffer) { if (new_buffer == nullptr) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yyFlexLexer::yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = nullptr; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ void yyFlexLexer::yyensure_buffer_stack(void) { int num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)fsmyyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( ""out of dynamic memory in yyensure_buffer_stack()"" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)fsmyyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( ""out of dynamic memory in yyensure_buffer_stack()"" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } void yyFlexLexer::yy_push_state( int new_state ) { if ( (yy_start_stack_ptr) >= (yy_start_stack_depth) ) { yy_size_t new_size; (yy_start_stack_depth) += YY_START_STACK_INCR; new_size = (yy_start_stack_depth) * sizeof( int ); if ( ! (yy_start_stack) ) (yy_start_stack) = (int *) fsmyyalloc(new_size ); else (yy_start_stack) = (int *) fsmyyrealloc((void *) (yy_start_stack),new_size ); if ( ! (yy_start_stack) ) YY_FATAL_ERROR( ""out of memory expanding start-condition stack"" ); } (yy_start_stack)[(yy_start_stack_ptr)++] = YY_START; BEGIN(new_state); } void yyFlexLexer::yy_pop_state() { if ( --(yy_start_stack_ptr) < 0 ) YY_FATAL_ERROR( ""start-condition stack underflow"" ); BEGIN((yy_start_stack)[(yy_start_stack_ptr)]); } int yyFlexLexer::yy_top_state() { return (yy_start_stack)[(yy_start_stack_ptr) - 1]; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif void yyFlexLexer::LexerError( yyconst char msg[] ) { std::cerr << msg << std::endl; exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \\ do \\ { \\ /* Undo effects of setting up yytext. */ \\ int yyless_macro_arg = (n); \\ YY_LESS_LINENO(yyless_macro_arg);\\ yytext[yyleng] = (yy_hold_char); \\ (yy_c_buf_p) = yytext + yyless_macro_arg; \\ (yy_hold_char) = *(yy_c_buf_p); \\ *(yy_c_buf_p) = '\\0'; \\ yyleng = yyless_macro_arg; \\ } \\ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *fsmyyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *fsmyyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void fsmyyfree (void * ptr ) { free( (char *) ptr ); /* see fsmyyrealloc() for (char *) cast */ } #define YYTABLES_NAME ""yytables"" #line 104 ""liblts_fsmlexer.ll"" void concrete_fsm_lexer::processId() { posNo += YYLeng(); // fsmyylval.result_string = ATmakeAppl0( ATmakeAFun( YYText(), 0, ATtrue ) ); // fsmyylval.result_string = YYText(); fsmyylval = static_cast(YYText()); } void concrete_fsm_lexer::processQuoted() { posNo += YYLeng(); std::string value = static_cast( YYText() ); value = value.substr( 1, value.length() - 2 ); fsmyylval = value; // fsmyylval.result_string = value; // fsmyylval.result_string = ATmakeAppl0( ATmakeAFun( value.c_str(), 0, ATtrue ) ); } void concrete_fsm_lexer::processNumber() { posNo += YYLeng(); // fsmyylval.number = atoi( YYText() ); fsmyylval=static_cast(YYText()); } //Implementation of parse_fsm bool parse_fsm(std::istream &stream, lts_fsm_t &l) { clexer = new concrete_fsm_lexer(); fsm_lexer_obj = clexer; bool result = clexer->parse_stream(stream,l); delete clexer; fsm_lexer_obj = nullptr; clexer = nullptr; return result; } //Implementation of global functions int fsmyylex(void) { return clexer->yylex(); } void fsmyyerror(const char *s) { return clexer->yyerror(s); } int fsmyyFlexLexer::yywrap(void) { return 1; } //Implementation of concrete_fsm_lexer concrete_fsm_lexer::concrete_fsm_lexer(void) : fsmyyFlexLexer(nullptr, nullptr) { } void concrete_fsm_lexer::yyerror(const char *s) { fprintf( stderr, ""token '%s' at position %d,%d caused the following error: %s\\n"", YYText(), lineNo, posNo, s ); } bool concrete_fsm_lexer::parse_stream(std::istream &stream, lts_fsm_t &l) { switch_streams(&stream, nullptr); lineNo=1; posNo=1; // INITIALISE fsm_lts = &l; /* protect_table = ATindexedSetCreate(10000,50); const_ATtype = ATmakeAFun( ""Type"", 2, ATfalse ); ATprotectAFun( const_ATtype ); const_ATvalue = ATmakeAFun( ""Value"", 2, ATfalse ); ATprotectAFun( const_ATvalue ); // stateVector = ATempty; // ATprotectList( &stateVector ); valueTable = ATempty; ATprotectList( &valueTable ); stateId = ATempty; ATprotectList( &stateId ); typeValues = NULL; ATprotectList( &typeValues ); typeId = NULL; ATprotectAppl( &typeId ); labelTable = ATtableCreate(100,50); */ // PARSE bool result; result = fsmyyparse() == 0; // CLEAN UP /* ATunprotectAFun( const_ATtype ); ATunprotectAFun( const_ATvalue ); // ATunprotectList( &stateVector ); ATunprotectList( &valueTable ); ATunprotectList( &stateId ); ATunprotectList( &typeValues ); ATunprotectAppl( &typeId ); ATtableDestroy( labelTable ); ATindexedSetDestroy( protect_table ); */ fsm_lts = nullptr; return result; } ",16201,True,2687.478735371804,median "// 3 analogista paineanturia, SIM900 ja MCP23017. Tehty Arduino IDE:ssä. /* Tehtävää: Käyttötuntilaskuri? Töpselin irrotuksen havaitsemiseminen? Nollaustoiminnon non-blockaus, ettei nappulan tarkistelu keskeydy hetkeksikään. Jos antureita nollattaessa moottoria ei pysäytettäisi kokonaan, niin se olisi käyttövalmis paljon nopeammin. sim_alustus() funktion viiveen sijaan uusi komento lähetettäisiin heti, kun GSM-moduuli on kuitannut edellisen saamansa komennon. Läimäyskäynnistys. 1K sarjavastus nappulan pinniin PC3, ettei vahingossa pinni kärähdä, jos sen pistää outputiksi. Hälytysledin ja kajarin käskeminen yhdellä kertaa I2Cllä, eikä vuoron perään. Toisen suodattimen mahdollinen keltainen valo jäätävä päälle hälytyksen ajaksi? Antureilla kestää noin 5 s lämmetä koodin uppauksen jälkeen. Joku fiksu nollaus 5 s virtojen kytkemisen jälkeen. Lämpenemisaika voi olla pidempikin, vaikka minuutteja, jos anturit ovat kylmiä. Antureiden viilentäminen kylmäkallella laskee niiden painelukemat 10 minuutissa negatiivisiin lukemiin -5, -19 ja -6 Pa. Alussa lukemat olivat 0 Pa.*/ // Kirjastot #include // Kierroslaskurin ja lennosta muutettavien muuttujien tallennus. #include // https://github.com/br3ttb/Arduino-PID-Library #include // Kommunikaatio GSM-moduulille. #include // Kommunikaatio ledeille ja kaiuttimelle. // PID muuttujat: double paine1 = 0, kaasu = 0, asetus = 0; double Kp, Ki, Kd; PID ohjain(&paine1, &kaasu, &asetus, Kp, Ki, Kd, DIRECT); // Pinnit 2 ja 9 on varattu moottorin ohjaukseen. // A3 on nappula ja 3 on sen ledi. const uint8_t mittauspinni1 = A6, mittauspinni2 = A7, mittauspinni3 = A0, nappula_pin = A3, led_pin = 3, anturienVirtaPin = 7; SoftwareSerial SIM900(10, 6); // RX, TX // Valitaan kumpaa sarjaporttia tietokone käyttää #define USB Serial // Muut globaalit muuttujat uint16_t mitattu_rpm, kierroslaskuri = 0; const uint16_t kaasu_max = 4000; // PWM säätö on välillä 0 - kaasu_max const uint16_t anturinHerkkyys = 1000; // mV/kPa const uint16_t kaasu_pid_max = kaasu_max * 0.9; // Tila 'p' = paineohjaus, 'r' = tyhjakaynti, 'o' = pallon pomputtelu int8_t tila = 'p', halytysledi, suodatinTila, puskuri[64] = {0}; const float paineresoluutio = 5.0 * 1000000 / anturinHerkkyys / 1023; // pascalia float ilmanpaine1, ilmanpaine2, ilmanpaine3, paine2, paine3; bool tyhjakaynti = true, numeroVastaanotettu = false, tuoreetPaineet = false; bool halytys = false, halytyslediPaalla = false, sim_toiminnassa = true; uint32_t kaynnistyshetki = 0, lepohetki = 0x7FFFFFFF, aika, napinTarkistusvali = 0; uint8_t GPIOA = 0xFF, GPIOB = 0x01; // MCP23017 General Purpose Input/Output rekisterit // EEPROMiin tallennettavia muuttujia uint8_t laiteid; uint16_t haluttu_rpm, resetlaskuri, kierroksia10k_mem; uint32_t ajastin, nollausAjastin, oskillointi, kierroksia10k; // Muuttujien sijainnit EEPROMissa const uint8_t haluttu_rpm_mem = 0, asetus_mem = 4, oskillointi_mem = 8, ajastin_mem = 12, Kp_mem = 16, Ki_mem = 20, Kd_mem = 24, laiteid_mem = 32, nollausAjastin_mem = 36, resetlaskuri_mem = 40; // Lisäksi kierroslaskurille on varattu muistipaikat 96-999. // Puhaltimen kierroslaskuri volatile uint8_t pulssit = 0; volatile uint32_t aikaVanha = 0; ISR(INT0_vect){ const uint32_t aikaNyt = micros(); if (aikaNyt - aikaVanha >= 15000){ // Hylätään mahdottomat yli 4000 rpm pulssit. aikaVanha = aikaNyt; pulssit++; } } // Tuulettimen nopeuden laskeminen void mittaaRPM(){ static uint32_t aikaMuinainen = 0; if (pulssit > 0) { EIMSK &= ~(1 << INT0); // Interrupt pois päältä siksi aikaa kun sen muuttujat luetaan. const uint32_t aikaViime = aikaVanha; const uint8_t kiekat = pulssit; pulssit = 0; EIMSK |= 1 << INT0; // Interrupt takaisin päälle. mitattu_rpm = 60 * 1000000 * kiekat / (aikaViime - aikaMuinainen); aikaMuinainen = aikaViime; kierroslaskuri += kiekat; // Tallennellaan kierroksia välillä EEPROMiin, jotta ne muistetaan virran katkaisun jälkeenkin. if (kierroslaskuri >= 10000) { kierroksia10k++; USB.println(F(""Tallennetaan kierrokset EEPROMiin."")); EEPROM.put(kierroksia10k_mem,kierroksia10k); kierroslaskuri -= 10000; // Tasoitetaan EEPROMin kulumista if (kierroksia10k % 10000 == 0) { USB.println(F(""Siirretaan kierrosten tallennuspaikkaa EEPROMissa."")); kierroksia10k_mem++; if (kierroksia10k_mem > 999) { kierroksia10k_mem = 100; } EEPROM.put(96, kierroksia10k_mem); } } } else if (mitattu_rpm != 0 && micros() - aikaMuinainen >= 1000000) mitattu_rpm = 0; // Tuuletin pysähtynyt. } // Arduinon analogRead muokattuna. Muokkaus ei juuri nopeuttanut koodia. int analogLuku(){ uint8_t low, high; ADCSRA |= 1 << ADSC; // aloita konversio while (bit_is_set(ADCSRA, ADSC)); // konversion jälkeen ADSC on tyhjennetty low = ADCL; high = ADCH; return (high << 8) | low; } /*Jumittamaton ylinäytteistysfunktio käytönaikaiseen mittailuun, jottei nappulassa olisi viivettä. Funktio ottaa tuhansia mittauksia ja laskee niistä keskiarvon. Parametri 1 on pin, josta jännitettä mitataan. Parametri 2 on otettavien näytteiden lukumäärä. Parametri 2 on valinnainen. Jos tätä parametria ei anneta, käytetään oletusarvoa. Palauttaa -1 jos ylinäytteistys on kesken. Palauttaa tuloksena luvun väliltä 0-1023 kun ylinäytteistys on valmis. Kutsumme funktiota noin 11000 kertaa sekunnissa ja nopeammin jos vain mahdollista. Siksi funktio vienee suurimman osan CPU ajasta ja on syytä saada mahdollisimman nopeaksi.*/ float ylinaytteista(uint8_t pin, const uint16_t nayteLukumaara = 3000){ static bool kesken = false; // Onko mittaus kesken static uint32_t summa, i; if (!kesken){ // Aloitetaan mittaus if (pin >= 14) pin -= 14; // allow for channel or pin numbers ADMUX = 1 << REFS0 | pin & 0x07; // MUX mittauspinniin. summa = analogLuku(); if (nayteLukumaara == 1){ return summa; } else { i = 1; kesken = true; return -1; } } else { if (i < nayteLukumaara){ const uint8_t pienisilmukka = 30; // Jos liian suuri luku, napin tarkistus viivästyy liikaa. for (uint8_t c = 0; c < pienisilmukka; c++){ // Pienisilmukka nopeuttaa ylinäytteistystä. summa += analogLuku(); // Summataan näytteitä yhteen. } i += pienisilmukka; return -1; } else { kesken = false; return (float)summa / i; // Skaalataan summa luvuksi välille 0-1023. } } } // Jumittava ylinäytteistysfunktio antureiden nollaamiseen. Ottaa noin 68000 näytettä sekunnissa. float ylinaytteista_nollaus(uint8_t pin, const uint8_t bits = 7){ if (pin >= 14) pin -= 14; // allow for channel or pin numbers ADMUX = 1 << REFS0 | pin & 0x07; // MUX mittauspinniin. const uint32_t nayteLukumaara = 1UL << (bits * 2); uint32_t summa = 0; // Summataan kaikki näytteet yhteen. for (uint32_t i = 0; i < nayteLukumaara; i++) { summa += analogLuku(); } return (float)(summa >> bits) / (1 << bits); // Skaalataan summa luvuksi välille 0-1023. } // Paineantureiden nollaus void nollaus(){ OCR1A = 0; // Pysäytetään puhallin asettamalla PWM nollaan. USB.println(F(""Odotetaan, etta puhallin pysahtyy."")); uint32_t aikaleima = millis(), aloitusaika = aikaleima; do { aika = millis(); tarkista_nappi(); if (pulssit > 0){ pulssit = 0; aikaleima = aika; } if(aika - aloitusaika > 20000){ USB.println(F(""Tuuletin ei suostu pysahtymaan, mutta nollataan silti."")); break; } } while (aika - aikaleima < 1000); OCR1A = 200; // Käynnistetään puhallin heti pysähtymisen jälkeen. // Nollaus ehditään tehdä sillä välin kun puhallin mietiskelee, // että kumpaankohan suuntaan lähtisi pyörimään. USB.println(F(""Nollaus alkaa."")); ilmanpaine1 = ylinaytteista_nollaus(mittauspinni1); ilmanpaine2 = ylinaytteista_nollaus(mittauspinni2); ilmanpaine3 = ylinaytteista_nollaus(mittauspinni3); USB.println(F(""Nollattu."")); } // Tallennettujen asetusten tulostus void printEEPROM(){ USB.print(F(""Tyhjakayntikierrosluku: "")); EEPROM.get(haluttu_rpm_mem, haluttu_rpm); USB.print(haluttu_rpm); USB.println(F("" rpm."")); kaasunKorjauskaava(); USB.print(F(""Dynaaminen paine: "")); EEPROM.get(asetus_mem, asetus); USB.print(asetus); USB.println(F("" Pa."")); USB.print(F(""Pallon pompotteluvali: "")); EEPROM.get(oskillointi_mem, oskillointi); USB.print(oskillointi); USB.println(F("" ms."")); USB.print(F(""Sammutusajastin: "")); EEPROM.get(ajastin_mem, ajastin); USB.print(ajastin); USB.println(F("" s."")); USB.print(F(""Nollausajastin: "")); EEPROM.get(nollausAjastin_mem, nollausAjastin); USB.print(nollausAjastin); USB.println(F("" s."")); USB.print(F(""Kierroslaskuri: "")); USB.print(kierroksia10k*10000+kierroslaskuri); // Mitä jos kierroksia onkin yli 0xFFFFFFFF ? USB.println(F("" kierrosta."")); USB.print(F(""Resetoitu "")); USB.print(resetlaskuri); USB.println(F("" kertaa."")); USB.print(F(""Laite id: "")); EEPROM.get(laiteid_mem,laiteid); USB.println(laiteid); USB.print(F(""Kp = "")); EEPROM.get(Kp_mem, Kp); USB.print(Kp); USB.print(F("", Ki = "")); EEPROM.get(Ki_mem, Ki); USB.print(Ki); USB.print(F("", Kd = "")); EEPROM.get(Kd_mem, Kd); USB.println(Kd); } // Funktio I/O expanderin rekistereihin kirjoittamiseen. // Ensimmäinen parametri on rekisteri, johon kirjoitetaan. // Toinen parametri on rekisteriin kirjoitettava arvo. void iox(const uint8_t rekisteri, const uint8_t arvo){ Wire.beginTransmission(0x20); // Valitaan I2C osoite. Wire.write(rekisteri); Wire.write(arvo); Wire.endTransmission(); } /*Funktio ledien värin vaihtamiseen. Parametri 1 valitsee ledin (1, 2 tai 3). Jos parametri 1 on 0, vaihdetaan kaikkia ledejä kerralla. Parametri 2 on lediin asetettava RGB väri binäärimuodossa: 0b010 = vihreä 0b110 = keltainen 0b100 = punainen*/ void ledi(const int8_t led, const uint8_t vari){ switch (led){ case 0: // Kaikki ledit kerralla GPIOA = 0xFF; GPIOB |= 1; if (vari & 0b100) GPIOA = 0b10110110; if (vari & 0b010) GPIOA &= 0b01101101; if (vari & 0b001){ GPIOA &= 0b11011011; GPIOB &= 0b11111110; } iox(0x13, GPIOB); break; case 1: // Ledi 1 GPIOA |= 0b00000111; if (vari & 0b100) GPIOA &= 0b11111110; // Punainen if (vari & 0b010) GPIOA &= 0b11111101; // Vihreä if (vari & 0b001) GPIOA &= 0b11111011; // Sininen break; case 2: // Ledi 2 GPIOA |= 0b00111000; if (vari & 0b100) GPIOA &= 0b11110111; if (vari & 0b010) GPIOA &= 0b11101111; if (vari & 0b001) GPIOA &= 0b11011111; break; case 3: // Ledi 3 GPIOA |= 0b11000000; GPIOB |= 0b00000001; if (vari & 0b100) GPIOA &= 0b10111111; if (vari & 0b010) GPIOA &= 0b01111111; if (vari & 0b001) GPIOB &= 0b11111110; iox(0x13, GPIOB); break; } iox(0x12, GPIOA); } // Kytkee kajarin yhtäjaksoisesti päälle/pois jos parametrina annetaan true. // Piipauttaa kajaria niin lyhyesti kuin mahdollista ja sammuttaa sen, // jos parametria ei anneta. void piip(const bool jatkuva = false){ bool paalle = true, pois = true; if(jatkuva){ if(GPIOB & 0x02) paalle = false; else pois = false; } if(paalle){ GPIOB |= 0x02; iox(0x13, GPIOB); } if(pois){ GPIOB &= 0xFD; iox(0x13, GPIOB); } } // kuuluvat nuotit = {1400,600,200} // hiljaiset nuotit = {2500,1600,500} void melodia(){ uint16_t nuotit[3] = {2500, 1600, 500}; for(uint8_t i = 0; i < 3; i++){ uint32_t kesto = millis() + 150; while(millis() < kesto){ piip(); delayMicroseconds(nuotit[i]); } } } //tuottaa äänen void sweep(){ for (uint16_t nuotti=0xFF;nuotti>0;nuotti--){ piip(); delayMicroseconds(nuotti); } } void setup() { //laitetaan pinnit päälle pinMode(mittauspinni1, INPUT); pinMode(mittauspinni2, INPUT); pinMode(mittauspinni3, INPUT); pinMode(nappula_pin, INPUT_PULLUP); pinMode(led_pin, OUTPUT); pinMode(anturienVirtaPin, OUTPUT); digitalWrite(anturienVirtaPin, HIGH); USB.begin(250000); // USB communicaatio tietsikkaan. SIM900.begin(19200); // SIM900 communicaatio. 1200-115200. // LED-piirin alkuvalmistelut Wire.begin(); iox(0x00, 0x00); // IODIRA rekisterin pinnit 0-7 outputiksi. iox(0x01, 0xFC); // IODIRB rekisterin pinnit 0-1 outputiksi. ledi(0, 0); // Sammuta ledit. PORTD |= 1 << PD2; // Pinnin 2 ylösvetovastus päälle. Liitä tuulettimen sense johto pinniin 2. EIMSK |= 1 << INT0; // External Interrupt MaSK register. Turns on INT0. EICRA = 0b10; // External Interrupt Control Register. Trigger interrupt from falling edge. // Nopeutetaan AD-muunninta. Lisätietoja löytyy sivulta 319 datasheetistä: // www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf ADCSRA &= 0b11111000; // Nollataan rekisterin 3 vikaa bittiä. ADCSRA |= 4; // Ja asetetaan 3 vikaa bittiä uudelleen. 4=nopein, 7=hitain (oletus). DDRB |= 1 << PB1; // Data Direction Register B. Pin 9 output. TCCR1A = 1 << COM1A1; // Timer/Counter Control Register. Compare Output Mode. non-inverting PWM TCCR1B = 1 << WGM13 | 1 << CS10; // Waveform Generation Mode. Mode 8 sivulla 172. Clock Select. No prescaling. ICR1 = kaasu_max; // Input Capture Register. TOP counter value. OCR1A = 0; ohjain.SetOutputLimits(200, kaasu_pid_max); ohjain.SetMode(AUTOMATIC); ohjain.SetSampleTime(200); EEPROM.get(resetlaskuri_mem,resetlaskuri); resetlaskuri++; EEPROM.put(resetlaskuri_mem,resetlaskuri); EEPROM.get(96, kierroksia10k_mem); if(kierroksia10k_mem < 100 || kierroksia10k_mem > 999){ USB.println(F(""Kierrosten muistipaikka alustettu."")); kierroksia10k_mem = 100; EEPROM.put(96, kierroksia10k_mem); kierroksia10k = 0; EEPROM.put(kierroksia10k_mem, kierroksia10k); } else EEPROM.get(kierroksia10k_mem, kierroksia10k); printEEPROM(); //melodia(); piip(); } void loop() { // Yksi kierros kesti 51 µs kun pienisilmukkaa ei vielä ollut ylinäytteistyksen sisällä. aika = millis(); // 2 µs tarkista_nappi(); // Tän funktion kutsuminen hidastaa looppii 3 µs. mittaaRPM(); // Tää 4 µs. // Mitataan paineet ylinäytteistäen kolmesta eri anturista. // Ylinäytteistetään yksi anturi kerrallaan, eikä mitattavaa // anturia jatkuvasti vaihdellen, jotta multiplekseri voidaan // pitää ylinäytteistyksen ajan samassa mittauspinnissä. // Tämä tekee ylinäytteistyksestä nopeampaa. // Mitataan dynaaminen paine viimeisimpänä, jotta PID-säädin saa tuoreimman // painelukeman. // Suodattimien paineantureita ei tarvitsisi mitata yhtä usein kuin moottorin // paineanturia, joten suodattimien antureiden tarkistusväliä voisi harventaa? // Moottorinkin anturia tarvitsisi mitata vain yhtä usein kuin PID-säädin laskee // uusia säätöarvoja, eli 5 kertaa sekunnissa. // Antureita ei tarvitse mitata lainkaan silloin kun puhallin on tyhjäkäynnillä, // tosin ei siitä kai haittaakaan ole. // Tällä hetkellä antureita mitataan niin usein kuin microcontrolleri pystyy. static uint8_t anturi = 0; if (anturi == 0){ const float os = ylinaytteista(mittauspinni3); if (os != -1){ paine3 = (os - ilmanpaine3) * paineresoluutio; anturi++; } } else if (anturi == 1){ const float os = ylinaytteista(mittauspinni2); if (os != -1){ paine2 = (os - ilmanpaine2) * paineresoluutio; anturi++; } } else if (anturi == 2){ const float os = ylinaytteista(mittauspinni1); if (os != -1){ paine1 = (os - ilmanpaine1) * paineresoluutio; anturi = 0; tuoreetPaineet = true; } } // Moottorin ohjaus painelukemalla (1 µs tyhjäkäynnillä) if (!tyhjakaynti && tila == 'p'){ if (mitattu_rpm < 300) { kaasu = 600; } else ohjain.Compute(); // EHDOTUS: Computataan heti kun dynaaminen paine on mitattu. } // Pallon pompottelutoiminto static uint32_t ajankohta = 0; if (tila == 'o' && !tyhjakaynti && aika - ajankohta > oskillointi){ ajankohta = aika; // Ledien vilkuttelua static byte colors[3]; byte led,color; led = random(1,4); do { color = random(0,8); } while (colors[led-1] == color); colors[led-1] = color; piip(); ledi(led, color); if (kaasu == 200) { kaasu = kaasu_max; } else { kaasu = 200; } digitalWrite(led_pin, kaasu == kaasu_max?HIGH:LOW); //MITÄ TARKOITTAA???? } // Tämä tarkoittaa sitä, että jos moottorille syötettävä PWM signaali on // saavuttanut maksimiarvonsa (kaasu_max), pistetään ledi päälle (HIGH) ja // kun PWM signaali on pian taas minimissään (200), ledi sammutetaan (LOW). // Näin ledi saadaan vilkkumaan samaan tahtiin moottorin kanssa. // Nollataan anturit jonkin aikaa sammutuksen jälkeen. (if lause vie 6 µs tyhjäkäynnillä) if (tyhjakaynti && tila!='t' && aika - lepohetki >= 1000UL * nollausAjastin) { nollaus(); lepohetki = aika; } OCR1A = kaasu; // Nopeuskäsky moottorille. // Lukujen tulostus tietokoneelle static uint32_t tulostushetki = 0; const uint32_t aikaViimeTulostuksesta = aika - tulostushetki; // Tulostetaan lukemat vain, jos uusia lukemia on saatavilla. if(tuoreetPaineet && (aikaViimeTulostuksesta >= 2000 || (tila=='t' && aikaViimeTulostuksesta >= 200))){ tulostushetki = aika; // Tulostetaan paineet USB.print(paine1,1); USB.print("", ""); USB.print(paine2,1); //USB.print(suodatettu_paine,1); //USB.print("", ""); //USB.print(sqrt(suodatettu_paine*2/1.25)); USB.print("", ""); USB.print(paine3,1); USB.print("", ""); /*USB.print(3.6*10.6*sqrt(paine2)); USB.print("", "");*/ USB.print(mitattu_rpm); USB.print("", ""); USB.print(kaasu,0); USB.print("", ""); USB.println(napinTarkistusvali); napinTarkistusvali = 0; // Testaustila (kokeiltava toimiiko vielä), jolla Excel painekuvaajat tehtiin if (tila == 't') { kaasu += 10; if (kaasu > 3000) { USB.println(F(""Testaus valmis."")); kaasu = 200; OCR1A = kaasu; tila = 'r'; toiminto('r'); while (!USB.available()); } } } // Tarkistetaan ovatko suodattimet tukossa static uint32_t ledihetki1 = 0, ledihetki2 = 0, ledihetki3 = 0; if(tuoreetPaineet){ tuoreetPaineet = false; char tukos; if (tukos = onTukossa()){ if (tukos & 0b000010){ USB.println(F(""Karkeasuodatin aivan tukossa"")); toiminto('r'); // Moottori tyhjäkäynnille. halytys = true; halytysledi = 1; suodatinTila = 1; sim_toiminnassa = true; } else if (tukos & 0b000001){ USB.println(F(""Karkeasuodatin melko tukossa"")); piip(); ledi(1, 0b110); ledihetki1 = aika; } if (tukos & 0b001000){ USB.println(F(""Hienosuodatin aivan tukossa"")); toiminto('r'); halytys = true; halytysledi = 2; if(suodatinTila == 1) suodatinTila = 3; else suodatinTila = 2; sim_toiminnassa = true; } else if (tukos & 0b000100){ USB.println(F(""Hienosuodatin melko tukossa"")); piip(); ledi(2, 0b110); ledihetki2 = aika; } if (tukos & 0b100000){ USB.println(F(""Imuaukko tai poistoputki aivan tukossa"")); toiminto('r'); halytys = true; halytysledi = 3; sim_toiminnassa = true; } else if (tukos & 0b010000){ USB.println(F(""Imuaukko tai poistoputki melko tukossa"")); ledi(3, 0b110); ledihetki3 = aika; } } } // Sammutetaan keltaiset ledit vähän ajan päästä if(tila == 'p'){ if ((GPIOA & 0b00000011) == 0 && aika-ledihetki1 > 5000) ledi(1, 0b010); if ((GPIOA & 0b00011000) == 0 && aika-ledihetki2 > 5000) ledi(2, 0b010); if ((GPIOA & 0b11000000) == 0 && aika-ledihetki3 > 5000) ledi(3, 0b010); } // Punaisten ledien vilkuttelu ja piippailu tukkeutumisen jälkeen static uint32_t halytyshetki = 0; if(halytys && aika-halytyshetki > 500){ halytyshetki = aika; piip(); if(halytyslediPaalla) ledi(halytysledi, 0b000); else ledi(halytysledi, 0b100); halytyslediPaalla = !halytyslediPaalla; } // Kutsutaan sim funktiota sen palauttamin aikavälein static bool sim_alustettu = false; static uint32_t sim_hetki = 0, sim_viive = 0; if (sim_toiminnassa && aika - sim_hetki >= sim_viive){ if (!sim_alustettu){ sim_viive = sim_alustus(); if (sim_viive == 0xFFFFFFFF){ USB.println(F(""Sim alustettu."")); sim_viive = 0; sim_alustettu = true; if(!halytys) sim_toiminnassa = false; } } else { sim_viive = sim_serveriyhteys(); if (sim_viive == 0xFFFFFFFF){ if (numeroVastaanotettu) { USB.println(F(""Tekstiviesti lähetetty."")); } else { USB.println(F(""Numeron vastaanotto epäonnistuí."")); } sim_viive = 0; sim_toiminnassa = false; } } sim_hetki = aika; } // Käskyjen vastaanotto tietokoneelta: static int8_t kasky[20]; if (USB.available()){ // Jatkuva available() tarkastelu hidastaa looppia 5 µs. delay(10); // Odotetaan, että kaikki data ehtii saapua serial bufferiin. int8_t kirjain; for (uint8_t i = 0; i kaasu_max) haluttu_rpm = kaasu_max; kaasunKorjauskaava(); USB.print(F(""Asetetaan RPM "")); USB.println(haluttu_rpm); EEPROM.put(haluttu_rpm_mem, haluttu_rpm); break; case 'p': kasky[0] = ' '; asetus = atoi(kasky); USB.print(F(""Asetetaan paine "")); USB.println(asetus, 0); EEPROM.put(asetus_mem, asetus); break; case 'o': tila = 'o'; kasky[0] = ' '; oskillointi = atoi(kasky); EEPROM.put(oskillointi_mem, oskillointi); break; case 'a': kasky[0] = ' '; ajastin = atoi(kasky); USB.print(F(""Asetetaan ajastin: "")); USB.println(ajastin); EEPROM.put(ajastin_mem, ajastin); break; case 'm': kasky[0] = ' '; nollausAjastin = atoi(kasky); USB.print(F(""Asetetaan nollausajastin: "")); USB.println(nollausAjastin); EEPROM.put(nollausAjastin_mem, nollausAjastin); break; case 't': toiminto('r'); tila = 't'; USB.println(F(""Antureiden testaus..."")); kaasu = 200; OCR1A = kaasu; do{ mittaaRPM(); if(millis() - aika > 20000){ USB.println(F(""Moottori ei tottele tai RPM piuha irti."")); tila = 'r'; toiminto('r'); break; } }while (mitattu_rpm > 320 || mitattu_rpm < 310); break; case 'n': nollaus(); break; case 's': if (!sim_alustettu) { USB.println(F(""Alustetaan SIM900..."")); } else { USB.println(F(""Lahetetaan serverille jotain..."")); } sim_toiminnassa = true; break; case 'i': printEEPROM(); break; case 'k': // PID kertoimien muuttaminen lennosta switch (kasky[1]){ case 'p': kasky[0] = ' '; kasky[1] = ' '; Kp = (double)atoi(kasky) / 100; USB.print(F(""Kp = "")); USB.println(Kp); EEPROM.put(Kp_mem, Kp); break; case 'i': kasky[0] = ' '; kasky[1] = ' '; Ki = (double)atoi(kasky) / 100; USB.print(F(""Ki = "")); USB.println(Ki); EEPROM.put(Ki_mem, Ki); break; case 'd': kasky[0] = ' '; kasky[1] = ' '; Kd = (double)atoi(kasky) / 100; USB.print(F(""Kd = "")); USB.println(Kd); EEPROM.put(Kd_mem, Kd); break; } ohjain.SetTunings(Kp, Ki, Kd); break; default: USB.println(F(""r1000 p100 o1000 a10 t n i s Kp100 Ki100 Kd100"")); } } } // Nappulan painamisen tarkistus. // Funktio vie aikaa 8-20 µs digitalReadilla, 460 µs I2C:llä // tai 4-16 µs PINillä. Käytämme PINiä, koska se on nopein. // Funktio suorittaa 100 kertaa sekunnissa, kun taas // ylinäytteistys pyörii 10000 kertaa sekunnissa, joten I2C:n käyttö // hidastaisi silti loop timeä vain 2 µs, eli 4 %. void tarkista_nappi(){ //uint32_t test=micros(); static uint32_t napinViimeTarkistushetki = 0; const uint32_t aikaViimeTarkistuksesta = aika - napinViimeTarkistushetki; if (aikaViimeTarkistuksesta >= 10){ if (aikaViimeTarkistuksesta > napinTarkistusvali) { napinTarkistusvali = aikaViimeTarkistuksesta; } napinViimeTarkistushetki = aika; // Tarkistetaan, kauanko nappia painetaan char painettu = 0; static bool viritetty = true, viritettyPitka = true; static uint32_t aikaleima = 0; const bool ylhaalla = PINC & 1<= 2000){ // Pitkä painallus. viritettyPitka = false; painettu = 2; aikaleima = aika; } } else if (!viritetty && aika - aikaleima >= 50){ // Viritetään nappi uudelleen. viritetty = true; viritettyPitka = true; } // Päätetään mitä tehdään kun nappia on painettu if (tyhjakaynti && painettu == 1) { piip(); if(halytys){ halytys=false; halytyslediPaalla=false; ledi(halytysledi,0b100); suodatinTila=0; } else toiminto('p'); } else if (!tyhjakaynti && (painettu == 1 || aika - kaynnistyshetki >= 1000UL * ajastin)) { piip(); toiminto('r'); // Lepotilaan 5 min kuluttua tai napin painalluksesta. sim_toiminnassa=true; } else if (painettu == 2) { // Pitkä painallus sweep(); if (tila == 'p') { toiminto('x'); } else if (tila == 'x') { toiminto('o'); } else if (tila == 'o'){ toiminto('p'); } } //USB.println(micros()-test); } } // Palauttaa binäärilukuna, mitkä suodattimet ovat tukossa. // Paluuarvon bitit 0-1 kertovat karkeasuodattimen tukkoisuuden, // bitit 2-3 hienosuodattimen tukkoisuuden ja bitit 4-5 // poisto- tai imuaukon tukkoisuuden. // Jos suodatin ei ole tukossa, sen bitit ovat 0b00. // Jos suodatin on melko tukossa, sen bitit ovat 0b01. // Jos suodatin on aivan tukossa, sen bitit ovat 0b10. uint8_t onTukossa(){ uint8_t tukot=0; static uint32_t viiveKarkeaAivan=aika, viiveKarkeaMelko=aika, viiveHienoAivan=aika, viiveHienoMelko=aika, viiveKierrosluku=aika; bool karkeaAivanTukossa = false, karkeaMelkoTukossa = false, hienoAivanTukossa = false, hienoMelkoTukossa = false; if (!tyhjakaynti && tila == 'p'){ // Tarkistetaan, onko oikea toiminto päällä. // Tukkoisuuden painerajat if (paine2 > 250) karkeaAivanTukossa=true; else if (paine2 > 100) karkeaMelkoTukossa=true; if (paine3 > 450) hienoAivanTukossa=true; else if (paine3 > 200) hienoMelkoTukossa=true; // Tarkistetaan, että tukkoisuus on kestänyt riittävän kauan if (karkeaAivanTukossa){ if (aika - viiveKarkeaAivan > 1000){ viiveKarkeaAivan=aika; tukot |= 0b000010; } } else viiveKarkeaAivan=aika; if (karkeaMelkoTukossa){ if (aika - viiveKarkeaMelko > 1000){ viiveKarkeaMelko=aika; tukot |= 0b000001; } } else viiveKarkeaMelko=aika; if (hienoAivanTukossa){ if (aika - viiveHienoAivan > 1000){ viiveHienoAivan=aika; tukot |= 0b001000; } } else viiveHienoAivan=aika; if (hienoMelkoTukossa){ if (aika - viiveHienoMelko > 1000){ viiveHienoMelko=aika; tukot |= 0b000100; } } else viiveHienoMelko=aika; // Jos moottori on pyörinyt täysillä jonkin aikaa if (kaasu == kaasu_pid_max && aika - viiveKierrosluku > 1000){ viiveKierrosluku = aika; const float yhteispaine = paine2 + paine3; if (yhteispaine < 300) tukot |= 0b100000; // Poistoputki aivan tukossa. else if (yhteispaine < 500) tukot |= 0b010000; // Poistoputki melko tukossa. } } return tukot; } // Moottorin RPM säädön korjauskaava void kaasunKorjauskaava(){ kaasu = 1.0385 * haluttu_rpm - 109; if (kaasu > kaasu_max) { kaasu = kaasu_max; } else if (kaasu < 0) { kaasu = 0; } } // Käynnistää eri toimintoja, kuten tyhjäkäynti 'r', nopeuden vakiona pito 'p' tai pallon pomputtelu 'o' void toiminto(const char toivomus){ if (toivomus == 'r'){ digitalWrite(led_pin,LOW); ledi(0,0); ohjain.SetMode(0); kaasunKorjauskaava(); tyhjakaynti = true; USB.println(F(""Tyhjakaynti"")); lepohetki = aika; } else { tila = toivomus; tyhjakaynti = false; kaynnistyshetki = aika; if (toivomus == 'p'){ digitalWrite(led_pin,HIGH); ledi(0,0b010); // Kaikki ledit vihreiksi ohjain.SetMode(1); USB.print(F(""Kaynnistetaan "")); USB.print(ajastin); USB.print(F("" sekunniksi paineeseen "")); USB.print(asetus,0); USB.println(F("" Pa."")); } else if (toivomus == 'o'){ ohjain.SetMode(0); USB.println(F(""Pallon pomputtelu"")); } else if(toivomus=='x'){ ohjain.SetMode(0); kaasu=kaasu_max; ledi(0,0b111); USB.println(F(""Taysteho"")); } } } ",12169,False,2437.6065254051446,median "// Copyright 2012 the V8 project authors. 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // 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 // OWNER 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 ""v8.h"" #include ""factory.h"" #include ""hydrogen.h"" #if V8_TARGET_ARCH_IA32 #include ""ia32/lithium-ia32.h"" #elif V8_TARGET_ARCH_X64 #include ""x64/lithium-x64.h"" #elif V8_TARGET_ARCH_ARM #include ""arm/lithium-arm.h"" #elif V8_TARGET_ARCH_MIPS #include ""mips/lithium-mips.h"" #else #error Unsupported target architecture. #endif namespace v8 { namespace internal { #define DEFINE_COMPILE(type) \\ LInstruction* H##type::CompileToLithium(LChunkBuilder* builder) { \\ return builder->Do##type(this); \\ } HYDROGEN_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE) #undef DEFINE_COMPILE const char* Representation::Mnemonic() const { switch (kind_) { case kNone: return ""v""; case kTagged: return ""t""; case kDouble: return ""d""; case kInteger32: return ""i""; case kExternal: return ""x""; default: UNREACHABLE(); return NULL; } } int HValue::LoopWeight() const { const int w = FLAG_loop_weight; static const int weights[] = { 1, w, w*w, w*w*w, w*w*w*w }; return weights[Min(block()->LoopNestingDepth(), static_cast(ARRAY_SIZE(weights)-1))]; } void HValue::AssumeRepresentation(Representation r) { if (CheckFlag(kFlexibleRepresentation)) { ChangeRepresentation(r); // The representation of the value is dictated by type feedback and // will not be changed later. ClearFlag(kFlexibleRepresentation); } } static int32_t ConvertAndSetOverflow(int64_t result, bool* overflow) { if (result > kMaxInt) { *overflow = true; return kMaxInt; } if (result < kMinInt) { *overflow = true; return kMinInt; } return static_cast(result); } static int32_t AddWithoutOverflow(int32_t a, int32_t b, bool* overflow) { int64_t result = static_cast(a) + static_cast(b); return ConvertAndSetOverflow(result, overflow); } static int32_t SubWithoutOverflow(int32_t a, int32_t b, bool* overflow) { int64_t result = static_cast(a) - static_cast(b); return ConvertAndSetOverflow(result, overflow); } static int32_t MulWithoutOverflow(int32_t a, int32_t b, bool* overflow) { int64_t result = static_cast(a) * static_cast(b); return ConvertAndSetOverflow(result, overflow); } int32_t Range::Mask() const { if (lower_ == upper_) return lower_; if (lower_ >= 0) { int32_t res = 1; while (res < upper_) { res = (res << 1) | 1; } return res; } return 0xffffffff; } void Range::AddConstant(int32_t value) { if (value == 0) return; bool may_overflow = false; // Overflow is ignored here. lower_ = AddWithoutOverflow(lower_, value, &may_overflow); upper_ = AddWithoutOverflow(upper_, value, &may_overflow); #ifdef DEBUG Verify(); #endif } void Range::Intersect(Range* other) { upper_ = Min(upper_, other->upper_); lower_ = Max(lower_, other->lower_); bool b = CanBeMinusZero() && other->CanBeMinusZero(); set_can_be_minus_zero(b); } void Range::Union(Range* other) { upper_ = Max(upper_, other->upper_); lower_ = Min(lower_, other->lower_); bool b = CanBeMinusZero() || other->CanBeMinusZero(); set_can_be_minus_zero(b); } void Range::Sar(int32_t value) { int32_t bits = value & 0x1F; lower_ = lower_ >> bits; upper_ = upper_ >> bits; set_can_be_minus_zero(false); } void Range::Shl(int32_t value) { int32_t bits = value & 0x1F; int old_lower = lower_; int old_upper = upper_; lower_ = lower_ << bits; upper_ = upper_ << bits; if (old_lower != lower_ >> bits || old_upper != upper_ >> bits) { upper_ = kMaxInt; lower_ = kMinInt; } set_can_be_minus_zero(false); } bool Range::AddAndCheckOverflow(Range* other) { bool may_overflow = false; lower_ = AddWithoutOverflow(lower_, other->lower(), &may_overflow); upper_ = AddWithoutOverflow(upper_, other->upper(), &may_overflow); KeepOrder(); #ifdef DEBUG Verify(); #endif return may_overflow; } bool Range::SubAndCheckOverflow(Range* other) { bool may_overflow = false; lower_ = SubWithoutOverflow(lower_, other->upper(), &may_overflow); upper_ = SubWithoutOverflow(upper_, other->lower(), &may_overflow); KeepOrder(); #ifdef DEBUG Verify(); #endif return may_overflow; } void Range::KeepOrder() { if (lower_ > upper_) { int32_t tmp = lower_; lower_ = upper_; upper_ = tmp; } } #ifdef DEBUG void Range::Verify() const { ASSERT(lower_ <= upper_); } #endif bool Range::MulAndCheckOverflow(Range* other) { bool may_overflow = false; int v1 = MulWithoutOverflow(lower_, other->lower(), &may_overflow); int v2 = MulWithoutOverflow(lower_, other->upper(), &may_overflow); int v3 = MulWithoutOverflow(upper_, other->lower(), &may_overflow); int v4 = MulWithoutOverflow(upper_, other->upper(), &may_overflow); lower_ = Min(Min(v1, v2), Min(v3, v4)); upper_ = Max(Max(v1, v2), Max(v3, v4)); #ifdef DEBUG Verify(); #endif return may_overflow; } const char* HType::ToString() { switch (type_) { case kTagged: return ""tagged""; case kTaggedPrimitive: return ""primitive""; case kTaggedNumber: return ""number""; case kSmi: return ""smi""; case kHeapNumber: return ""heap-number""; case kString: return ""string""; case kBoolean: return ""boolean""; case kNonPrimitive: return ""non-primitive""; case kJSArray: return ""array""; case kJSObject: return ""object""; case kUninitialized: return ""uninitialized""; } UNREACHABLE(); return ""Unreachable code""; } HType HType::TypeFromValue(Handle value) { HType result = HType::Tagged(); if (value->IsSmi()) { result = HType::Smi(); } else if (value->IsHeapNumber()) { result = HType::HeapNumber(); } else if (value->IsString()) { result = HType::String(); } else if (value->IsBoolean()) { result = HType::Boolean(); } else if (value->IsJSObject()) { result = HType::JSObject(); } else if (value->IsJSArray()) { result = HType::JSArray(); } return result; } bool HValue::IsDefinedAfter(HBasicBlock* other) const { return block()->block_id() > other->block_id(); } HUseListNode* HUseListNode::tail() { // Skip and remove dead items in the use list. while (tail_ != NULL && tail_->value()->CheckFlag(HValue::kIsDead)) { tail_ = tail_->tail_; } return tail_; } bool HValue::CheckUsesForFlag(Flag f) { for (HUseIterator it(uses()); !it.Done(); it.Advance()) { if (!it.value()->CheckFlag(f)) return false; } return true; } HUseIterator::HUseIterator(HUseListNode* head) : next_(head) { Advance(); } void HUseIterator::Advance() { current_ = next_; if (current_ != NULL) { next_ = current_->tail(); value_ = current_->value(); index_ = current_->index(); } } int HValue::UseCount() const { int count = 0; for (HUseIterator it(uses()); !it.Done(); it.Advance()) ++count; return count; } HUseListNode* HValue::RemoveUse(HValue* value, int index) { HUseListNode* previous = NULL; HUseListNode* current = use_list_; while (current != NULL) { if (current->value() == value && current->index() == index) { if (previous == NULL) { use_list_ = current->tail(); } else { previous->set_tail(current->tail()); } break; } previous = current; current = current->tail(); } #ifdef DEBUG // Do not reuse use list nodes in debug mode, zap them. if (current != NULL) { HUseListNode* temp = new HUseListNode(current->value(), current->index(), NULL); current->Zap(); current = temp; } #endif return current; } bool HValue::Equals(HValue* other) { if (other->opcode() != opcode()) return false; if (!other->representation().Equals(representation())) return false; if (!other->type_.Equals(type_)) return false; if (other->flags() != flags()) return false; if (OperandCount() != other->OperandCount()) return false; for (int i = 0; i < OperandCount(); ++i) { if (OperandAt(i)->id() != other->OperandAt(i)->id()) return false; } bool result = DataEquals(other); ASSERT(!result || Hashcode() == other->Hashcode()); return result; } intptr_t HValue::Hashcode() { intptr_t result = opcode(); int count = OperandCount(); for (int i = 0; i < count; ++i) { result = result * 19 + OperandAt(i)->id() + (result >> 7); } return result; } const char* HValue::Mnemonic() const { switch (opcode()) { #define MAKE_CASE(type) case k##type: return #type; HYDROGEN_CONCRETE_INSTRUCTION_LIST(MAKE_CASE) #undef MAKE_CASE case kPhi: return ""Phi""; default: return """"; } } void HValue::SetOperandAt(int index, HValue* value) { RegisterUse(index, value); InternalSetOperandAt(index, value); } void HValue::DeleteAndReplaceWith(HValue* other) { // We replace all uses first, so Delete can assert that there are none. if (other != NULL) ReplaceAllUsesWith(other); ASSERT(HasNoUses()); Kill(); DeleteFromGraph(); } void HValue::ReplaceAllUsesWith(HValue* other) { while (use_list_ != NULL) { HUseListNode* list_node = use_list_; HValue* value = list_node->value(); ASSERT(!value->block()->IsStartBlock()); value->InternalSetOperandAt(list_node->index(), other); use_list_ = list_node->tail(); list_node->set_tail(other->use_list_); other->use_list_ = list_node; } } void HValue::Kill() { // Instead of going through the entire use list of each operand, we only // check the first item in each use list and rely on the tail() method to // skip dead items, removing them lazily next time we traverse the list. SetFlag(kIsDead); for (int i = 0; i < OperandCount(); ++i) { HValue* operand = OperandAt(i); HUseListNode* first = operand->use_list_; if (first != NULL && first->value() == this && first->index() == i) { operand->use_list_ = first->tail(); } } } void HValue::SetBlock(HBasicBlock* block) { ASSERT(block_ == NULL || block == NULL); block_ = block; if (id_ == kNoNumber && block != NULL) { id_ = block->graph()->GetNextValueID(this); } } void HValue::PrintTypeTo(StringStream* stream) { if (!representation().IsTagged() || type().Equals(HType::Tagged())) return; stream->Add("" type[%s]"", type().ToString()); } void HValue::PrintRangeTo(StringStream* stream) { if (range() == NULL || range()->IsMostGeneric()) return; stream->Add("" range[%d,%d,m0=%d]"", range()->lower(), range()->upper(), static_cast(range()->CanBeMinusZero())); } void HValue::PrintChangesTo(StringStream* stream) { GVNFlagSet changes_flags = ChangesFlags(); if (changes_flags.IsEmpty()) return; stream->Add("" changes[""); if (changes_flags == AllSideEffectsFlagSet()) { stream->Add(""*""); } else { bool add_comma = false; #define PRINT_DO(type) \\ if (changes_flags.Contains(kChanges##type)) { \\ if (add_comma) stream->Add("",""); \\ add_comma = true; \\ stream->Add(#type); \\ } GVN_FLAG_LIST(PRINT_DO); #undef PRINT_DO } stream->Add(""]""); } void HValue::PrintNameTo(StringStream* stream) { stream->Add(""%s%d"", representation_.Mnemonic(), id()); } bool HValue::UpdateInferredType() { HType type = CalculateInferredType(); bool result = (!type.Equals(type_)); type_ = type; return result; } void HValue::RegisterUse(int index, HValue* new_value) { HValue* old_value = OperandAt(index); if (old_value == new_value) return; HUseListNode* removed = NULL; if (old_value != NULL) { removed = old_value->RemoveUse(this, index); } if (new_value != NULL) { if (removed == NULL) { new_value->use_list_ = new HUseListNode(this, index, new_value->use_list_); } else { removed->set_tail(new_value->use_list_); new_value->use_list_ = removed; } } } void HValue::AddNewRange(Range* r, Zone* zone) { if (!HasRange()) ComputeInitialRange(zone); if (!HasRange()) range_ = new(zone) Range(); ASSERT(HasRange()); r->StackUpon(range_); range_ = r; } void HValue::RemoveLastAddedRange() { ASSERT(HasRange()); ASSERT(range_->next() != NULL); range_ = range_->next(); } void HValue::ComputeInitialRange(Zone* zone) { ASSERT(!HasRange()); range_ = InferRange(zone); ASSERT(HasRange()); } void HInstruction::PrintTo(StringStream* stream) { PrintMnemonicTo(stream); PrintDataTo(stream); PrintRangeTo(stream); PrintChangesTo(stream); PrintTypeTo(stream); } void HInstruction::PrintMnemonicTo(StringStream* stream) { stream->Add(""%s "", Mnemonic()); } void HInstruction::Unlink() { ASSERT(IsLinked()); ASSERT(!IsControlInstruction()); // Must never move control instructions. ASSERT(!IsBlockEntry()); // Doesn't make sense to delete these. ASSERT(previous_ != NULL); previous_->next_ = next_; if (next_ == NULL) { ASSERT(block()->last() == this); block()->set_last(previous_); } else { next_->previous_ = previous_; } clear_block(); } void HInstruction::InsertBefore(HInstruction* next) { ASSERT(!IsLinked()); ASSERT(!next->IsBlockEntry()); ASSERT(!IsControlInstruction()); ASSERT(!next->block()->IsStartBlock()); ASSERT(next->previous_ != NULL); HInstruction* prev = next->previous(); prev->next_ = this; next->previous_ = this; next_ = next; previous_ = prev; SetBlock(next->block()); } void HInstruction::InsertAfter(HInstruction* previous) { ASSERT(!IsLinked()); ASSERT(!previous->IsControlInstruction()); ASSERT(!IsControlInstruction() || previous->next_ == NULL); HBasicBlock* block = previous->block(); // Never insert anything except constants into the start block after finishing // it. if (block->IsStartBlock() && block->IsFinished() && !IsConstant()) { ASSERT(block->end()->SecondSuccessor() == NULL); InsertAfter(block->end()->FirstSuccessor()->first()); return; } // If we're inserting after an instruction with side-effects that is // followed by a simulate instruction, we need to insert after the // simulate instruction instead. HInstruction* next = previous->next_; if (previous->HasObservableSideEffects() && next != NULL) { ASSERT(next->IsSimulate()); previous = next; next = previous->next_; } previous_ = previous; next_ = next; SetBlock(block); previous->next_ = this; if (next != NULL) next->previous_ = this; } #ifdef DEBUG void HInstruction::Verify() { // Verify that input operands are defined before use. HBasicBlock* cur_block = block(); for (int i = 0; i < OperandCount(); ++i) { HValue* other_operand = OperandAt(i); HBasicBlock* other_block = other_operand->block(); if (cur_block == other_block) { if (!other_operand->IsPhi()) { HInstruction* cur = this->previous(); while (cur != NULL) { if (cur == other_operand) break; cur = cur->previous(); } // Must reach other operand in the same block! ASSERT(cur == other_operand); } } else { // If the following assert fires, you may have forgotten an // AddInstruction. ASSERT(other_block->Dominates(cur_block)); } } // Verify that instructions that may have side-effects are followed // by a simulate instruction. if (HasObservableSideEffects() && !IsOsrEntry()) { ASSERT(next()->IsSimulate()); } // Verify that instructions that can be eliminated by GVN have overridden // HValue::DataEquals. The default implementation is UNREACHABLE. We // don't actually care whether DataEquals returns true or false here. if (CheckFlag(kUseGVN)) DataEquals(this); } #endif void HUnaryCall::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add("" ""); stream->Add(""#%d"", argument_count()); } void HBinaryCall::PrintDataTo(StringStream* stream) { first()->PrintNameTo(stream); stream->Add("" ""); second()->PrintNameTo(stream); stream->Add("" ""); stream->Add(""#%d"", argument_count()); } void HBoundsCheck::PrintDataTo(StringStream* stream) { index()->PrintNameTo(stream); stream->Add("" ""); length()->PrintNameTo(stream); } void HCallConstantFunction::PrintDataTo(StringStream* stream) { if (IsApplyFunction()) { stream->Add(""optimized apply ""); } else { stream->Add(""%o "", function()->shared()->DebugName()); } stream->Add(""#%d"", argument_count()); } void HCallNamed::PrintDataTo(StringStream* stream) { stream->Add(""%o "", *name()); HUnaryCall::PrintDataTo(stream); } void HCallGlobal::PrintDataTo(StringStream* stream) { stream->Add(""%o "", *name()); HUnaryCall::PrintDataTo(stream); } void HCallKnownGlobal::PrintDataTo(StringStream* stream) { stream->Add(""o "", target()->shared()->DebugName()); stream->Add(""#%d"", argument_count()); } void HCallRuntime::PrintDataTo(StringStream* stream) { stream->Add(""%o "", *name()); stream->Add(""#%d"", argument_count()); } void HClassOfTestAndBranch::PrintDataTo(StringStream* stream) { stream->Add(""class_of_test(""); value()->PrintNameTo(stream); stream->Add("", \\""%o\\"")"", *class_name()); } void HAccessArgumentsAt::PrintDataTo(StringStream* stream) { arguments()->PrintNameTo(stream); stream->Add(""[""); index()->PrintNameTo(stream); stream->Add(""], length ""); length()->PrintNameTo(stream); } void HControlInstruction::PrintDataTo(StringStream* stream) { stream->Add("" goto (""); bool first_block = true; for (HSuccessorIterator it(this); !it.Done(); it.Advance()) { stream->Add(first_block ? ""B%d"" : "", B%d"", it.Current()->block_id()); first_block = false; } stream->Add("")""); } void HUnaryControlInstruction::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); HControlInstruction::PrintDataTo(stream); } void HIsNilAndBranch::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add(kind() == kStrictEquality ? "" === "" : "" == ""); stream->Add(nil() == kNullValue ? ""null"" : ""undefined""); HControlInstruction::PrintDataTo(stream); } void HReturn::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); } void HCompareMap::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add("" (%p)"", *map()); HControlInstruction::PrintDataTo(stream); } const char* HUnaryMathOperation::OpName() const { switch (op()) { case kMathFloor: return ""floor""; case kMathRound: return ""round""; case kMathCeil: return ""ceil""; case kMathAbs: return ""abs""; case kMathLog: return ""log""; case kMathSin: return ""sin""; case kMathCos: return ""cos""; case kMathTan: return ""tan""; case kMathASin: return ""asin""; case kMathACos: return ""acos""; case kMathATan: return ""atan""; case kMathExp: return ""exp""; case kMathSqrt: return ""sqrt""; default: break; } return ""(unknown operation)""; } void HUnaryMathOperation::PrintDataTo(StringStream* stream) { const char* name = OpName(); stream->Add(""%s "", name); value()->PrintNameTo(stream); } void HUnaryOperation::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); } void HHasInstanceTypeAndBranch::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); switch (from_) { case FIRST_JS_RECEIVER_TYPE: if (to_ == LAST_TYPE) stream->Add("" spec_object""); break; case JS_REGEXP_TYPE: if (to_ == JS_REGEXP_TYPE) stream->Add("" reg_exp""); break; case JS_ARRAY_TYPE: if (to_ == JS_ARRAY_TYPE) stream->Add("" array""); break; case JS_FUNCTION_TYPE: if (to_ == JS_FUNCTION_TYPE) stream->Add("" function""); break; default: break; } } void HTypeofIsAndBranch::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add("" == %o"", *type_literal_); HControlInstruction::PrintDataTo(stream); } void HCheckMapValue::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add("" ""); map()->PrintNameTo(stream); } void HForInPrepareMap::PrintDataTo(StringStream* stream) { enumerable()->PrintNameTo(stream); } void HForInCacheArray::PrintDataTo(StringStream* stream) { enumerable()->PrintNameTo(stream); stream->Add("" ""); map()->PrintNameTo(stream); stream->Add(""[%d]"", idx_); } void HLoadFieldByIndex::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add("" ""); index()->PrintNameTo(stream); } HValue* HConstant::Canonicalize() { return HasNoUses() ? NULL : this; } HValue* HTypeof::Canonicalize() { return HasNoUses() ? NULL : this; } HValue* HBitwise::Canonicalize() { if (!representation().IsInteger32()) return this; // If x is an int32, then x & -1 == x, x | 0 == x and x ^ 0 == x. int32_t nop_constant = (op() == Token::BIT_AND) ? -1 : 0; if (left()->IsConstant() && HConstant::cast(left())->HasInteger32Value() && HConstant::cast(left())->Integer32Value() == nop_constant) { return right(); } if (right()->IsConstant() && HConstant::cast(right())->HasInteger32Value() && HConstant::cast(right())->Integer32Value() == nop_constant) { return left(); } return this; } HValue* HAdd::Canonicalize() { if (!representation().IsInteger32()) return this; if (CheckUsesForFlag(kTruncatingToInt32)) ClearFlag(kCanOverflow); return this; } HValue* HSub::Canonicalize() { if (!representation().IsInteger32()) return this; if (CheckUsesForFlag(kTruncatingToInt32)) ClearFlag(kCanOverflow); return this; } HValue* HChange::Canonicalize() { return (from().Equals(to())) ? value() : this; } void HTypeof::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); } void HChange::PrintDataTo(StringStream* stream) { HUnaryOperation::PrintDataTo(stream); stream->Add("" %s to %s"", from().Mnemonic(), to().Mnemonic()); if (CanTruncateToInt32()) stream->Add("" truncating-int32""); if (CheckFlag(kBailoutOnMinusZero)) stream->Add("" -0?""); if (CheckFlag(kDeoptimizeOnUndefined)) stream->Add("" deopt-on-undefined""); } void HJSArrayLength::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add("" ""); typecheck()->PrintNameTo(stream); } HValue* HCheckInstanceType::Canonicalize() { if (check_ == IS_STRING && !value()->type().IsUninitialized() && value()->type().IsString()) { return NULL; } if (check_ == IS_SYMBOL && value()->IsConstant() && HConstant::cast(value())->handle()->IsSymbol()) { return NULL; } return this; } void HCheckInstanceType::GetCheckInterval(InstanceType* first, InstanceType* last) { ASSERT(is_interval_check()); switch (check_) { case IS_SPEC_OBJECT: *first = FIRST_SPEC_OBJECT_TYPE; *last = LAST_SPEC_OBJECT_TYPE; return; case IS_JS_ARRAY: *first = *last = JS_ARRAY_TYPE; return; default: UNREACHABLE(); } } void HCheckInstanceType::GetCheckMaskAndTag(uint8_t* mask, uint8_t* tag) { ASSERT(!is_interval_check()); switch (check_) { case IS_STRING: *mask = kIsNotStringMask; *tag = kStringTag; return; case IS_SYMBOL: *mask = kIsSymbolMask; *tag = kSymbolTag; return; default: UNREACHABLE(); } } void HCheckMap::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add("" %p"", *map()); if (mode() == REQUIRE_EXACT_MAP) { stream->Add("" [EXACT]""); } else if (!has_element_transitions_) { stream->Add("" [EXACT*]""); } else { stream->Add("" [MATCH ELEMENTS]""); } } void HCheckFunction::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add("" %p"", *target()); } const char* HCheckInstanceType::GetCheckName() { switch (check_) { case IS_SPEC_OBJECT: return ""object""; case IS_JS_ARRAY: return ""array""; case IS_STRING: return ""string""; case IS_SYMBOL: return ""symbol""; } UNREACHABLE(); return """"; } void HCheckInstanceType::PrintDataTo(StringStream* stream) { stream->Add(""%s "", GetCheckName()); HUnaryOperation::PrintDataTo(stream); } void HCallStub::PrintDataTo(StringStream* stream) { stream->Add(""%s "", CodeStub::MajorName(major_key_, false)); HUnaryCall::PrintDataTo(stream); } void HInstanceOf::PrintDataTo(StringStream* stream) { left()->PrintNameTo(stream); stream->Add("" ""); right()->PrintNameTo(stream); stream->Add("" ""); context()->PrintNameTo(stream); } Range* HValue::InferRange(Zone* zone) { // Untagged integer32 cannot be -0, all other representations can. Range* result = new(zone) Range(); result->set_can_be_minus_zero(!representation().IsInteger32()); return result; } Range* HChange::InferRange(Zone* zone) { Range* input_range = value()->range(); if (from().IsInteger32() && to().IsTagged() && input_range != NULL && input_range->IsInSmiRange()) { set_type(HType::Smi()); } Range* result = (input_range != NULL) ? input_range->Copy(zone) : HValue::InferRange(zone); if (to().IsInteger32()) result->set_can_be_minus_zero(false); return result; } Range* HConstant::InferRange(Zone* zone) { if (has_int32_value_) { Range* result = new(zone) Range(int32_value_, int32_value_); result->set_can_be_minus_zero(false); return result; } return HValue::InferRange(zone); } Range* HPhi::InferRange(Zone* zone) { if (representation().IsInteger32()) { if (block()->IsLoopHeader()) { Range* range = new(zone) Range(kMinInt, kMaxInt); return range; } else { Range* range = OperandAt(0)->range()->Copy(zone); for (int i = 1; i < OperandCount(); ++i) { range->Union(OperandAt(i)->range()); } return range; } } else { return HValue::InferRange(zone); } } Range* HAdd::InferRange(Zone* zone) { if (representation().IsInteger32()) { Range* a = left()->range(); Range* b = right()->range(); Range* res = a->Copy(zone); if (!res->AddAndCheckOverflow(b)) { ClearFlag(kCanOverflow); } bool m0 = a->CanBeMinusZero() && b->CanBeMinusZero(); res->set_can_be_minus_zero(m0); return res; } else { return HValue::InferRange(zone); } } Range* HSub::InferRange(Zone* zone) { if (representation().IsInteger32()) { Range* a = left()->range(); Range* b = right()->range(); Range* res = a->Copy(zone); if (!res->SubAndCheckOverflow(b)) { ClearFlag(kCanOverflow); } res->set_can_be_minus_zero(a->CanBeMinusZero() && b->CanBeZero()); return res; } else { return HValue::InferRange(zone); } } Range* HMul::InferRange(Zone* zone) { if (representation().IsInteger32()) { Range* a = left()->range(); Range* b = right()->range(); Range* res = a->Copy(zone); if (!res->MulAndCheckOverflow(b)) { ClearFlag(kCanOverflow); } bool m0 = (a->CanBeZero() && b->CanBeNegative()) || (a->CanBeNegative() && b->CanBeZero()); res->set_can_be_minus_zero(m0); return res; } else { return HValue::InferRange(zone); } } Range* HDiv::InferRange(Zone* zone) { if (representation().IsInteger32()) { Range* result = new(zone) Range(); if (left()->range()->CanBeMinusZero()) { result->set_can_be_minus_zero(true); } if (left()->range()->CanBeZero() && right()->range()->CanBeNegative()) { result->set_can_be_minus_zero(true); } if (right()->range()->Includes(-1) && left()->range()->Includes(kMinInt)) { SetFlag(HValue::kCanOverflow); } if (!right()->range()->CanBeZero()) { ClearFlag(HValue::kCanBeDivByZero); } return result; } else { return HValue::InferRange(zone); } } Range* HMod::InferRange(Zone* zone) { if (representation().IsInteger32()) { Range* a = left()->range(); Range* result = new(zone) Range(); if (a->CanBeMinusZero() || a->CanBeNegative()) { result->set_can_be_minus_zero(true); } if (!right()->range()->CanBeZero()) { ClearFlag(HValue::kCanBeDivByZero); } return result; } else { return HValue::InferRange(zone); } } void HPhi::PrintTo(StringStream* stream) { stream->Add(""[""); for (int i = 0; i < OperandCount(); ++i) { HValue* value = OperandAt(i); stream->Add("" ""); value->PrintNameTo(stream); stream->Add("" ""); } stream->Add("" uses%d_%di_%dd_%dt"", UseCount(), int32_non_phi_uses() + int32_indirect_uses(), double_non_phi_uses() + double_indirect_uses(), tagged_non_phi_uses() + tagged_indirect_uses()); stream->Add(""%s%s]"", is_live() ? ""_live"" : """", IsConvertibleToInteger() ? """" : ""_ncti""); } void HPhi::AddInput(HValue* value) { inputs_.Add(NULL); SetOperandAt(OperandCount() - 1, value); // Mark phis that may have 'arguments' directly or indirectly as an operand. if (!CheckFlag(kIsArguments) && value->CheckFlag(kIsArguments)) { SetFlag(kIsArguments); } } bool HPhi::HasRealUses() { for (HUseIterator it(uses()); !it.Done(); it.Advance()) { if (!it.value()->IsPhi()) return true; } return false; } HValue* HPhi::GetRedundantReplacement() { HValue* candidate = NULL; int count = OperandCount(); int position = 0; while (position < count && candidate == NULL) { HValue* current = OperandAt(position++); if (current != this) candidate = current; } while (position < count) { HValue* current = OperandAt(position++); if (current != this && current != candidate) return NULL; } ASSERT(candidate != this); return candidate; } void HPhi::DeleteFromGraph() { ASSERT(block() != NULL); block()->RemovePhi(this); ASSERT(block() == NULL); } void HPhi::InitRealUses(int phi_id) { // Initialize real uses. phi_id_ = phi_id; for (HUseIterator it(uses()); !it.Done(); it.Advance()) { HValue* value = it.value(); if (!value->IsPhi()) { Representation rep = value->RequiredInputRepresentation(it.index()); non_phi_uses_[rep.kind()] += value->LoopWeight(); } } } void HPhi::AddNonPhiUsesFrom(HPhi* other) { for (int i = 0; i < Representation::kNumRepresentations; i++) { indirect_uses_[i] += other->non_phi_uses_[i]; } } void HPhi::AddIndirectUsesTo(int* dest) { for (int i = 0; i < Representation::kNumRepresentations; i++) { dest[i] += indirect_uses_[i]; } } void HSimulate::PrintDataTo(StringStream* stream) { stream->Add(""id=%d"", ast_id()); if (pop_count_ > 0) stream->Add("" pop %d"", pop_count_); if (values_.length() > 0) { if (pop_count_ > 0) stream->Add("" /""); for (int i = 0; i < values_.length(); ++i) { if (i > 0) stream->Add("",""); if (HasAssignedIndexAt(i)) { stream->Add("" var[%d] = "", GetAssignedIndexAt(i)); } else { stream->Add("" push ""); } values_[i]->PrintNameTo(stream); } } } void HDeoptimize::PrintDataTo(StringStream* stream) { if (OperandCount() == 0) return; OperandAt(0)->PrintNameTo(stream); for (int i = 1; i < OperandCount(); ++i) { stream->Add("" ""); OperandAt(i)->PrintNameTo(stream); } } void HEnterInlined::PrintDataTo(StringStream* stream) { SmartArrayPointer name = function()->debug_name()->ToCString(); stream->Add(""%s, id=%d"", *name, function()->id()); } HConstant::HConstant(Handle handle, Representation r) : handle_(handle), has_int32_value_(false), has_double_value_(false), int32_value_(0), double_value_(0) { set_representation(r); SetFlag(kUseGVN); if (handle_->IsNumber()) { double n = handle_->Number(); double roundtrip_value = static_cast(static_cast(n)); has_int32_value_ = BitCast(roundtrip_value) == BitCast(n); if (has_int32_value_) int32_value_ = static_cast(n); double_value_ = n; has_double_value_ = true; } } HConstant* HConstant::CopyToRepresentation(Representation r) const { if (r.IsInteger32() && !has_int32_value_) return NULL; if (r.IsDouble() && !has_double_value_) return NULL; return new HConstant(handle_, r); } HConstant* HConstant::CopyToTruncatedInt32() const { if (!has_double_value_) return NULL; int32_t truncated = NumberToInt32(*handle_); return new HConstant(FACTORY->NewNumberFromInt(truncated), Representation::Integer32()); } bool HConstant::ToBoolean() const { // Converts the constant's boolean value according to // ECMAScript section 9.2 ToBoolean conversion. if (HasInteger32Value()) return Integer32Value() != 0; if (HasDoubleValue()) { double v = DoubleValue(); return v != 0 && !isnan(v); } if (handle()->IsTrue()) return true; if (handle()->IsFalse()) return false; if (handle()->IsUndefined()) return false; if (handle()->IsNull()) return false; if (handle()->IsString() && String::cast(*handle())->length() == 0) return false; return true; } void HConstant::PrintDataTo(StringStream* stream) { handle()->ShortPrint(stream); } bool HArrayLiteral::IsCopyOnWrite() const { if (!boilerplate_object_->IsJSObject()) return false; return Handle::cast(boilerplate_object_)->elements()->map() == HEAP->fixed_cow_array_map(); } void HBinaryOperation::PrintDataTo(StringStream* stream) { left()->PrintNameTo(stream); stream->Add("" ""); right()->PrintNameTo(stream); if (CheckFlag(kCanOverflow)) stream->Add("" !""); if (CheckFlag(kBailoutOnMinusZero)) stream->Add("" -0?""); } Range* HBitwise::InferRange(Zone* zone) { if (op() == Token::BIT_XOR) return HValue::InferRange(zone); const int32_t kDefaultMask = static_cast(0xffffffff); int32_t left_mask = (left()->range() != NULL) ? left()->range()->Mask() : kDefaultMask; int32_t right_mask = (right()->range() != NULL) ? right()->range()->Mask() : kDefaultMask; int32_t result_mask = (op() == Token::BIT_AND) ? left_mask & right_mask : left_mask | right_mask; return (result_mask >= 0) ? new(zone) Range(0, result_mask) : HValue::InferRange(zone); } Range* HSar::InferRange(Zone* zone) { if (right()->IsConstant()) { HConstant* c = HConstant::cast(right()); if (c->HasInteger32Value()) { Range* result = (left()->range() != NULL) ? left()->range()->Copy(zone) : new(zone) Range(); result->Sar(c->Integer32Value()); result->set_can_be_minus_zero(false); return result; } } return HValue::InferRange(zone); } Range* HShr::InferRange(Zone* zone) { if (right()->IsConstant()) { HConstant* c = HConstant::cast(right()); if (c->HasInteger32Value()) { int shift_count = c->Integer32Value() & 0x1f; if (left()->range()->CanBeNegative()) { // Only compute bounds if the result always fits into an int32. return (shift_count >= 1) ? new(zone) Range(0, static_cast(0xffffffff) >> shift_count) : new(zone) Range(); } else { // For positive inputs we can use the >> operator. Range* result = (left()->range() != NULL) ? left()->range()->Copy(zone) : new(zone) Range(); result->Sar(c->Integer32Value()); result->set_can_be_minus_zero(false); return result; } } } return HValue::InferRange(zone); } Range* HShl::InferRange(Zone* zone) { if (right()->IsConstant()) { HConstant* c = HConstant::cast(right()); if (c->HasInteger32Value()) { Range* result = (left()->range() != NULL) ? left()->range()->Copy(zone) : new(zone) Range(); result->Shl(c->Integer32Value()); result->set_can_be_minus_zero(false); return result; } } return HValue::InferRange(zone); } Range* HLoadKeyedSpecializedArrayElement::InferRange(Zone* zone) { switch (elements_kind()) { case EXTERNAL_PIXEL_ELEMENTS: return new(zone) Range(0, 255); case EXTERNAL_BYTE_ELEMENTS: return new(zone) Range(-128, 127); case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: return new(zone) Range(0, 255); case EXTERNAL_SHORT_ELEMENTS: return new(zone) Range(-32768, 32767); case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: return new(zone) Range(0, 65535); default: return HValue::InferRange(zone); } } void HCompareGeneric::PrintDataTo(StringStream* stream) { stream->Add(Token::Name(token())); stream->Add("" ""); HBinaryOperation::PrintDataTo(stream); } void HStringCompareAndBranch::PrintDataTo(StringStream* stream) { stream->Add(Token::Name(token())); stream->Add("" ""); HControlInstruction::PrintDataTo(stream); } void HCompareIDAndBranch::PrintDataTo(StringStream* stream) { stream->Add(Token::Name(token())); stream->Add("" ""); left()->PrintNameTo(stream); stream->Add("" ""); right()->PrintNameTo(stream); HControlInstruction::PrintDataTo(stream); } void HCompareObjectEqAndBranch::PrintDataTo(StringStream* stream) { left()->PrintNameTo(stream); stream->Add("" ""); right()->PrintNameTo(stream); HControlInstruction::PrintDataTo(stream); } void HGoto::PrintDataTo(StringStream* stream) { stream->Add(""B%d"", SuccessorAt(0)->block_id()); } void HCompareIDAndBranch::SetInputRepresentation(Representation r) { input_representation_ = r; if (r.IsDouble()) { // According to the ES5 spec (11.9.3, 11.8.5), Equality comparisons (==, === // and !=) have special handling of undefined, e.g. undefined == undefined // is 'true'. Relational comparisons have a different semantic, first // calling ToPrimitive() on their arguments. The standard Crankshaft // tagged-to-double conversion to ensure the HCompareIDAndBranch's inputs // are doubles caused 'undefined' to be converted to NaN. That's compatible // out-of-the box with ordered relational comparisons (<, >, <=, // >=). However, for equality comparisons (and for 'in' and 'instanceof'), // it is not consistent with the spec. For example, it would cause undefined // == undefined (should be true) to be evaluated as NaN == NaN // (false). Therefore, any comparisons other than ordered relational // comparisons must cause a deopt when one of their arguments is undefined. // See also v8:1434 if (!Token::IsOrderedRelationalCompareOp(token_)) { SetFlag(kDeoptimizeOnUndefined); } } else { ASSERT(r.IsInteger32()); } } void HParameter::PrintDataTo(StringStream* stream) { stream->Add(""%u"", index()); } void HLoadNamedField::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add("" @%d%s"", offset(), is_in_object() ? ""[in-object]"" : """"); } HLoadNamedFieldPolymorphic::HLoadNamedFieldPolymorphic(HValue* context, HValue* object, SmallMapList* types, Handle name) : types_(Min(types->length(), kMaxLoadPolymorphism)), name_(name), need_generic_(false) { SetOperandAt(0, context); SetOperandAt(1, object); set_representation(Representation::Tagged()); SetGVNFlag(kDependsOnMaps); for (int i = 0; i < types->length() && types_.length() < kMaxLoadPolymorphism; ++i) { Handle map = types->at(i); LookupResult lookup(map->GetIsolate()); map->LookupInDescriptors(NULL, *name, &lookup); if (lookup.IsFound()) { switch (lookup.type()) { case FIELD: { int index = lookup.GetLocalFieldIndexFromMap(*map); if (index < 0) { SetGVNFlag(kDependsOnInobjectFields); } else { SetGVNFlag(kDependsOnBackingStoreFields); } types_.Add(types->at(i)); break; } case CONSTANT_FUNCTION: types_.Add(types->at(i)); break; default: break; } } } if (types_.length() == types->length() && FLAG_deoptimize_uncommon_cases) { SetFlag(kUseGVN); } else { SetAllSideEffects(); need_generic_ = true; } } bool HLoadNamedFieldPolymorphic::DataEquals(HValue* value) { HLoadNamedFieldPolymorphic* other = HLoadNamedFieldPolymorphic::cast(value); if (types_.length() != other->types()->length()) return false; if (!name_.is_identical_to(other->name())) return false; if (need_generic_ != other->need_generic_) return false; for (int i = 0; i < types_.length(); i++) { bool found = false; for (int j = 0; j < types_.length(); j++) { if (types_.at(j).is_identical_to(other->types()->at(i))) { found = true; break; } } if (!found) return false; } return true; } void HLoadNamedFieldPolymorphic::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add("".""); stream->Add(*String::cast(*name())->ToCString()); } void HLoadNamedGeneric::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add("".""); stream->Add(*String::cast(*name())->ToCString()); } void HLoadKeyedFastElement::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add(""[""); key()->PrintNameTo(stream); stream->Add(""]""); } bool HLoadKeyedFastElement::RequiresHoleCheck() { if (hole_check_mode_ == OMIT_HOLE_CHECK) { return false; } for (HUseIterator it(uses()); !it.Done(); it.Advance()) { HValue* use = it.value(); if (!use->IsChange()) return true; } return false; } void HLoadKeyedFastDoubleElement::PrintDataTo(StringStream* stream) { elements()->PrintNameTo(stream); stream->Add(""[""); key()->PrintNameTo(stream); stream->Add(""]""); } void HLoadKeyedGeneric::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add(""[""); key()->PrintNameTo(stream); stream->Add(""]""); } HValue* HLoadKeyedGeneric::Canonicalize() { // Recognize generic keyed loads that use property name generated // by for-in statement as a key and rewrite them into fast property load // by index. if (key()->IsLoadKeyedFastElement()) { HLoadKeyedFastElement* key_load = HLoadKeyedFastElement::cast(key()); if (key_load->object()->IsForInCacheArray()) { HForInCacheArray* names_cache = HForInCacheArray::cast(key_load->object()); if (names_cache->enumerable() == object()) { HForInCacheArray* index_cache = names_cache->index_cache(); HCheckMapValue* map_check = new(block()->zone()) HCheckMapValue(object(), names_cache->map()); HInstruction* index = new(block()->zone()) HLoadKeyedFastElement( index_cache, key_load->key(), HLoadKeyedFastElement::OMIT_HOLE_CHECK); HLoadFieldByIndex* load = new(block()->zone()) HLoadFieldByIndex( object(), index); map_check->InsertBefore(this); index->InsertBefore(this); load->InsertBefore(this); return load; } } } return this; } void HLoadKeyedSpecializedArrayElement::PrintDataTo( StringStream* stream) { external_pointer()->PrintNameTo(stream); stream->Add("".""); switch (elements_kind()) { case EXTERNAL_BYTE_ELEMENTS: stream->Add(""byte""); break; case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: stream->Add(""u_byte""); break; case EXTERNAL_SHORT_ELEMENTS: stream->Add(""short""); break; case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: stream->Add(""u_short""); break; case EXTERNAL_INT_ELEMENTS: stream->Add(""int""); break; case EXTERNAL_UNSIGNED_INT_ELEMENTS: stream->Add(""u_int""); break; case EXTERNAL_FLOAT_ELEMENTS: stream->Add(""float""); break; case EXTERNAL_DOUBLE_ELEMENTS: stream->Add(""double""); break; case EXTERNAL_PIXEL_ELEMENTS: stream->Add(""pixel""); break; case FAST_ELEMENTS: case FAST_SMI_ONLY_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case DICTIONARY_ELEMENTS: case NON_STRICT_ARGUMENTS_ELEMENTS: UNREACHABLE(); break; } stream->Add(""[""); key()->PrintNameTo(stream); stream->Add(""]""); } void HStoreNamedGeneric::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add("".""); ASSERT(name()->IsString()); stream->Add(*String::cast(*name())->ToCString()); stream->Add("" = ""); value()->PrintNameTo(stream); } void HStoreNamedField::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add("".""); stream->Add(*String::cast(*name())->ToCString()); stream->Add("" = ""); value()->PrintNameTo(stream); stream->Add("" @%d%s"", offset(), is_in_object() ? ""[in-object]"" : """"); if (!transition().is_null()) { stream->Add("" (transition map %p)"", *transition()); } } void HStoreKeyedFastElement::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add(""[""); key()->PrintNameTo(stream); stream->Add(""] = ""); value()->PrintNameTo(stream); } void HStoreKeyedFastDoubleElement::PrintDataTo(StringStream* stream) { elements()->PrintNameTo(stream); stream->Add(""[""); key()->PrintNameTo(stream); stream->Add(""] = ""); value()->PrintNameTo(stream); } void HStoreKeyedGeneric::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add(""[""); key()->PrintNameTo(stream); stream->Add(""] = ""); value()->PrintNameTo(stream); } void HStoreKeyedSpecializedArrayElement::PrintDataTo( StringStream* stream) { external_pointer()->PrintNameTo(stream); stream->Add("".""); switch (elements_kind()) { case EXTERNAL_BYTE_ELEMENTS: stream->Add(""byte""); break; case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: stream->Add(""u_byte""); break; case EXTERNAL_SHORT_ELEMENTS: stream->Add(""short""); break; case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: stream->Add(""u_short""); break; case EXTERNAL_INT_ELEMENTS: stream->Add(""int""); break; case EXTERNAL_UNSIGNED_INT_ELEMENTS: stream->Add(""u_int""); break; case EXTERNAL_FLOAT_ELEMENTS: stream->Add(""float""); break; case EXTERNAL_DOUBLE_ELEMENTS: stream->Add(""double""); break; case EXTERNAL_PIXEL_ELEMENTS: stream->Add(""pixel""); break; case FAST_SMI_ONLY_ELEMENTS: case FAST_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case DICTIONARY_ELEMENTS: case NON_STRICT_ARGUMENTS_ELEMENTS: UNREACHABLE(); break; } stream->Add(""[""); key()->PrintNameTo(stream); stream->Add(""] = ""); value()->PrintNameTo(stream); } void HTransitionElementsKind::PrintDataTo(StringStream* stream) { object()->PrintNameTo(stream); stream->Add("" %p -> %p"", *original_map(), *transitioned_map()); } void HLoadGlobalCell::PrintDataTo(StringStream* stream) { stream->Add(""[%p]"", *cell()); if (!details_.IsDontDelete()) stream->Add("" (deleteable)""); if (details_.IsReadOnly()) stream->Add("" (read-only)""); } bool HLoadGlobalCell::RequiresHoleCheck() { if (details_.IsDontDelete() && !details_.IsReadOnly()) return false; for (HUseIterator it(uses()); !it.Done(); it.Advance()) { HValue* use = it.value(); if (!use->IsChange()) return true; } return false; } void HLoadGlobalGeneric::PrintDataTo(StringStream* stream) { stream->Add(""%o "", *name()); } void HStoreGlobalCell::PrintDataTo(StringStream* stream) { stream->Add(""[%p] = "", *cell()); value()->PrintNameTo(stream); if (!details_.IsDontDelete()) stream->Add("" (deleteable)""); if (details_.IsReadOnly()) stream->Add("" (read-only)""); } void HStoreGlobalGeneric::PrintDataTo(StringStream* stream) { stream->Add(""%o = "", *name()); value()->PrintNameTo(stream); } void HLoadContextSlot::PrintDataTo(StringStream* stream) { value()->PrintNameTo(stream); stream->Add(""[%d]"", slot_index()); } void HStoreContextSlot::PrintDataTo(StringStream* stream) { context()->PrintNameTo(stream); stream->Add(""[%d] = "", slot_index()); value()->PrintNameTo(stream); } // Implementation of type inference and type conversions. Calculates // the inferred type of this instruction based on the input operands. HType HValue::CalculateInferredType() { return type_; } HType HCheckMap::CalculateInferredType() { return value()->type(); } HType HCheckFunction::CalculateInferredType() { return value()->type(); } HType HCheckNonSmi::CalculateInferredType() { // TODO(kasperl): Is there any way to signal that this isn't a smi? return HType::Tagged(); } HType HCheckSmi::CalculateInferredType() { return HType::Smi(); } HType HPhi::CalculateInferredType() { HType result = HType::Uninitialized(); for (int i = 0; i < OperandCount(); ++i) { HType current = OperandAt(i)->type(); result = result.Combine(current); } return result; } HType HConstant::CalculateInferredType() { return HType::TypeFromValue(handle_); } HType HCompareGeneric::CalculateInferredType() { return HType::Boolean(); } HType HInstanceOf::CalculateInferredType() { return HType::Boolean(); } HType HDeleteProperty::CalculateInferredType() { return HType::Boolean(); } HType HInstanceOfKnownGlobal::CalculateInferredType() { return HType::Boolean(); } HType HChange::CalculateInferredType() { if (from().IsDouble() && to().IsTagged()) return HType::HeapNumber(); return type(); } HType HBitwiseBinaryOperation::CalculateInferredType() { return HType::TaggedNumber(); } HType HArithmeticBinaryOperation::CalculateInferredType() { return HType::TaggedNumber(); } HType HAdd::CalculateInferredType() { return HType::Tagged(); } HType HBitNot::CalculateInferredType() { return HType::TaggedNumber(); } HType HUnaryMathOperation::CalculateInferredType() { return HType::TaggedNumber(); } HType HStringCharFromCode::CalculateInferredType() { return HType::String(); } HType HAllocateObject::CalculateInferredType() { return HType::JSObject(); } HType HFastLiteral::CalculateInferredType() { // TODO(mstarzinger): Be smarter, could also be JSArray here. return HType::JSObject(); } HType HArrayLiteral::CalculateInferredType() { return HType::JSArray(); } HType HObjectLiteral::CalculateInferredType() { return HType::JSObject(); } HType HRegExpLiteral::CalculateInferredType() { return HType::JSObject(); } HType HFunctionLiteral::CalculateInferredType() { return HType::JSObject(); } HValue* HUnaryMathOperation::EnsureAndPropagateNotMinusZero( BitVector* visited) { visited->Add(id()); if (representation().IsInteger32() && !value()->representation().IsInteger32()) { if (value()->range() == NULL || value()->range()->CanBeMinusZero()) { SetFlag(kBailoutOnMinusZero); } } if (RequiredInputRepresentation(0).IsInteger32() && representation().IsInteger32()) { return value(); } return NULL; } HValue* HChange::EnsureAndPropagateNotMinusZero(BitVector* visited) { visited->Add(id()); if (from().IsInteger32()) return NULL; if (CanTruncateToInt32()) return NULL; if (value()->range() == NULL || value()->range()->CanBeMinusZero()) { SetFlag(kBailoutOnMinusZero); } ASSERT(!from().IsInteger32() || !to().IsInteger32()); return NULL; } HValue* HForceRepresentation::EnsureAndPropagateNotMinusZero( BitVector* visited) { visited->Add(id()); return value(); } HValue* HMod::EnsureAndPropagateNotMinusZero(BitVector* visited) { visited->Add(id()); if (range() == NULL || range()->CanBeMinusZero()) { SetFlag(kBailoutOnMinusZero); return left(); } return NULL; } HValue* HDiv::EnsureAndPropagateNotMinusZero(BitVector* visited) { visited->Add(id()); if (range() == NULL || range()->CanBeMinusZero()) { SetFlag(kBailoutOnMinusZero); } return NULL; } HValue* HMul::EnsureAndPropagateNotMinusZero(BitVector* visited) { visited->Add(id()); if (range() == NULL || range()->CanBeMinusZero()) { SetFlag(kBailoutOnMinusZero); } return NULL; } HValue* HSub::EnsureAndPropagateNotMinusZero(BitVector* visited) { visited->Add(id()); // Propagate to the left argument. If the left argument cannot be -0, then // the result of the add operation cannot be either. if (range() == NULL || range()->CanBeMinusZero()) { return left(); } return NULL; } HValue* HAdd::EnsureAndPropagateNotMinusZero(BitVector* visited) { visited->Add(id()); // Propagate to the left argument. If the left argument cannot be -0, then // the result of the sub operation cannot be either. if (range() == NULL || range()->CanBeMinusZero()) { return left(); } return NULL; } #define H_CONSTANT_INT32(val) \\ new(zone) HConstant(FACTORY->NewNumberFromInt(val, TENURED), \\ Representation::Integer32()) #define H_CONSTANT_DOUBLE(val) \\ new(zone) HConstant(FACTORY->NewNumber(val, TENURED), \\ Representation::Double()) #define DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HInstr, op) \\ HInstruction* HInstr::New##HInstr(Zone* zone, \\ HValue* context, \\ HValue* left, \\ HValue* right) { \\ if (left->IsConstant() && right->IsConstant()) { \\ HConstant* c_left = HConstant::cast(left); \\ HConstant* c_right = HConstant::cast(right); \\ if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { \\ double double_res = c_left->DoubleValue() op c_right->DoubleValue(); \\ if (TypeInfo::IsInt32Double(double_res)) { \\ return H_CONSTANT_INT32(static_cast(double_res)); \\ } \\ return H_CONSTANT_DOUBLE(double_res); \\ } \\ } \\ return new(zone) HInstr(context, left, right); \\ } DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HAdd, +) DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HMul, *) DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HSub, -) #undef DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR HInstruction* HMod::NewHMod(Zone* zone, HValue* context, HValue* left, HValue* right) { if (left->IsConstant() && right->IsConstant()) { HConstant* c_left = HConstant::cast(left); HConstant* c_right = HConstant::cast(right); if (c_left->HasInteger32Value() && c_right->HasInteger32Value()) { int32_t dividend = c_left->Integer32Value(); int32_t divisor = c_right->Integer32Value(); if (divisor != 0) { int32_t res = dividend % divisor; if ((res == 0) && (dividend < 0)) { return H_CONSTANT_DOUBLE(-0.0); } return H_CONSTANT_INT32(res); } } } return new(zone) HMod(context, left, right); } HInstruction* HDiv::NewHDiv(Zone* zone, HValue* context, HValue* left, HValue* right) { // If left and right are constant values, try to return a constant value. if (left->IsConstant() && right->IsConstant()) { HConstant* c_left = HConstant::cast(left); HConstant* c_right = HConstant::cast(right); if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { if (c_right->DoubleValue() != 0) { double double_res = c_left->DoubleValue() / c_right->DoubleValue(); if (TypeInfo::IsInt32Double(double_res)) { return H_CONSTANT_INT32(static_cast(double_res)); } return H_CONSTANT_DOUBLE(double_res); } } } return new(zone) HDiv(context, left, right); } HInstruction* HBitwise::NewHBitwise(Zone* zone, Token::Value op, HValue* context, HValue* left, HValue* right) { if (left->IsConstant() && right->IsConstant()) { HConstant* c_left = HConstant::cast(left); HConstant* c_right = HConstant::cast(right); if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { int32_t result; int32_t v_left = c_left->NumberValueAsInteger32(); int32_t v_right = c_right->NumberValueAsInteger32(); switch (op) { case Token::BIT_XOR: result = v_left ^ v_right; break; case Token::BIT_AND: result = v_left & v_right; break; case Token::BIT_OR: result = v_left | v_right; break; default: result = 0; // Please the compiler. UNREACHABLE(); } return H_CONSTANT_INT32(result); } } return new(zone) HBitwise(op, context, left, right); } #define DEFINE_NEW_H_BITWISE_INSTR(HInstr, result) \\ HInstruction* HInstr::New##HInstr(Zone* zone, \\ HValue* context, \\ HValue* left, \\ HValue* right) { \\ if (left->IsConstant() && right->IsConstant()) { \\ HConstant* c_left = HConstant::cast(left); \\ HConstant* c_right = HConstant::cast(right); \\ if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { \\ return H_CONSTANT_INT32(result); \\ } \\ } \\ return new(zone) HInstr(context, left, right); \\ } DEFINE_NEW_H_BITWISE_INSTR(HSar, c_left->NumberValueAsInteger32() >> (c_right->NumberValueAsInteger32() & 0x1f)) DEFINE_NEW_H_BITWISE_INSTR(HShl, c_left->NumberValueAsInteger32() << (c_right->NumberValueAsInteger32() & 0x1f)) #undef DEFINE_NEW_H_BITWISE_INSTR HInstruction* HShr::NewHShr(Zone* zone, HValue* context, HValue* left, HValue* right) { if (left->IsConstant() && right->IsConstant()) { HConstant* c_left = HConstant::cast(left); HConstant* c_right = HConstant::cast(right); if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { int32_t left_val = c_left->NumberValueAsInteger32(); int32_t right_val = c_right->NumberValueAsInteger32() & 0x1f; if ((right_val == 0) && (left_val < 0)) { return H_CONSTANT_DOUBLE( static_cast(static_cast(left_val))); } return H_CONSTANT_INT32(static_cast(left_val) >> right_val); } } return new(zone) HShr(context, left, right); } #undef H_CONSTANT_INT32 #undef H_CONSTANT_DOUBLE void HIn::PrintDataTo(StringStream* stream) { key()->PrintNameTo(stream); stream->Add("" ""); object()->PrintNameTo(stream); } // Node-specific verification code is only included in debug mode. #ifdef DEBUG void HPhi::Verify() { ASSERT(OperandCount() == block()->predecessors()->length()); for (int i = 0; i < OperandCount(); ++i) { HValue* value = OperandAt(i); HBasicBlock* defining_block = value->block(); HBasicBlock* predecessor_block = block()->predecessors()->at(i); ASSERT(defining_block == predecessor_block || defining_block->Dominates(predecessor_block)); } } void HSimulate::Verify() { HInstruction::Verify(); ASSERT(HasAstId()); } void HCheckSmi::Verify() { HInstruction::Verify(); ASSERT(HasNoUses()); } void HCheckNonSmi::Verify() { HInstruction::Verify(); ASSERT(HasNoUses()); } void HCheckFunction::Verify() { HInstruction::Verify(); ASSERT(HasNoUses()); } void HCheckPrototypeMaps::Verify() { HInstruction::Verify(); ASSERT(HasNoUses()); } #endif } } // namespace v8::internal ",16349,True,3102.51082328959,median "package GESTE_Fonts.FreeMonoOblique6pt7b is Font : constant Bitmap_Font_Ref; private FreeMonoOblique6pt7bBitmaps : aliased constant Font_Bitmap := ( 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#08#, 16#08#, 16#08#, 16#00#, 16#00#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#36#, 16#24#, 16#24#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#14#, 16#3E#, 16#18#, 16#3C#, 16#28#, 16#28#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#32#, 16#18#, 16#04#, 16#04#, 16#18#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#18#, 16#24#, 16#28#, 16#18#, 16#1E#, 16#2C#, 16#14#, 16#1C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#10#, 16#10#, 16#34#, 16#34#, 16#28#, 16#34#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#08#, 16#08#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#02#, 16#04#, 16#08#, 16#08#, 16#08#, 16#08#, 16#08#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#10#, 16#10#, 16#10#, 16#10#, 16#10#, 16#10#, 16#20#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#1A#, 16#0C#, 16#18#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#08#, 16#3E#, 16#10#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#18#, 16#00#, 16#00#, 16#00#, 16#00#, 16#02#, 16#02#, 16#04#, 16#08#, 16#08#, 16#10#, 16#20#, 16#20#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#12#, 16#22#, 16#22#, 16#22#, 16#24#, 16#24#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#18#, 16#08#, 16#08#, 16#10#, 16#10#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#32#, 16#02#, 16#04#, 16#08#, 16#10#, 16#60#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#02#, 16#02#, 16#0C#, 16#04#, 16#04#, 16#44#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#04#, 16#0C#, 16#14#, 16#14#, 16#24#, 16#3C#, 16#08#, 16#1C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#10#, 16#20#, 16#1C#, 16#02#, 16#02#, 16#04#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#07#, 16#08#, 16#10#, 16#2C#, 16#32#, 16#22#, 16#24#, 16#18#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#12#, 16#04#, 16#04#, 16#08#, 16#08#, 16#10#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#12#, 16#22#, 16#1C#, 16#24#, 16#24#, 16#24#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#12#, 16#22#, 16#22#, 16#1E#, 16#04#, 16#0C#, 16#30#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#00#, 16#00#, 16#00#, 16#18#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#18#, 16#00#, 16#00#, 16#10#, 16#30#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#02#, 16#0C#, 16#30#, 16#10#, 16#0C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#00#, 16#7E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#10#, 16#08#, 16#06#, 16#0C#, 16#30#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0E#, 16#02#, 16#04#, 16#00#, 16#00#, 16#00#, 16#18#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#12#, 16#26#, 16#3C#, 16#34#, 16#2C#, 16#20#, 16#20#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#18#, 16#14#, 16#14#, 16#24#, 16#3C#, 16#44#, 16#E6#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#22#, 16#22#, 16#3C#, 16#22#, 16#42#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1D#, 16#22#, 16#40#, 16#40#, 16#40#, 16#40#, 16#3C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3C#, 16#22#, 16#22#, 16#42#, 16#42#, 16#44#, 16#78#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#20#, 16#20#, 16#38#, 16#28#, 16#42#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3F#, 16#20#, 16#20#, 16#38#, 16#28#, 16#40#, 16#70#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1F#, 16#22#, 16#40#, 16#40#, 16#4E#, 16#42#, 16#3C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#33#, 16#22#, 16#22#, 16#3C#, 16#24#, 16#44#, 16#6E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#08#, 16#08#, 16#08#, 16#10#, 16#10#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0F#, 16#02#, 16#02#, 16#04#, 16#44#, 16#44#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3B#, 16#22#, 16#2C#, 16#38#, 16#44#, 16#44#, 16#66#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3C#, 16#10#, 16#10#, 16#20#, 16#20#, 16#22#, 16#7E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#21#, 16#33#, 16#56#, 16#5A#, 16#42#, 16#42#, 16#E6#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#23#, 16#32#, 16#32#, 16#4A#, 16#4A#, 16#4C#, 16#64#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#22#, 16#42#, 16#42#, 16#42#, 16#44#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3C#, 16#22#, 16#22#, 16#22#, 16#3C#, 16#40#, 16#70#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#22#, 16#42#, 16#42#, 16#42#, 16#44#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#22#, 16#22#, 16#3C#, 16#44#, 16#44#, 16#62#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#22#, 16#20#, 16#1C#, 16#02#, 16#44#, 16#78#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3F#, 16#29#, 16#08#, 16#08#, 16#10#, 16#10#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#33#, 16#22#, 16#22#, 16#22#, 16#22#, 16#24#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#73#, 16#22#, 16#22#, 16#24#, 16#28#, 16#28#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#33#, 16#21#, 16#5A#, 16#5A#, 16#6A#, 16#6C#, 16#44#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#33#, 16#22#, 16#14#, 16#08#, 16#38#, 16#44#, 16#66#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#33#, 16#22#, 16#14#, 16#08#, 16#10#, 16#10#, 16#3C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#22#, 16#04#, 16#18#, 16#20#, 16#44#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#06#, 16#08#, 16#08#, 16#08#, 16#10#, 16#10#, 16#10#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#10#, 16#10#, 16#10#, 16#10#, 16#08#, 16#08#, 16#08#, 16#08#, 16#00#, 16#00#, 16#00#, 16#00#, 16#18#, 16#08#, 16#08#, 16#08#, 16#10#, 16#10#, 16#10#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#14#, 16#22#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#3C#, 16#44#, 16#44#, 16#7E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#20#, 16#20#, 16#20#, 16#3C#, 16#22#, 16#42#, 16#42#, 16#FC#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#22#, 16#40#, 16#40#, 16#3C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#02#, 16#02#, 16#02#, 16#1E#, 16#22#, 16#44#, 16#44#, 16#3A#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#62#, 16#7E#, 16#40#, 16#3C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#07#, 16#08#, 16#10#, 16#3E#, 16#10#, 16#10#, 16#10#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1F#, 16#22#, 16#44#, 16#44#, 16#3C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#20#, 16#20#, 16#20#, 16#3C#, 16#22#, 16#42#, 16#44#, 16#6E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#00#, 16#18#, 16#08#, 16#10#, 16#10#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#04#, 16#00#, 16#3C#, 16#04#, 16#04#, 16#08#, 16#08#, 16#00#, 16#00#, 16#00#, 16#00#, 16#30#, 16#20#, 16#20#, 16#26#, 16#28#, 16#30#, 16#28#, 16#4E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#18#, 16#08#, 16#08#, 16#08#, 16#10#, 16#10#, 16#10#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#76#, 16#4A#, 16#52#, 16#52#, 16#DA#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3C#, 16#22#, 16#42#, 16#42#, 16#66#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#22#, 16#42#, 16#44#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#7C#, 16#22#, 16#42#, 16#22#, 16#5C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1F#, 16#22#, 16#42#, 16#44#, 16#3C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#36#, 16#18#, 16#20#, 16#20#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#22#, 16#1C#, 16#44#, 16#78#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#10#, 16#20#, 16#3C#, 16#20#, 16#20#, 16#20#, 16#3C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#26#, 16#24#, 16#24#, 16#24#, 16#3E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#77#, 16#22#, 16#24#, 16#28#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#63#, 16#4A#, 16#4A#, 16#7C#, 16#24#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#36#, 16#24#, 16#18#, 16#34#, 16#6E#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#33#, 16#22#, 16#24#, 16#28#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#24#, 16#18#, 16#20#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#04#, 16#08#, 16#08#, 16#08#, 16#38#, 16#10#, 16#10#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#08#, 16#08#, 16#08#, 16#10#, 16#10#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#08#, 16#08#, 16#08#, 16#04#, 16#08#, 16#10#, 16#10#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#32#, 16#0C#, 16#00#, 16#00#, 16#00#); Font_D : aliased constant Bitmap_Font := ( Bytes_Per_Glyph => 12, Glyph_Width => 8, Glyph_Height => 12, Data => FreeMonoOblique6pt7bBitmaps'Access); Font : constant Bitmap_Font_Ref := Font_D'Access; end GESTE_Fonts.FreeMonoOblique6pt7b; ",8276,True,3362.9707068489265,median "/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include ""hphp/runtime/base/stats.h"" #include ""hphp/runtime/vm/jit/abi-x64.h"" #include ""hphp/runtime/vm/jit/abi-arm.h"" #include ""hphp/runtime/vm/jit/print.h"" #include ""hphp/runtime/vm/jit/punt.h"" #include ""hphp/runtime/vm/jit/reg-algorithms.h"" #include ""hphp/runtime/vm/jit/vasm-print.h"" #include ""hphp/runtime/vm/jit/vasm-x64.h"" #include ""hphp/runtime/vm/jit/mc-generator.h"" #include ""hphp/runtime/base/arch.h"" #include ""hphp/util/assertions.h"" #include ""hphp/util/ringbuffer.h"" #include #include // future work // - #3098509 streamline code, vectors vs linked lists, etc // - #3409409 Enable use of SIMD at least for doubles, for packed_tv // - #3098685 Optimize lifetime splitting // - #3098712 reuse spill slots // - #3098739 new features now possible with XLS TRACE_SET_MOD(xls); namespace HPHP { namespace jit { using Trace::RingBufferType; using Trace::ringbufferName; namespace { using namespace Stats; size_t s_counter; // Sort blocks in reverse postorder, and try to arrange fall-through // blocks in the same area to be close together. struct BlockSorter { explicit BlockSorter(const Vunit& unit) : unit(unit) , visited(unit.blocks.size()) { blocks.reserve(unit.blocks.size()); } unsigned area(Vlabel b) { return (unsigned)unit.blocks[b].area; } void dfs(Vlabel b) { assert(size_t(b) < unit.blocks.size() && !unit.blocks[b].code.empty()); if (visited.test(b)) return; visited.set(b); if (area(b) == 0) { for (auto s : succs(unit.blocks[b])) { // visit colder if (area(s) > area(b)) dfs(s); } for (auto s : succs(unit.blocks[b])) { if (area(s) <= area(b)) dfs(s); } } else { for (auto s : succs(unit.blocks[b])) dfs(s); } blocks.push_back(b); } const Vunit& unit; jit::vector blocks; boost::dynamic_bitset<> visited; }; // A Use refers to the position where an interval is used or defined struct Use { VregKind kind; unsigned pos; Vreg hint; // if valid, try to use same vreg as this }; // A LiveRange is an closed-open range of positions where an interval is live. // Specifically, for the LiveRange [start, end), start is in the range and // end is not. struct LiveRange { bool contains(unsigned pos) const { return pos >= start && pos < end; } bool intersects(LiveRange r) const { return r.start < end && start < r.end; } bool contains(LiveRange r) const; public: unsigned start, end; }; typedef jit::vector RangeList; typedef jit::vector UseList; // An Interval stores the lifetime of an Vreg as a sorted list of disjoint // ranges, and a sorted list of use positions. If this interval was split, // then the first interval is deemed ""parent"" and the rest are ""children"", // and they're all connected as a singly linked list sorted by start. // // Every use position must be inside one of the ranges, or exactly at the // end of the last range. Allowing a use exactly at the end facilitates // lifetime splitting when the use at the position of an instruction // clobbers registers as a side effect, e.g. a call. struct Interval { explicit Interval(Vreg r) : parent(nullptr), vreg(r) {} explicit Interval(Interval* parent) : parent(parent) , vreg(parent->vreg) , wide(parent->wide) , cns(parent->cns) , val(parent->val) {} // accessors unsigned start() const { return ranges.front().start; } unsigned end() const { return ranges.back().end; } bool fixed() const { return vreg.isPhys(); } Interval* leader() { return parent ? parent : this; } bool spilled() const { return reg == InvalidReg && slot >= 0; } // queries unsigned findRange(unsigned pos) const; unsigned findUse(unsigned pos) const; bool covers(unsigned pos) const; bool usedAt(unsigned pos) const; unsigned firstUseAfter(unsigned pos) const; unsigned lastUseBefore(unsigned pos) const; unsigned firstUse() const; Interval* childAt(unsigned pos); // mutators void add(LiveRange r); Interval* split(unsigned pos, bool keep_uses = false); // debugging std::string toString(); public: Interval* const parent; Interval* next{nullptr}; RangeList ranges; UseList uses; const Vreg vreg; unsigned def_pos; int slot{-1}; bool wide{false}; PhysReg reg; bool cns{false}; uint64_t val; }; typedef boost::dynamic_bitset<> LiveSet; typedef std::pair EdgeKey; struct EdgeHasher { size_t operator()(EdgeKey k) const { return size_t(k.first) ^ k.second; } }; typedef PhysReg::Map CopyPlan; typedef PhysReg::Map PosVec; // Extended Linear Scan register allocator over vasm virtual registers (Vregs). // This encapsulates the intermediate data structures used during the algorithm // so we don't have to pass them around everywhere. struct Vxls { Vxls(Vunit& unit, const Abi& abi) : unit(unit) , m_abi(abi) , m_sp(mcg->backEnd().rSp()) { switch (arch()) { case Arch::X64: m_tmp = reg::xmm15; // reserve xmm15 to break shuffle cycles m_srkill = RegSet(x64::rAsm); break; case Arch::ARM: m_tmp = vixl::x17; // also used as tmp1 by MacroAssembler m_srkill = RegSet(arm::rAsm);//m_abi.all(); break; } m_abi.simdUnreserved.remove(m_tmp); m_abi.simdReserved.add(m_tmp); assert(!m_abi.gpUnreserved.contains(m_sp)); assert(!m_abi.gpUnreserved.contains(m_tmp)); } ~Vxls(); // phases void allocate(); void splitCritEdges(); void computePositions(); void analyzeRsp(); void buildIntervals(); void walkIntervals(); void renameOperands(); void resolveSplits(); void lowerCopyargs(); void resolveEdges(); void insertCopies(); // utilities void update(unsigned pos); void allocate(Interval*); void allocBlocked(Interval*); void assignReg(Interval*, PhysReg); unsigned constrain(Interval*, RegSet&); void insertSpill(Interval*); Vlabel findBlock(unsigned pos); LiveRange findBlockRange(unsigned pos); void spill(Interval*); void spillAfter(Interval* ivl, unsigned pos); void spillOthers(Interval* current, PhysReg r); void assignSpill(Interval* ivl); void insertCopiesAt(jit::vector& code, unsigned& j, const CopyPlan&, MemoryRef slots, unsigned pos); void insertSpillsAt(jit::vector& code, unsigned& j, const CopyPlan&, MemoryRef slots, unsigned pos); PhysReg findHint(Interval* current, const PosVec& free_until, RegSet allow); unsigned nearestSplitBefore(unsigned pos); void forwardJmp(Vlabel middleLabel, Vlabel destLabel); // debugging void print(const char* caption); void printInstr(std::ostringstream& out, Vinstr* instr, unsigned pos, Vlabel); void dumpIntervals(); int spEffect(Vinstr& inst) const; void getEffects(const Vinstr& i, RegSet& uses, RegSet& across, RegSet& defs); public: struct Compare { bool operator()(const Interval*, const Interval*); }; public: Vunit& unit; Abi m_abi; PhysReg m_sp; // arch-dependent stack pointer PhysReg m_tmp; // only for breaking cycles RegSet m_srkill; // killed by service requests jit::vector blocks; // sorted blocks jit::vector block_ranges; // [start,end) position of each block jit::vector spill_offsets; // per-block sp[offset] to spill-slots jit::vector livein; // per-block live-in sets jit::vector intervals; // parent intervals, null if unused jit::priority_queue pending; // sorted by Interval start jit::vector active, inactive; // intervals that overlap jit::hash_map copies; // where to insert copies jit::hash_map spills; // where to insert spills jit::hash_map edge_copies; // copies on edges unsigned m_nextSlot{0}; // next available spill slot }; ////////////////////////////////////////////////////////////////////////////// const unsigned kMaxPos = UINT_MAX; // ""infinity"" use position // comparison function for pending priority queue. priority_queue // requires a less operation, but sorts the heap highest-first; we // need the opposite (lowest-first), so use greater-than. bool Vxls::Compare::operator()(const Interval* i1, const Interval* i2) { return i1->start() > i2->start(); } ////////////////////////////////////////////////////////////////////////////// // returns true if this range contains r bool LiveRange::contains(LiveRange r) const { return r.start >= start && r.end <= end; } ////////////////////////////////////////////////////////////////////////////// template void forEach(LiveSet& bits, Fn fn) { for (auto i = bits.find_first(); i != bits.npos; i = bits.find_next(i)) { fn(Vreg(i)); } } ////////////////////////////////////////////////////////////////////////////// void Interval::add(LiveRange r) { while (!ranges.empty() && r.contains(ranges.back())) { ranges.pop_back(); } if (ranges.empty()) { return ranges.push_back(r); } auto& first = ranges.back(); if (first.contains(r)) return; if (r.end >= first.start) { first.start = r.start; } else { ranges.push_back(r); } } // Return range index containing or higher than pos unsigned Interval::findRange(unsigned pos) const { unsigned lo = 0; for (unsigned hi = ranges.size(); lo < hi;) { auto mid = (lo + hi) / 2; auto r = ranges[mid]; if (pos < r.start) { hi = mid; } else if (r.end <= pos) { lo = mid + 1; } else { return mid; } } assert(lo == ranges.size() || pos < ranges[lo].start); return lo; } unsigned Interval::findUse(unsigned pos) const { unsigned lo = 0, hi = uses.size(); while (lo < hi) { auto mid = (lo + hi) / 2; auto u = uses[mid].pos; if (pos < u) { hi = mid; } else if (u < pos) { lo = mid + 1; } else { return mid; } } assert(lo == uses.size() || pos < uses[lo].pos); return lo; } // Return true if one of the ranges in this interval includes pos bool Interval::covers(unsigned pos) const { if (pos < start() || pos >= end()) return false; auto i = ranges.begin() + findRange(pos); return i != ranges.end() && i->contains(pos); } // Return true if there is a use position at pos bool Interval::usedAt(unsigned pos) const { if (pos < start() || pos > end()) return false; auto i = uses.begin() + findUse(pos); return i != uses.end() && pos == i->pos; } // Return the interval which has a use position at pos Interval* Interval::childAt(unsigned pos) { assert(!parent); for (auto ivl = this; ivl; ivl = ivl->next) { if (pos < ivl->start()) return nullptr; if (ivl->usedAt(pos)) return ivl; } return nullptr; } // Return the next intersection point between current and other, or kMaxPos // if they never intersect. unsigned nextIntersect(Interval* current, Interval* other) { assert(!current->fixed()); if (!current->parent && !other->parent && !other->fixed()) { // Since other is inactive, it cannot cover current's start, and // current cannot cover other's start, since other started earlier. // Therefore, SSA guarantees no intersection. return kMaxPos; } if (current->end() <= other->start()) { // current ends before other starts. return kMaxPos; } // r1,e1 span all of current auto r1 = current->ranges.begin(); auto e1 = current->ranges.end(); // r2,e2 span the tail of other that might intersect current auto r2 = other->ranges.begin() + other->findRange(current->start()); auto e2 = other->ranges.end(); // search for the lowest position covered by current and other for (;;) { if (r1->start < r2->start) { if (r2->start < r1->end) return r2->start; if (++r1 == e1) return kMaxPos; } else { if (r1->start < r2->end) return r1->start; if (++r2 == e2) return kMaxPos; } } return kMaxPos; } // Return the position of the next use >= pos. // If there are no more uses after pos, return kMaxPos. unsigned Interval::firstUseAfter(unsigned pos) const { auto u = uses.begin() + findUse(pos); return u != uses.end() && pos <= u->pos ? u->pos : kMaxPos; } // Return the position of the latest use <= pos. // If the first use is after pos, return 0. unsigned Interval::lastUseBefore(unsigned pos) const { auto prev = 0; for (auto& u : uses) { if (u.pos > pos) return prev; prev = u.pos; } return prev; } // Return the position of the first use that requires a register, // or kMaxPos if no remaining uses need registers. unsigned Interval::firstUse() const { return uses.empty() ? kMaxPos : uses.front().pos; } // Split this interval at pos and return the rest. Pos must be a location // that ensures both shorter intervals are nonempty. If keep_uses is set, Uses // exactly at the end of the first interval will stay with the first part. Interval* Interval::split(unsigned pos, bool keep_uses) { assert(pos > start() && pos < end()); // both parts will be non-empty auto leader = this->leader(); Interval* child = jit::make(leader); child->next = next; next = child; // advance r1 to the first range we want in child; maybe split a range. auto r1 = ranges.begin() + findRange(pos); if (pos > r1->start) { // split r at pos child->ranges.push_back({pos, r1->end}); r1->end = pos; r1++; } child->ranges.insert(child->ranges.end(), r1, ranges.end()); ranges.erase(r1, ranges.end()); // advance u1 to the first use position in child, then copy u1..end to child. auto u1 = uses.begin() + findUse(end()); auto u2 = uses.end(); if (keep_uses) { while (u1 != u2 && u1->pos <= end()) u1++; } else { while (u1 != u2 && u1->pos < child->start()) u1++; } child->uses.insert(child->uses.end(), u1, u2); uses.erase(u1, u2); return child; } ////////////////////////////////////////////////////////////////////////////// Vxls::~Vxls() { for (auto ivl : intervals) { for (Interval* next; ivl; ivl = next) { next = ivl->next; jit::destroy(ivl); } } } bool is_nop(copy& i) { return i.s == i.d; } bool is_nop(copy2& i) { return i.s0 == i.d0 && i.s1 == i.d1; } bool is_nop(lea& i) { return i.s.disp == 0 && ( (i.s.base == i.d && !i.s.index.isValid()) || (!i.s.base.isValid() && i.s.index == i.d && i.s.scale == 1)); } /* * Extended Linear Scan is based on Wimmer & Franz ""Linear Scan Register * Allocation on SSA Form"". As currently written, it also works on non-ssa * input. * * 1. Sort blocks such that all predecessors of B come before B, except * loop-edge predecessors. If the input IR is in SSA form, this also * implies the definition of each SSATmp comes before all uses. * * 2. Assign an even numbered position to every instruction. Positions * between instructions are used to insert copies and spills. Each block * starts with an extra position number that corresponds to an imaginary * ""label"" instruction that is not physically in the vasm IR. * * 3. Create one interval I for each Vreg R that requires register allocation, * by iterating blocks and instructions in reverse order, computing live * registers as we go. Each interval consists of a sorted list of disjoint, * live ranges covering the positions where R must be in a physical register * or spill slot. Vregs that are constants or have forced registers * (e.g. VmSp) are skipped. If the input is SSA, the start position of each * interval dominates every live range and use position in the interval. * * 4. Process intervals in order of start position, maintaining the set of * active (live) and inactive (not live, but with live ranges that start * after the current interval). When choosing a register, prefer the one * available furthest into the future. If necessary, split the current * interval so the first part gets a register, and enqueue the rest. * When no registers are available, choose either the current interval or * another one to spill, trying to free up the longest-available register. * * Split positions must be after an interval's start position, and on or before * the chosen split point. We're free try to choose a good position inbetween, * for example block boundaries and cold blocks. * * 5. Once intervals have been walked and split, every interval has an assigned * operand (register or spill location) for all positions where its alive. * visit every instruction and modify its Vreg operands to the physical * register that was assigned. * * 6. Splitting creates sub-intervals that are assigned to different registers * or spill locations, so insert resolving copies at the split positions * between intervals that were split in a block, and copies on control-flow * edges connecting different sub-intervals. When more than one copy occurs * in a position, they are parallel-copies (all sources read before any dest * is written). * * If any sub-interval was spilled, we a single store is generated after each * definition point. */ void Vxls::allocate() { blocks = sortBlocks(unit); assert(check(unit)); splitCritEdges(); computePositions(); analyzeRsp(); buildIntervals(); walkIntervals(); resolveSplits(); lowerCopyargs(); resolveEdges(); renameOperands(); insertCopies(); // we're completely done. remove nop-copies for (auto b : blocks) { auto& code = unit.blocks[b].code; auto end = std::remove_if(code.begin(), code.end(), [&](Vinstr& inst) { return (inst.op == Vinstr::copy && is_nop(inst.copy_)) || (inst.op == Vinstr::copy2 && is_nop(inst.copy2_)) || (inst.op == Vinstr::lea && is_nop(inst.lea_)) || (inst.op == Vinstr::copyargs) || // we lowered it (inst.op == Vinstr::nop) || // we inserted it (inst.op == Vinstr::phidef); // we lowered it }); code.erase(end, code.end()); } printUnit(kVasmRegAllocLevel, ""after vasm-xls"", unit); } void Vxls::forwardJmp(Vlabel middleLabel, Vlabel destLabel) { auto& middle = unit.blocks[middleLabel]; auto& dest = unit.blocks[destLabel]; // We need to preserve any phidefs in the forwarding block if they're present // in the original destination block. auto& headInst = dest.code.front(); if (headInst.op == Vinstr::phidef) { auto tuple = headInst.phidef_.defs; auto forwardedRegs = unit.tuples[tuple]; VregList regs(forwardedRegs.size()); for (unsigned i = 0; i < forwardedRegs.size(); ++i) { regs[i] = unit.makeReg(); } auto newTuple = unit.makeTuple(regs); middle.code.emplace_back(phidef{newTuple}); middle.code.emplace_back(phijmp{destLabel, newTuple}); return; } middle.code.emplace_back(jmp{destLabel}); } void Vxls::splitCritEdges() { jit::vector preds(unit.blocks.size()); for (auto pred : blocks) { auto succlist = succs(unit.blocks[pred]); for (auto succ : succlist) { preds[succ]++; } } auto resort = false; for (auto pred : blocks) { auto succlist = succs(unit.blocks[pred]); if (succlist.size() <= 1) continue; for (auto& succ : succlist) { if (preds[succ] <= 1) continue; // split the critical edge. auto middle = unit.makeBlock(unit.blocks[succ].area); forwardJmp(middle, succ); succ = middle; resort = true; } } if (resort) { blocks = sortBlocks(unit); } } // compute the linear position range of each block void Vxls::computePositions() { block_ranges.resize(unit.blocks.size()); unsigned pos = 0; for (auto b : blocks) { auto& code = unit.blocks[b].code; bool front_uses{false}; visitUses(unit, code.front(), [&](Vreg r) { front_uses = true; }); if (front_uses) { code.insert(code.begin(), nop{}); } auto start = pos; for (auto& inst : unit.blocks[b].code) { inst.pos = pos; pos += 2; } block_ranges[b] = { start, pos }; } } // Return the effect this instruction has on the value of sp. // this will assert if an instruction mutates sp in an untrackable way. int Vxls::spEffect(Vinstr& inst) const { switch (inst.op) { default: if (debug) visitDefs(unit, inst, [&](Vreg r) { assert(r != m_sp); }); return 0; case Vinstr::push: case Vinstr::pushl: case Vinstr::pushm: return -8; case Vinstr::pop: case Vinstr::popm: return 8; case Vinstr::addqi: { auto& i = inst.addqi_; if (i.d == Vreg64(m_sp)) { assert(i.s1 == Vreg64(m_sp)); return i.s0.l(); } return 0; } case Vinstr::subqi: { auto& i = inst.subqi_; if (i.d == Vreg64(m_sp)) { assert(i.s1 == Vreg64(m_sp)); return -i.s0.l(); } return 0; } } } // compute the offset from RSP to the spill area at each block start. void Vxls::analyzeRsp() { auto num_blocks = unit.blocks.size(); boost::dynamic_bitset<> visited(num_blocks); spill_offsets.resize(num_blocks); for (auto b : blocks) { int offset; if (visited.test(b)) { offset = spill_offsets[b]; } else { offset = 0; } for (auto& inst : unit.blocks[b].code) { offset -= spEffect(inst); } for (auto s : succs(unit.blocks[b])) { if (visited.test(s)) { assert_flog(offset == spill_offsets[s], ""sp mismatch on edge B{}->B{}, expected {} got {}"", size_t(b), size_t(s), spill_offsets[s], offset); } else { spill_offsets[s] = offset; visited.set(s); } } } } // Visits defs of an instruction, updates their liveness, adds live // ranges, and adds Uses with appropriate hints. struct DefVisitor { DefVisitor(LiveSet& live, Vxls& vxls, unsigned pos) : m_intervals(vxls.intervals) , m_tuples(vxls.unit.tuples) , m_live(live) , m_pos(pos) {} template void imm(const F&){} // skip immediates template void use(R){} // skip uses template void useHint(S, H){} // skip uses template void across(R){} // skip uses void def(Vtuple defs) { for (auto r : m_tuples[defs]) def(r); } void defHint(Vtuple def_tuple, Vtuple hint_tuple) { auto& defs = m_tuples[def_tuple]; auto& hints = m_tuples[hint_tuple]; for (int i = 0; i < defs.size(); i++) { def(defs[i], VregKind::Any, hints[i]); } } template void defHint(D dst, H hint) { def(dst, dst.kind, hint, dst.bits == 128); } template void def(R r) { def(r, r.kind, Vreg{}, r.bits == 128); } void def(Vreg r) { def(r, VregKind::Any); } void defHint(Vreg d, Vreg hint) { def(d, VregKind::Any, hint); } void def(RegSet rs) { rs.forEach([&](Vreg r) { def(r); }); } private: void def(Vreg r, VregKind kind, Vreg hint = Vreg{}, bool wide = false) { auto ivl = m_intervals[r]; if (m_live.test(r)) { m_live.reset(r); ivl->ranges.back().start = m_pos; } else { if (!ivl) { ivl = m_intervals[r] = jit::make(r); } ivl->add({m_pos, m_pos + 1}); } if (!ivl->fixed()) { ivl->uses.push_back(Use{kind, m_pos, hint}); ivl->wide |= wide; ivl->def_pos = m_pos; } i++; } private: jit::vector& m_intervals; jit::vector& m_tuples; LiveSet& m_live; unsigned m_pos; unsigned i{0}; }; // this kinda sucks, but I can't use a lambda to handle Vreg and Vptr // at the same time. struct UseVisitor { UseVisitor(LiveSet& live, Vxls& vxls, LiveRange range) : m_intervals(vxls.intervals) , m_tuples(vxls.unit.tuples) , m_live(live) , m_range(range) {} template void imm(const F&){} // skip immediates template void def(R){} // skip defs template void defHint(D, H){} // skip defs void use(Vptr m) { if (m.base.isValid()) use(m.base); if (m.index.isValid()) use(m.index); } void use(Vtuple uses) { for (auto r : m_tuples[uses]) use(r); } void use(VcallArgsId id) { always_assert(false && ""vcall unsupported in vxls""); } void useHint(Vtuple src_tuple, Vtuple hint_tuple) { auto& uses = m_tuples[src_tuple]; auto& hints = m_tuples[hint_tuple]; for (int i = 0, n = uses.size(); i < n; i++) { useHint(uses[i], hints[i]); } } void use(RegSet regs) { regs.forEach([&](Vreg r) { use(r); }); } void across(RegSet regs) { regs.forEach([&](Vreg r) { across(r); }); } template void use(R r) { use(r, r.kind, m_range.end); } template void useHint(S src, H hint) { use(src, src.kind, m_range.end, hint); } void use(Vreg r, VregKind kind, unsigned end, Vreg hint = Vreg{}) { m_live.set(r); auto ivl = m_intervals[r]; if (!ivl) ivl = m_intervals[r] = jit::make(r); ivl->add({m_range.start, end}); if (!ivl->fixed()) { ivl->uses.push_back({kind, m_range.end, hint}); } } // An operand marked as UA means use-after or use-across. Mark it live // across the instruction so its lifetime conflicts with the destination, // which ensures it will be assigned a different register than the // destination. This isn't necessary if *both* operands of a binary // instruction are the same virtual register, but is still correct. template void across(R r) { use(r, r.kind, m_range.end + 1); } private: jit::vector& m_intervals; jit::vector& m_tuples; LiveSet& m_live; const LiveRange m_range; }; // Return the set of physical registers implicitly accessed (used or defined) // TODO: t4779515: replace this, and other switches, with logic using // attributes, instead of hardcoded opcode names. void Vxls::getEffects(const Vinstr& i, RegSet& uses, RegSet& across, RegSet& defs) { uses = defs = across = RegSet(); switch (i.op) { case Vinstr::mccall: case Vinstr::call: case Vinstr::callm: case Vinstr::callr: defs = m_abi.all() - m_abi.calleeSaved; break; case Vinstr::callstub: defs = i.callstub_.kills; break; case Vinstr::bindcall: case Vinstr::contenter: case Vinstr::nativeimpl: defs = m_abi.all(); break; case Vinstr::cqo: uses = RegSet(reg::rax); defs = RegSet().add(reg::rax).add(reg::rdx); break; case Vinstr::idiv: uses = defs = RegSet(reg::rax).add(reg::rdx); break; case Vinstr::shlq: case Vinstr::sarq: across = RegSet(reg::rcx); break; case Vinstr::resume: case Vinstr::retransopt: case Vinstr::bindaddr: case Vinstr::bindjcc1st: case Vinstr::bindjcc2nd: case Vinstr::bindjmp: case Vinstr::bindexit: defs = m_srkill; break; // arm instrs case Vinstr::hostcall: defs = (m_abi.all() - m_abi.calleeSaved) | RegSet(PhysReg(arm::rHostCallReg)); break; case Vinstr::vcall: case Vinstr::vinvoke: always_assert(false && ""Unsupported instruction in vxls""); default: break; } } // Compute lifetime intervals and use positions of all intervals by walking // the code bottom-up once. Loops aren't handled yet. void Vxls::buildIntervals() { if (dumpIREnabled(kRegAllocLevel)) { printCfg(unit, blocks); } livein.resize(unit.blocks.size()); intervals.resize(unit.next_vr); auto loops = false; auto preds = computePreds(unit); for (auto blockIt = blocks.end(); blockIt != blocks.begin();) { auto b = *--blockIt; auto& block = unit.blocks[b]; // initial live set is the union of successor live sets. LiveSet live(unit.next_vr); for (auto s : succs(block)) { if (!livein[s].empty()) { live |= livein[s]; } else { loops = true; } } // add a range covering the whole block to every live interval auto& block_range = block_ranges[b]; forEach(live, [&](Vreg r) { intervals[r]->add(block_range); }); // visit instructions bottom-up, adding uses & ranges auto pos = block_range.end; for (auto i = block.code.end(); i != block.code.begin();) { auto& inst = *--i; pos -= 2; DefVisitor dv(live, *this, pos); UseVisitor uv(live, *this, {block_range.start, pos}); visitOperands(inst, dv); RegSet implicit_uses, implicit_across, implicit_defs; getEffects(inst, implicit_uses, implicit_across, implicit_defs); dv.def(implicit_defs); visitOperands(inst, uv); uv.use(implicit_uses); uv.across(implicit_across); } // save live set so it can propagate to predecessors livein[b] = live; // add a loop-covering range to each interval live into a loop. for (auto p: preds[b]) { auto pred_end = block_ranges[p].end; if (pred_end > block_range.start) { forEach(live, [&](Vreg r) { auto ivl = intervals[r]; ivl->add(LiveRange{block_range.start, pred_end}); }); } } } // finish processing live ranges for constants for (auto& c : unit.cpool) { if (auto ivl = intervals[c.second]) { ivl->ranges.back().start = 0; ivl->cns = true; ivl->val = c.first; } } // Ranges and uses were generated in reverse order. Unreverse them now. for (auto ivl : intervals) { if (!ivl) continue; assert(!ivl->ranges.empty()); // no empty intervals std::reverse(ivl->uses.begin(), ivl->uses.end()); std::reverse(ivl->ranges.begin(), ivl->ranges.end()); } if (dumpIREnabled(kRegAllocLevel)) { if (loops) HPHP::Trace::traceRelease(""vasm-loops\\n""); print(""after building intervals""); } // only constants and physical registers can be live-into the entry block. if (debug) { forEach(livein[unit.entry], [&](Vreg r) { UNUSED auto ivl = intervals[r]; assert(ivl->cns || ivl->fixed()); }); for (auto ivl : intervals) { if (!ivl) continue; for (unsigned i = 1; i < ivl->uses.size(); i++) { assert(ivl->uses[i].pos >= ivl->uses[i-1].pos); // monotonic } for (unsigned i = 1; i < ivl->ranges.size(); i++) { assert(ivl->ranges[i].end > ivl->ranges[i].start); // no empty ranges assert(ivl->ranges[i].start > ivl->ranges[i-1].end); // no empty gaps } } } } void Vxls::walkIntervals() { for (auto ivl : intervals) { if (!ivl) continue; if (ivl->fixed()) { assignReg(ivl, ivl->vreg); } else if (ivl->cns) { spill(ivl); } else { pending.push(ivl); } } while (!pending.empty()) { auto current = pending.top(); pending.pop(); update(current->start()); allocate(current); } } void erase(jit::vector& list, jit::vector::iterator i) { *i = list.back(); list.pop_back(); } // Update active and inactive lists based on pos void Vxls::update(unsigned pos) { // check for active intervals in that are expired or inactive for (auto i = active.begin(); i != active.end();) { auto ivl = *i; if (pos >= ivl->end()) { erase(active, i); } else if (!ivl->covers(pos)) { erase(active, i); inactive.push_back(ivl); } else { i++; } } // check for intervals that are expired or active for (auto i = inactive.begin(); i != inactive.end();) { auto ivl = *i; if (pos >= ivl->end()) { erase(inactive, i); } else if (ivl->covers(pos)) { erase(inactive, i); active.push_back(ivl); } else { i++; } } } PhysReg find(const PosVec& posns) { unsigned max = 0; PhysReg r1 = *posns.begin(); for (auto r : posns) { if (posns[r] > max) { r1 = r; max = posns[r]; } } return r1; } // Constrain the allowable registers for ivl by inspecting uses, and // return the latest position for which that set is valid. unsigned Vxls::constrain(Interval* ivl, RegSet& allow) { auto const any = m_abi.unreserved() - m_abi.sf; // Any but not flags. allow = m_abi.unreserved(); for (auto& u : ivl->uses) { auto need = u.kind == VregKind::Simd ? m_abi.simdUnreserved : u.kind == VregKind::Gpr ? m_abi.gpUnreserved : u.kind == VregKind::Sf ? m_abi.sf : /* VregKind::Any */ any; if ((allow & need).empty()) { // cannot satisfy constraints; must split before u.pos return u.pos - 1; } allow &= need; } return kMaxPos; } // return the closest split position on or before pos. // the result might be exactly on an edge, or inbetween normal positions. unsigned Vxls::nearestSplitBefore(unsigned pos) { auto b = findBlock(pos); auto range = block_ranges[b]; if (pos == range.start) return pos; return (pos - 1) | 1; } // Return the first usable hint from all the uses in this interval. // Skip uses that don't have any hint, or have an unsable hint. PhysReg Vxls::findHint(Interval* current, const PosVec& free_until, RegSet allow) { if (!RuntimeOption::EvalHHIREnablePreColoring && !RuntimeOption::EvalHHIREnableCoalescing) return InvalidReg; // search ivl for the register assigned to a sub-interval that ends at pos. auto search = [&](Interval* ivl, unsigned pos) -> PhysReg { for (; ivl; ivl = ivl->next) { if (pos == ivl->end() && ivl->reg != InvalidReg) return ivl->reg; } return InvalidReg; }; for (auto u : current->uses) { if (!u.hint.isValid()) continue; auto hint_ivl = intervals[u.hint]; PhysReg hint; if (hint_ivl->fixed()) { hint = hint_ivl->reg; } else if (u.pos == current->def_pos) { // this is a def, so u.hint is a src hint = search(hint_ivl, u.pos); } if (hint == InvalidReg) continue; if (!allow.contains(hint)) continue; if (free_until[hint] >= current->end()) { return hint; } } return InvalidReg; } void Vxls::allocate(Interval* current) { PosVec free_until; // 0 by default RegSet allow; unsigned conflict = constrain(current, allow); allow.forEach([&](PhysReg r) { free_until[r] = conflict; }); for (auto ivl : active) { free_until[ivl->reg] = 0; } for (auto ivl : inactive) { auto r = ivl->reg; if (free_until[r] == 0) continue; auto until = nextIntersect(current, ivl); free_until[r] = std::min(until, free_until[r]); } // Try to get a hinted register auto hint = findHint(current, free_until, allow); if (hint != InvalidReg) { return assignReg(current, hint); } auto r = find(free_until); auto pos = free_until[r]; if (pos >= current->end()) { return assignReg(current, r); } if (pos > current->start()) { // r is free for the first part of current auto prev_use = current->lastUseBefore(pos); UNUSED auto min_split = std::max(prev_use, current->start() + 1); auto max_split = pos; assert(min_split <= max_split); auto split_pos = nearestSplitBefore(max_split); if (split_pos > current->start()) { auto second = current->split(split_pos, true); pending.push(second); return assignReg(current, r); } } // must spill current or another victim allocBlocked(current); } // When all registers are in use, find a good interval to split and spill, // which could be the current interval. When an interval is split and the // second part is spilled, possibly split the second part again before the // next use-pos that requires a register, and enqueue the third part. void Vxls::allocBlocked(Interval* current) { PosVec used, blocked; RegSet allow; unsigned conflict = constrain(current, allow); // repeated from allocate allow.forEach([&](PhysReg r) { used[r] = blocked[r] = conflict; }); auto const cur_start = current->start(); // compute next use of active registers, so we can pick the furthest one for (auto ivl : active) { if (ivl->fixed()) { blocked[ivl->reg] = used[ivl->reg] = 0; } else { auto use_pos = ivl->firstUseAfter(cur_start); used[ivl->reg] = std::min(use_pos, used[ivl->reg]); } } // compute next intersection/use of inactive regs to find whats free longest for (auto ivl : inactive) { auto r = ivl->reg; if (blocked[r] == 0) continue; auto intersect_pos = nextIntersect(current, ivl); if (intersect_pos == kMaxPos) continue; if (ivl->fixed()) { blocked[r] = std::min(intersect_pos, blocked[r]); used[r] = std::min(blocked[r], used[r]); } else { auto use_pos = ivl->firstUseAfter(cur_start); used[r] = std::min(use_pos, used[r]); } } // choose the best victim register(s) to spill auto r = find(used); auto used_pos = used[r]; if (used_pos < current->firstUse()) { // all other intervals are used before current's first register-use return spill(current); } auto block_pos = blocked[r]; if (block_pos < current->end()) { auto prev_use = current->lastUseBefore(block_pos); UNUSED auto min_split = std::max(prev_use, cur_start + 1); auto max_split = block_pos; assert(cur_start < min_split && min_split <= max_split); auto split_pos = nearestSplitBefore(max_split); if (split_pos > current->start()) { auto second = current->split(split_pos, true); pending.push(second); } } spillOthers(current, r); assignReg(current, r); } // Assign r to this interval. void Vxls::assignReg(Interval* ivl, PhysReg r) { ivl->reg = r; active.push_back(ivl); } // split ivl at pos and spill the second part. If pos is too close // to ivl->start(), spill all of ivl. void Vxls::spillAfter(Interval* ivl, unsigned pos) { auto split_pos = nearestSplitBefore(pos); auto tail = split_pos <= ivl->start() ? ivl : ivl->split(split_pos); spill(tail); } // Spill ivl from its start until its first register use. If there // is no use, spill the entire interval. Otherwise split the // interval just before the use, and enqueue the second part. void Vxls::spill(Interval* ivl) { unsigned first_use = ivl->firstUse(); if (first_use <= ivl->end()) { auto split_pos = nearestSplitBefore(first_use); if (split_pos <= ivl->start()) { // this only can happen if we need more than the available registers // at a single position. It can happen in phijmp or callargs. TRACE(1, ""vxls-punt RegSpill\\n""); PUNT(RegSpill); // cannot split before first_use } pending.push(ivl->split(split_pos)); } assert(ivl->uses.empty()); ivl->reg = InvalidReg; if (!ivl->cns) assignSpill(ivl); } // Split and spill other intervals that conflict with current for // register r, at current->start(). If necessary, split the victims // again before their first use position that requires a register. void Vxls::spillOthers(Interval* current, PhysReg r) { auto cur_start = current->start(); for (auto i = active.begin(); i != active.end();) { auto other = *i; if (other->fixed() || r != other->reg) { i++; continue; } erase(active, i); spillAfter(other, cur_start); } for (auto i = inactive.begin(); i != inactive.end();) { auto other = *i; if (other->fixed() || r != other->reg) { i++; continue; } auto intersect = nextIntersect(current, other); if (intersect >= current->end()) { i++; continue; } erase(inactive, i); spillAfter(other, cur_start); } } // Assign the next available spill slot to interval void Vxls::assignSpill(Interval* ivl) { assert(!ivl->fixed() && ivl->parent && ivl->uses.empty()); auto leader = ivl->parent; if (leader->slot < 0) { if (!leader->wide) { leader->slot = m_nextSlot++; } else { assert(leader->reg.isSIMD()); if (!isSlotAligned(m_nextSlot)) m_nextSlot++; leader->slot = m_nextSlot; m_nextSlot += 2; } if (m_nextSlot > NumPreAllocatedSpillLocs) { // ran out of spill slots if (dumpIREnabled(kRegAllocLevel)) dumpIntervals(); TRACE(1, ""vxls-punt TooManySpills\\n""); PUNT(LinearScan_TooManySpills); } } ivl->slot = leader->slot; } // Visitor class for renaming registers. Visit every virtual-register // typed operand, and rename it to its assigned physical register. struct Renamer { Renamer(Vxls& xls, unsigned pos) : xls(xls), pos(pos) {} template void imm(const T& r) {} template void def(R& r) { rename(r); } template void defHint(D& dst, H) { rename(dst); } void use(VcallArgsId) { always_assert(false && ""vcall unsupported in vxls""); } template void use(R& r) { rename(r); } template void useHint(S& src, H) { rename(src); } template void across(R& r) { rename(r); } void def(RegSet) {} void use(Vptr& m) { if (m.base.isValid()) rename(m.base); if (m.index.isValid()) rename(m.index); } void use(RegSet r){} private: void rename(Vreg8& r) { r = lookup(r, VregKind::Gpr); } void rename(Vreg16& r) { r = lookup(r, VregKind::Gpr); } void rename(Vreg32& r) { r = lookup(r, VregKind::Gpr); } void rename(Vreg64& r) { r = lookup(r, VregKind::Gpr); } void rename(VregDbl& r) { r = lookup(r, VregKind::Simd); } void rename(Vreg128& r) { r = lookup(r, VregKind::Simd); } void rename(VregSF& r) { r = lookup(r, VregKind::Sf); } void rename(Vreg& r) { r = lookup(r, VregKind::Any); } void rename(Vtuple t) { /* phijmp/phijcc+phidef handled by resolveEdges */ } PhysReg lookup(Vreg vreg, VregKind kind) { auto ivl = xls.intervals[vreg]; if (!ivl || vreg.isPhys()) return vreg; PhysReg reg = ivl->childAt(pos)->reg; assert((kind == VregKind::Gpr && reg.isGP()) || (kind == VregKind::Simd && reg.isSIMD()) || (kind == VregKind::Sf && reg.isSF()) || (kind == VregKind::Any && reg != InvalidReg)); return reg; } private: Vxls& xls; unsigned pos; }; void Vxls::renameOperands() { for (auto b : blocks) { auto pos = block_ranges[b].start; for (auto& inst : unit.blocks[b].code) { Renamer renamer(*this, pos); visitOperands(inst, renamer); pos += 2; } } if (dumpIREnabled(kRegAllocLevel)) { print(""after renaming operands""); } } // Insert spills and copies that connect sub-intervals that were split // between instructions. Do not assume SSA; insert a spill-store // after every def, ignoring the interval's full live range. void Vxls::resolveSplits() { if (dumpIREnabled(kRegAllocLevel)) dumpIntervals(); for (auto i1 : intervals) { if (!i1) continue; auto slot = i1->slot; if (slot >= 0) insertSpill(i1); for (auto i2 = i1->next; i2; i1 = i2, i2 = i2->next) { auto pos = i2->start(); if (i1->end() != pos) continue; // spans lifetime hole if (i2->reg == InvalidReg) continue; // no load necessary if (i2->reg == i1->reg) continue; // no copy necessary auto b = findBlock(pos); auto range = block_ranges[b]; if (pos % 2 == 0) { // even position requiring a copy must be on edge assert(range.start == pos); } else { // odd position assert(pos > range.start); // implicit label position per block if (pos + 1 == range.end) continue; // copy belongs on successor edge if (i2->reg != i1->reg) { copies[pos][i2->reg] = i1; } } } } } // Insert a spill after the def-position in ivl. void Vxls::insertSpill(Interval* ivl) { auto DEBUG_ONLY checkPos = [&](unsigned pos) { assert(pos % 2 == 1); DEBUG_ONLY auto b = findBlock(pos); DEBUG_ONLY auto range = block_ranges[b]; assert(pos - 1 >= range.start && pos + 1 < range.end); return true; }; auto pos = ivl->def_pos + 1; assert(checkPos(pos)); spills[pos][ivl->reg] = ivl; // store ivl->reg => ivl->slot } // Lower copyargs into moveplans at the copyargs position. void Vxls::lowerCopyargs() { for (auto b : blocks) { auto pos = block_ranges[b].start; for (auto& inst : unit.blocks[b].code) { if (inst.op == Vinstr::copyargs) { auto& uses = unit.tuples[inst.copyargs_.s]; auto& defs = unit.tuples[inst.copyargs_.d]; for (unsigned i = 0, n = uses.size(); i < n; ++i) { auto i1 = intervals[uses[i]]; if (i1 && !i1->fixed()) i1 = i1->childAt(pos); auto i2 = intervals[defs[i]]; if (i2->reg != i1->reg) { assert(!copies[pos][i2->reg]); copies[pos][i2->reg] = i1; } } } pos += 2; } } } void Vxls::resolveEdges() { auto addEdgeCopiesForPhiUseDefIntervalConflicts = [&]( Vlabel block, Vlabel target, uint32_t targetIndex, const VregList& uses) { auto p1 = block_ranges[block].end - 2; auto& defs = unit.tuples[findDefs(unit, target)]; for (unsigned i = 0, n = uses.size(); i < n; ++i) { auto i1 = intervals[uses[i]]; if (i1) i1 = i1->childAt(p1); auto i2 = intervals[defs[i]]; if (i2->reg != i1->reg) { assert((edge_copies[{block,targetIndex}][i2->reg] == nullptr)); edge_copies[{block,targetIndex}][i2->reg] = i1; } } }; for (auto b1 : blocks) { auto& block1 = unit.blocks[b1]; auto p1 = block_ranges[b1].end - 2; auto succlist = succs(block1); auto& inst1 = block1.code.back(); if (inst1.op == Vinstr::phijmp) { auto target = inst1.phijmp_.target; auto& uses = unit.tuples[inst1.phijmp_.uses]; addEdgeCopiesForPhiUseDefIntervalConflicts(b1, target, 0, uses); auto tmp_pos = inst1.pos; inst1 = jmp{target}; inst1.pos = tmp_pos; } else if (inst1.op == Vinstr::phijcc) { auto& uses = unit.tuples[inst1.phijcc_.uses]; uint32_t i = 0; for (auto target : succs(inst1)) { addEdgeCopiesForPhiUseDefIntervalConflicts(b1, target, i, uses); i += 1; } auto& targets = inst1.phijcc_.targets; auto tmp_pos = inst1.pos; inst1 = jcc{inst1.phijcc_.cc, inst1.phijcc_.sf, {targets[0], targets[1]}}; inst1.pos = tmp_pos; } for (unsigned i = 0, n = succlist.size(); i < n; i++) { auto b2 = succlist[i]; auto p2 = block_ranges[b2].start; forEach(livein[b2], [&](Vreg vr) { auto ivl = intervals[vr]; if (ivl->fixed()) return; Interval* i1 = nullptr; Interval* i2 = nullptr; for (auto ivl = intervals[vr]; ivl && !(i1 && i2); ivl = ivl->next) { if (ivl->covers(p1)) i1 = ivl; if (ivl->covers(p2)) i2 = ivl; } // i2 can be unallocated if the tmp is a constant or is spilled. if (i2->reg != InvalidReg && i2->reg != i1->reg) { assert((edge_copies[{b1,i}][i2->reg] == nullptr)); edge_copies[{b1,i}][i2->reg] = i1; } }); } } } // last phase: mutate the code by inserting copies. this destroyes // the position numbering, so we can't use interval positions after this. void Vxls::insertCopies() { // insert copies inside blocks for (auto b : blocks) { auto pos = block_ranges[b].start; auto& block = unit.blocks[b]; auto& code = block.code; auto offset = spill_offsets[b]; for (unsigned j = 0; j < code.size(); j++, pos += 2) { MemoryRef slots = m_sp[offset]; offset -= spEffect(code[j]); auto s = spills.find(pos - 1); if (s != spills.end()) { insertSpillsAt(code, j, s->second, slots, pos - 1); } auto c = copies.find(pos - 1); if (c != copies.end()) { insertCopiesAt(code, j, c->second, slots, pos - 1); } c = copies.find(pos); if (c != copies.end()) { insertCopiesAt(code, j, c->second, slots, pos); } } } // insert copies on edges for (auto b : blocks) { auto& block = unit.blocks[b]; auto succlist = succs(block); if (succlist.size() == 1) { // copies will go at end of b auto& code = block.code; auto c = edge_copies.find({b, 0}); if (c != edge_copies.end()) { unsigned j = code.size() - 1; auto slots = m_sp[spill_offsets[succlist[0]]]; insertCopiesAt(code, j, c->second, slots, block_ranges[b].end - 1); } } else { // copies will go at start of successor for (int i = 0, n = succlist.size(); i < n; i++) { auto s = succlist[i]; auto c = edge_copies.find({b, i}); if (c != edge_copies.end()) { auto slots = m_sp[spill_offsets[s]]; auto& code = unit.blocks[s].code; unsigned j = 0; insertCopiesAt(code, j, c->second, slots, block_ranges[s].start); } } } } if (dumpIREnabled(kRegAllocLevel)) { dumpIntervals(); print(""after inserting copies""); } } void Vxls::insertSpillsAt(jit::vector& code, unsigned& j, const CopyPlan& spills, MemoryRef slots, unsigned pos) { jit::vector stores; for (auto src : spills) { auto ivl = spills[src]; if (!ivl) continue; auto slot = ivl->leader()->slot; assert(slot >= 0 && src == ivl->reg); MemoryRef ptr{slots.r + slotOffset(slot)}; if (!ivl->wide) { stores.emplace_back(store{src, ptr}); } else { assert(src.isSIMD()); stores.emplace_back(storedqu{src, ptr}); } } code.insert(code.begin() + j, stores.size(), ud2{}); for (auto& inst : stores) { code[j] = inst; code[j++].pos = pos; } } void Vxls::insertCopiesAt(jit::vector& code, unsigned& j, const CopyPlan& copies, MemoryRef slots, unsigned pos) { MovePlan moves; jit::vector loads; jit::hash_map cpool; for (auto dst : copies) { auto ivl = copies[dst]; if (!ivl) continue; if (ivl->reg != InvalidReg) { moves[dst] = ivl->reg; } else if (ivl->cns) { loads.emplace_back(ldimm{ivl->val, dst, true}); } else { assert(ivl->spilled()); MemoryRef ptr{slots.r + slotOffset(ivl->slot)}; if (!ivl->wide) { loads.emplace_back(load{ptr, dst}); } else { assert(dst.isSIMD()); loads.emplace_back(loaddqu{ptr, dst}); } } } auto origin = code[j].origin; auto hows = doRegMoves(moves, m_tmp); auto count = hows.size() + loads.size(); code.insert(code.begin() + j, count, ud2{}); for (auto& how : hows) { if (how.m_kind == MoveInfo::Kind::Xchg) { code[j] = copy2{how.m_src, how.m_dst, how.m_dst, how.m_src}; } else { code[j] = copy{how.m_src, how.m_dst}; } code[j].origin = origin; code[j++].pos = pos; } for (auto& inst : loads) { code[j] = inst; code[j].origin = origin; code[j++].pos = pos; } } // Return the [start,end) range for the block enclosing pos. Vlabel Vxls::findBlock(unsigned pos) { for (unsigned lo = 0, hi = blocks.size(); lo < hi;) { auto mid = (lo + hi) / 2; auto r = block_ranges[blocks[mid]]; if (pos < r.start) { hi = mid; } else if (pos >= r.end) { lo = mid + 1; } else { return blocks[mid]; } } always_assert(false); return Vlabel{unit.blocks.size()}; } LiveRange Vxls::findBlockRange(unsigned pos) { return block_ranges[findBlock(pos)]; } enum Mode { Light, Heavy }; template const char* draw(Interval* parent, unsigned pos, Mode m, Pred covers) { // Light Heavy static const char* top[] = { ""\\u2575"", ""\\u2579"" }; static const char* bottom[] = { ""\\u2577"", ""\\u257B"" }; static const char* both[] = { ""\\u2502"", ""\\u2503"" }; static const char* empty[] = { "" "", "" "" }; auto f = [&](unsigned pos) { for (auto ivl = parent; ivl; ivl = ivl->next) { if (covers(ivl, pos)) return true; } return false; }; auto s = f(pos); auto d = pos%2 == 1 ? s : f(pos+1); return ( s && !d) ? top[m] : ( s && d) ? both[m] : (!s && d) ? bottom[m] : empty[m]; } std::string Interval::toString() { std::ostringstream out; auto delim = """"; if (reg != InvalidReg) { out << show(reg); delim = "" ""; } if (cns) { out << delim << folly::format(""#{:08x}"", val); } if (slot >= 0) { out << delim << folly::format(""[%sp+{}]"", slotOffset(slot)); } delim = """"; out << "" [""; for (auto& r : ranges) { out << delim << folly::format(""{}-{}"", r.start, r.end); delim = "",""; } out << "") {""; delim = """"; for (auto& u : uses) { if (u.pos == def_pos) { out << delim << ""@"" << u.pos << ""=""; if (u.hint.isValid()) out << show(u.hint); } else { if (u.hint.isValid()) { out << delim << show(u.hint) << ""=@"" << u.pos; } else { out << delim << ""=@"" << u.pos; } } delim = "",""; } out << ""}""; return out.str(); } void Vxls::dumpIntervals() { Trace::traceRelease(""Spills %u\\n"", m_nextSlot); for (auto ivl : intervals) { if (!ivl || ivl->fixed()) continue; HPHP::Trace::traceRelease(""%%%-2lu %s\\n"", size_t(ivl->vreg), ivl->toString().c_str()); for (ivl = ivl->next; ivl; ivl = ivl->next) { HPHP::Trace::traceRelease("" %s\\n"", ivl->toString().c_str()); } } } auto const ignore_reserved = true; auto const collapse_fixed = true; void Vxls::printInstr(std::ostringstream& str, Vinstr* inst, unsigned pos, Vlabel b) { bool fixed_covers[2] = { false, false }; Interval* fixed = nullptr; for (auto ivl : intervals) { if (!ivl) continue; if (ivl->fixed()) { if (ignore_reserved && !m_abi.unreserved().contains(ivl->vreg)) { continue; } if (collapse_fixed) { fixed = ivl; // can be any. fixed_covers[0] |= ivl->covers(pos); fixed_covers[1] |= ivl->covers(pos + 1); continue; } } str << "" ""; str << draw(ivl, pos, Light, [&](Interval* child, unsigned p) { return child->covers(p); }); str << draw(ivl, pos, Heavy, [&](Interval* child, unsigned p) { return child->usedAt(p); }); } str << "" "" << draw(fixed, pos, Heavy, [&](Interval*, unsigned p) { assert(p-pos < 2); return fixed_covers[p-pos]; }); if (pos == block_ranges[b].start) { str << folly::format("" B{: <3}"", size_t(b)); } else { str << "" ""; } str << folly::format("" {: <3} "", pos) << show(unit, *inst) << ""\\n""; } void Vxls::print(const char* caption) { std::ostringstream str; str << ""Intervals "" << caption << "" "" << s_counter << ""\\n""; for (auto ivl : intervals) { if (!ivl) continue; if (ivl->fixed()) { if (ignore_reserved && !m_abi.unreserved().contains(ivl->vreg)) { continue; } if (collapse_fixed) { continue; } } str << folly::format("" {: <2}"", size_t(ivl->vreg)); } str << "" FX\\n""; for (auto b : blocks) { for (auto& inst : unit.blocks[b].code) { printInstr(str, &inst, inst.pos, b); } } HPHP::Trace::traceRelease(""%s\\n"", str.str().c_str()); } } jit::vector sortBlocks(const Vunit& unit) { BlockSorter s(unit); s.dfs(unit.entry); std::reverse(s.blocks.begin(), s.blocks.end()); // put the blocks containing ""end"" last; expect at most one per area. std::stable_partition(s.blocks.begin(), s.blocks.end(), [&] (Vlabel b) { auto& block = unit.blocks[b]; auto& code = block.code; return code.back().op != Vinstr::end; }); return s.blocks; } void allocateRegisters(Vunit& unit, const Abi& abi) { s_counter++; Vxls a(unit, abi); a.allocate(); } folly::Range succs(Vinstr& inst) { switch (inst.op) { case Vinstr::jcc: return {inst.jcc_.targets, 2}; case Vinstr::jmp: return {&inst.jmp_.target, 1}; case Vinstr::phijmp: return {&inst.phijmp_.target, 1}; case Vinstr::phijcc: return {inst.phijcc_.targets, 2}; case Vinstr::unwind: return {inst.unwind_.targets, 2}; case Vinstr::vinvoke: return {inst.vinvoke_.targets, 2}; case Vinstr::cbcc: return {inst.cbcc_.targets, 2}; case Vinstr::tbcc: return {inst.tbcc_.targets, 2}; case Vinstr::hcunwind: return {inst.hcunwind_.targets, 2}; default: return {nullptr, nullptr}; } } folly::Range succs(const Vinstr& inst) { return succs(const_cast(inst)).castToConst(); } folly::Range succs(Vblock& block) { if (block.code.empty()) return {nullptr, nullptr}; return succs(block.code.back()); } folly::Range succs(const Vblock& block) { return succs(const_cast(block)).castToConst(); } }} ",16196,True,3120.804556969494,median "#ifdef __arm__ // should use uinstd.h to define sbrk but Due causes a conflict extern ""C"" char* sbrk(int incr); #else // __ARM__ extern char *__brkval; #endif // __arm__ #ifdef MNSLAC_NODE_M0 float getBattVoltage() { return analogRead(BATT) * BATT_MEAS_COEFF; } uint16_t getBattVoltageBits() { return analogRead(BATT); } #else float getBattVoltage() { return 0.0f; } #endif int freeMemory() { char top; #ifdef __arm__ return &top - reinterpret_cast(sbrk(0)); #elif defined(CORE_TEENSY) || (ARDUINO > 103 && ARDUINO != 151) return &top - __brkval; #else // __arm__ return __brkval ? &top - __brkval : &top - __malloc_heap_start; #endif // __arm__ } // Print a message struct to the console void printMessage(Message msg) { inc(); pcln(""Message Contents""); sprintf(medium_buf, ""| → %-8s%d"", ""Valid: "", msg.valid); pcln(medium_buf); sprintf(medium_buf, ""| → %-8s%d"", ""From: "", msg.from); pcln(medium_buf); sprintf(medium_buf, ""| → %-8s%d"", ""Seq: "", msg.seq); pcln(medium_buf); sprintf(medium_buf, ""| → %-8s%s"", ""Type: "", MsgTypes[msg.type]); pcln(medium_buf); sprintf(medium_buf, ""| → %-8s0x%.*X"", ""Data: "", msg.len, msg.data); pcln(medium_buf); dec(); } void receiver() { DW1000.newReceive(); DW1000.setDefaults(); // so we don't need to restart the receiver manually DW1000.receivePermanently(true); DW1000.startReceive(); } // Get a message from the DW1000 and return its message format Message getMessage() { // Create a data buffer byte data[MAC_LEN + DATA_LEN]; // Populate the main data buffer DW1000.getData(data, MAC_LEN + DATA_LEN); // Get the length of this message uint8_t dataLength = DW1000.getDataLength(); return getMessage(data, dataLength); } // Get a message struct from the given byte array with the given length Message getMessage(byte data[], uint8_t dataLength) { // Create Message Struct Message msg; // Check if the message is the correct min length. Also confirm that the // Check Byte (Byte 0) is 0x9B (unique to our project) if (dataLength >= 3 && data[0] == 0x9B) { // Get our From bits msg.from = data[1] >> 4; // Get our Type bits msg.type = (Msg_Type) (data[2] & 0x0F); // Get our Seq bits msg.seq = (data[1] << 4) | (data[2] >> 4); // Create a pointer for data (for easy manipulation) byte *ptr = (byte *)data; // Copy the payload portion of data into msg.data. Notice that this starts // at data[MAC_LEN] and steps for dataLength-MAC_LEN bytes. This can be // zero bytes if no payload is recieved memcpy(msg.data, ptr + MAC_LEN, dataLength - MAC_LEN); // Store the length of the payload in msg msg.len = dataLength - MAC_LEN; // Set this message to valid msg.valid = 1; } return msg; } enum Serial_Command { SERIAL_CMD_NULL = 255, SERIAL_CMD_BLANK = 0, SERIAL_CMD_RESET = 1, SERIAL_CMD_RESET_BASE = 2, SERIAL_CMD_SLEEP = 3, }; uint8_t serial_cmd = SERIAL_CMD_NULL; uint32_t serial_data = 0; uint8_t serial_data_count = 0; // Handle command serial. only for the base station void handleSerial() { if (!isBase) return; // Input Serial Command Structure // ?R\\n -- Reset command // ?S#####\\n -- Sleep command (##### = time in seconds) // ?*\\n -- Reset the base station only // SUPER basic serial interface lol if (Serial && Serial.available()) { while(Serial.available()) { int c = Serial.read(); if (c == '?') { // Start of a command. Move on to the next charactor serial_cmd = SERIAL_CMD_BLANK; serial_data_count = 0; serial_data = 0; continue; } else if (c == '\\n' || c == '\\r') { switch(serial_cmd) { case SERIAL_CMD_RESET: pcln(""Queueing Reset""); queueReset(); break; case SERIAL_CMD_RESET_BASE: reset(); break; case SERIAL_CMD_SLEEP: if (serial_data_count == 5) { sprintf(medium_buf, ""Queueing %d second sleep"", serial_data); pcln(medium_buf); queueSleep(serial_data); } break; default: break; } serial_cmd = SERIAL_CMD_NULL; continue; } switch (serial_cmd) { case SERIAL_CMD_BLANK: if (c == 'S') { serial_cmd = SERIAL_CMD_SLEEP; } else if (c == 'R') { serial_cmd = SERIAL_CMD_RESET; } else if (c == '*') { serial_cmd = SERIAL_CMD_RESET_BASE; } else { serial_cmd = SERIAL_CMD_NULL; } break; case SERIAL_CMD_RESET: case SERIAL_CMD_RESET_BASE: serial_cmd = SERIAL_CMD_NULL; break; case SERIAL_CMD_SLEEP: if (serial_data_count > 4) { break; } serial_data += (c - 48) * intPow(10, 4 - serial_data_count); serial_data_count ++; break; default: serial_cmd = SERIAL_CMD_NULL; break; } } } // Print out our incomming messages various_msg packet; uint8_t packet_id; while (getPacketFromBuffer(&packet, &packet_id)) { if (!Serial) continue; // continue; switch(packet_id) { case RANGE_PACKET: { range_msg * msg = (range_msg *) &packet; Serial.print(""Range Packet | Cycle:""); Serial.print(cycle_counter); Serial.print("",\\tFrom:""); Serial.print(msg -> from); Serial.print("",\\tTo:""); Serial.print(msg -> to); Serial.print("",\\tSeq:""); Serial.print(msg -> seq); Serial.print("",\\tHops:""); Serial.print(msg -> hops); Serial.print("",\\tRange:""); Serial.println(msg -> range); } break; case STATUS_PACKET: { stats_msg * msg = (stats_msg *) &packet; Serial.print(""Stats Packet | Cycle:""); Serial.print(cycle_counter); Serial.print("",\\tFrom:""); Serial.print(msg->from); Serial.print("",\\t\\tSeq:""); Serial.print(msg->seq); Serial.print("",\\tHops:""); Serial.print(msg->hops); Serial.print("",\\tBat:""); Serial.print(msg->bat * BATT_MEAS_COEFF); Serial.print("",\\tTemp:""); Serial.print(DW1000.convertTemp(msg->temp)); Serial.print("",\\tHeading:""); Serial.println(msg->heading); } break; default: // Serial5.print(""Unknown Packet Type: ""); Serial5.println(packet_id); break; } } } // 3 ^ 5; // // 3 // int intPow(int x, int p) { int ret = 1; for (int i = 0; i < p; i++) { ret *= x; } return ret; } // Returns true if we can send this sequence number (and thus // we should store it until our next bcast) boolean processSequenceNumber(uint8_t from, uint8_t seq) { if (from > LEN_NODES_LIST) { pcln(""Invalid From Address Detected"", C_RED); return false; } if (seq > 31) { pcln(""Invalid Sequance Detected"", C_RED); return false; } boolean ret = (packet_sendable[from] >> seq) & 0x1; if (ret) { // If this sequence is sendable, then we should assume it will // be sent. Mark this sequence as unsendable to prevent us from // receiving any additional copies // packet_sendable[from] = packet_sendable[from] | (0x1 << seq); packet_sendable[from] = packet_sendable[from] & ~(0x1 << seq); // Set to false // number &= ~(1UL << n); // Clear (set to true) the opposite half of the packet sendable list to allow // new packets from this node to come in under different // sequence numbers // 0b0000000////////////////000000001 idx 0 // 0b00000000000000000000000000000001 // 0b00000001111111111111111000000000 // 0b////////////////0000000010000000 idx 7 // 0b00000000000000000000000010000000 // 0b11111111111111110000000000000000 if (seq <= 7) { packet_sendable[from] = packet_sendable[from] | (0xFFFF0000 >> (7 - seq)); } // 0b///////////////0000000010000000/ idx 8 // 0b00000000000000000000000100000000 // 0b11111111111111100000000000000001 // 0b/0000000010000000/////////////// idx 22 // 0b00000000010000000000000000000000 // 0b10000000000000000111111111111111 else if (seq <= 22) { packet_sendable[from] = packet_sendable[from] | (0x00007FFF >> (22 - seq)); packet_sendable[from] = packet_sendable[from] | (0xFFFE0000 << (seq - 8)); } // 0b0000000010000000//////////////// idx 23 // 0b00000000100000000000000000000000 // 0b00000000000000001111111111111111 // 0b10000000////////////////00000000 idx 31 // 0b10000000000000000000000000000000 // 0b00000000111111111111111100000000 else { packet_sendable[from] = packet_sendable[from] | (0x0000FFFF << (seq - 23)); } } return ret; } void processMessage(Message msg){ if (msg.valid && msg.len == sizeof(com_stack)) { com_stack *msg_com_stack = (com_stack *)msg.data; pcln(""Decoded COM Stack"", C_ORANGE); sprintf(medium_buf, ""| → node_id: %u"", msg_com_stack -> node_id); pcln(medium_buf); sprintf(medium_buf, ""| → number_msgs: %u"", msg_com_stack -> number_msgs); pcln(medium_buf); for (uint8_t i = 0; i < msg_com_stack->number_msgs; i++){ if (msg_com_stack->msg_id[i] == RANGE_PACKET){ // Range Message range_msg * rm = (range_msg *)&msg_com_stack->msg[i]; if ((rm->hops > 0 || isBase) && rm->from != nodeNumber && processSequenceNumber(rm->from, rm->seq)) { rm->hops --; if (!putPacketInBuffer((various_msg *)rm, RANGE_PACKET)) { pcln(""Packet Buffer Full. Overwrote Message"", C_RED); } sprintf(medium_buf, ""Processed Range Packet: %u"", packet_sendable[rm->from]); pcln(medium_buf); sprintf(medium_buf, ""| → From: %u"", rm -> from); pcln(medium_buf); sprintf(medium_buf, ""| → To: %u"", rm -> to); pcln(medium_buf); sprintf(medium_buf, ""| → Seq: %u"", rm -> seq); pcln(medium_buf); sprintf(medium_buf, ""| → Hops: %u"", rm -> hops); pcln(medium_buf); sprintf(medium_buf, ""| → Range: %u"", rm -> range); pcln(medium_buf); } else if (isBase){ Serial.print(""Discarded Range Packet due to Seq (Host: ""); Serial.print(msg.from); Serial.print("", Seq: ""); Serial.print(rm->seq); Serial.print("", From: ""); Serial.print(rm->from); Serial.print("", To: ""); Serial.print(rm->to); Serial.print("", Hops: ""); Serial.print(rm->hops); Serial.print("", Sendable: ""); Serial.print(packet_sendable[rm->from]); Serial.println("")""); } else { pcln(""Range Packet Failed Seq or Hops"", C_ORANGE); sprintf(medium_buf, ""| → From: %u"", rm -> from); pcln(medium_buf); sprintf(medium_buf, ""| → To: %u"", rm -> to); pcln(medium_buf); sprintf(medium_buf, ""| → Seq: %u"", rm -> seq); pcln(medium_buf); sprintf(medium_buf, ""| → Hops: %u"", rm -> hops); pcln(medium_buf); sprintf(medium_buf, ""| → Range: %u"", rm -> range); pcln(medium_buf); } // memcpy(&range_array[range_array_pointer], rm, sizeof(range_msg)); // packet_life } else if (msg_com_stack->msg_id[i] == STATUS_PACKET){ stats_msg * sm = (stats_msg *)&msg_com_stack->msg[i]; if ((sm->hops > 0 || isBase) && sm->from != nodeNumber && processSequenceNumber(sm->from, sm->seq)) { sm->hops --; if (!putPacketInBuffer((various_msg *)sm, STATUS_PACKET)) { pcln(""Packet Buffer Full. Overwrote Message"", C_RED); } sprintf(medium_buf, ""Processed Stats Packet: %u"", packet_sendable[sm->from]); pcln(medium_buf); // sprintf(medium_buf, ""| → From: %u"", sm -> from); pcln(medium_buf); // sprintf(medium_buf, ""| → Seq: %u"", sm -> seq); pcln(medium_buf); // sprintf(medium_buf, ""| → Hops: %u"", sm -> hops); pcln(medium_buf); // sprintf(medium_buf, ""| → Bat: %u"", sm -> bat); pcln(medium_buf); // sprintf(medium_buf, ""| → Heading: %u"", sm -> heading); pcln(medium_buf); // sprintf(medium_buf, ""| → Temp: %u"", sm -> temp); pcln(medium_buf); } else if (isBase){ Serial.print(""Discarded Stats Packet due to Seq (Host: ""); Serial.print(msg.from); Serial.println("")""); // Serial5.print("", Seq: ""); Serial5.print(sm->seq); // Serial5.print("", From: ""); Serial5.print(sm->from); // Serial5.print("", Hops: ""); Serial5.print(sm->hops); // Serial5.print("", Bat: ""); Serial5.print(sm->bat); // Serial5.print("", Heading: ""); Serial5.print(sm->heading); // Serial5.print("", Temp: ""); Serial5.print(sm->temp); // Serial5.print("", Sendable: ""); Serial5.print(packet_sendable[sm->from]); // Serial5.println("")""); } else { sprintf(medium_buf, ""Stats Packet Failed Seq or Hops: %u"", packet_sendable[sm->from]); pcln(medium_buf); } } else if (msg_com_stack->msg_id[i] == CMD_PACKET) { // The base station does not relay or process command packets. Continue to // the next packet if (isBase) continue; // Cast our data to a command packet type cmd_msg * cm = (cmd_msg *)&msg_com_stack->msg[i]; // Ensure that the packet is good (note that they are always from // the base station [node 0]) if (processSequenceNumber(0, cm->seq)) { pcln(""Command Packet Received"", C_ORANGE); sprintf(medium_buf, ""| → Seq: %u"", cm -> seq); pcln(medium_buf); sprintf(medium_buf, ""| → Hops: %u"", cm -> hops); pcln(medium_buf); sprintf(medium_buf, ""| → Cmd_ID: %u"", cm -> cmd_id); pcln(medium_buf); // Handle this command switch (cm->cmd_id) { case COM_TRANSMIT_AUTH: { sprintf(medium_buf, ""| → Transmit Authorization Accepted""); pcln(medium_buf, C_GREEN); // If our transmit authorization was zero, then we should clear the // packet buffer before moving on (so that we don't send really old // messages) if (transmitAuthorization == 0) { // Clear the packet buffer clearPacketBuffer(); } if (cm->data != 0) { uint32_t dateData = cm->data; uint8_t s = (uint8_t) (cm->data); uint8_t m = (uint8_t) (cm->data >> 8); uint8_t h = (uint8_t) (cm->data >> 16); updateTime(h,m,s); min = m; sec = s; hour = h; sprintf(medium_buf, ""| → Got Time: %02d:%02d:%02d"", h, m, s); pcln(medium_buf, C_GREEN); } // Up our transmit authorization and cycle valid status transmitAuthorization = TRANSMIT_AUTH_CAP; cycleValid = CYCLE_VALID_CAP; } break; case SOFT_RESET: sprintf(medium_buf, ""| → Soft Reset"", cm -> cmd_id); pcln(medium_buf, D_BLINK_C_CYAN); resetCounter = RESET_CYCLE_DELAY; break; case SLEEP: if (sleepCounter == -1) { uint16_t seconds = (uint16_t) cm->data; uint8_t min = seconds / 60; sleepTime = (uint16_t) cm->data; sleepCounter = SLEEP_CYCLE_DELAY; sprintf(medium_buf, ""| → Got Sleep Command (%d seconds from now)"", sleepTime); pcln(medium_buf, D_BLINK_C_CYAN); } break; default: sprintf(medium_buf, ""Unknown Command Id: %u"", cm->cmd_id); pcln(medium_buf, C_RED); break; } // Only add this command to our buffer if it has at least one hop left if (cm->hops > 0) { // Age the packet by one hop cm->hops --; if (!putPacketInBuffer((various_msg *)cm, CMD_PACKET)) { pcln(""Packet Buffer Full. Overwrote Message"", C_RED); } } } }else{ sprintf(medium_buf, ""Unknown Packet Type: %u"", msg_com_stack->msg_id[i]); pcln(medium_buf, C_RED); } } } } void queueTransmitAuth(boolean sendTime) { // Build our cycle's transmit authorization message uint32_t timeData = 0; if (sendTime) { timeData = timeData | sec; timeData = timeData | (((uint32_t) min) << 8); timeData = timeData | (((uint32_t) hour) << 16); } if (cmd_buffer_len >= MAX_CMD_MESSAGES) { cmd_buffer_len = 0; pcln(""Cleared Command Buffer (Xmit Auth)"", C_RED); } cmd_msg cm = {.seq = getMsgSeq(), .cmd_id = COM_TRANSMIT_AUTH, .hops = ALLOWABLE_HOPS, .data = timeData}; memcpy(&cmd_buffer[0], (various_msg *)&cm, sizeof(various_msg)); cmd_buffer_len ++; } void queueReset() { if (cmd_buffer_len >= MAX_CMD_MESSAGES) { cmd_buffer_len = 0; pcln(""Cleared Command Buffer (Reset)"", C_RED); } cmd_msg rstcmd = {.seq = getMsgSeq(), .cmd_id = SOFT_RESET, .hops = ALLOWABLE_HOPS, .data = 0}; memcpy(&cmd_buffer[cmd_buffer_len], (various_msg *)&rstcmd, sizeof(various_msg)); cmd_buffer_len ++; resetCounter = RESET_CYCLE_DELAY; } void queueSleep(uint16_t delay) { if (cmd_buffer_len >= MAX_CMD_MESSAGES) { cmd_buffer_len = 0; pcln(""Cleared Command Buffer (Sleep)"", C_RED); } cmd_msg rstcmd = {.seq = getMsgSeq(), .cmd_id = SLEEP, .hops = ALLOWABLE_HOPS, .data = delay}; memcpy(&cmd_buffer[cmd_buffer_len], (various_msg *)&rstcmd, sizeof(various_msg)); cmd_buffer_len ++; } void checkSleep() { if (sleepCounter > 0) { sprintf(medium_buf, ""Sleeping in %d cycle(s) (%d seconds)"", sleepCounter, sleepTime); pcln(medium_buf, C_ORANGE); sleepCounter --; } else if (sleepCounter == 0) { // Constrain the sleepTime if (sleepTime > MAX_SLEEP_TIME) { sleepTime = MAX_SLEEP_TIME; } else if (sleepTime < MIN_SLEEP_TIME) { sleepTime = MIN_SLEEP_TIME; } // Grab the current epoch time uint32_t epoch = rtc.getEpoch(); // Add our sleep time epoch += sleepTime; sprintf(medium_buf, ""Sleeping for %d seconds (%d)"", sleepTime, epoch); pcln(medium_buf, C_ORANGE); // shut down the main watchdog timer disableWatchdog(); // Set the alarm to the epoch time rtc.setAlarmEpoch(epoch); // Enable the alarm matched to hour, min, second rtc.enableAlarm(rtc.MATCH_HHMMSS); // Go into standby mode standby(); // Reset the system reset(); // // Start the main watchdog timer back up; // enableWatchdog(); // // // Update the RTC time after the sleep // updateRTC(); // // // Update flags // transmitAuthorization = 0; // cycleValid = 0; // cycle_counter = 0; // // sprintf(medium_buf, ""Sleep Compleate (%02d:%02d:%02d)"", hour, min, sec); pcln(medium_buf, C_ORANGE); // // // Reset our cleep counter to disable sleep next time // sleepCounter = -1; } } // Disable the main protection watchdog timer void disableWatchdog() { rtc.disableAlarm(); rtc.detachInterrupt(); } // Enable the main protection watchdog timer void enableWatchdog() { __watchdog_comp = false; __watchdog_last = false; // Attach the watchdogCallback function rtc.attachInterrupt(watchdogCallback); // Grab the current epoch time uint32_t epoch = rtc.getEpoch(); // Add our sleep time epoch += WATCHDOG_INTERVAL; // Set the alarm to the epoch time rtc.setAlarmEpoch(epoch); // Enable the alarm matched to hour, min, second rtc.enableAlarm(rtc.MATCH_SS); } void updateTime(uint8_t h, uint8_t m, uint8_t s) { set_hour = h; set_min = m; set_sec = s; clockUpdateReceived = true; } // Main protection watchdog callback function void watchdogCallback() { // If the watchdog value has not changed, then it is time to reset if (false && (freeMemory() < LOW_MEM_CUTOFF || __watchdog_last ==__watchdog_comp)) { reset(); } else { // Record what the watchdog value was this time to check against next time __watchdog_last = __watchdog_comp; // Update the time if needed if (clockUpdateReceived) { clockUpdateReceived = false; // Turn off the watchdog timer rtc.disableAlarm(); // Set the new time rtc.setSeconds(set_sec); rtc.setMinutes(set_min); rtc.setHours(set_hour); } // Set the alarm to the epoch time plus the watchdog interval rtc.setAlarmEpoch(rtc.getEpoch() + WATCHDOG_INTERVAL); // Enable the alarm matched to hour, min, second rtc.enableAlarm(rtc.MATCH_SS); } } // Hold the watchdog off for another alarm rotation void holdWatchdog() { // Only change the watchdog value if it hasnt changed since the last time // the watchdog was fired if (__watchdog_comp == __watchdog_last) __watchdog_comp = !__watchdog_last; } void standby() { // Stop all of the timers stopTimers(); // Put the DW1000 to sleep DW1000.deepSleep(); // Turn all of the LEDs off setLed(LED_AUX, MODE_OFF); setLed(LED_RED, MODE_OFF); setLed(LED_GREEN, MODE_OFF); setLed(LED_BLUE, MODE_OFF); // Wait for the DW1000 to fully enter sleep mode delay(10); // Enter standby mode rtc.standbyMode(); // Start the DW1000 back up DW1000.spiWakeup(); // Wait for the DW1000 to boot up delay(10); // TODO Reset here? } void checkReset() { // If our reset flag is high, then force the system to reset if (resetCounter > 0) { sprintf(medium_buf, ""Resetting in %d cycle(s)"", sleepCounter); pcln(medium_buf, C_ORANGE); resetCounter --; } else if (resetCounter == 0) { resetCounter = -1; reset(); } } void reset() { stopTimers(); disableWatchdog(); // setup(); NVIC_SystemReset(); } // typedef struct cmd_msg // { // 5 Bytes // uint8_t seq : 5; // Unique message number // uint8_t cmd_id : 5; // Command ID // uint8_t hops : 3; // Total allowed remaining hops for this message // uint32_t data : 27; // Command data // } cmd_msg; void loadPackets(Message * msg) { uint8_t num_messages = 0; uint8_t ids[MSGS_PER_COM_STACK]; various_msg v_packets[MSGS_PER_COM_STACK]; if (isBase) { if (cmd_buffer_len == 0) { msg->len = 0; return; } msg->len = (uint8_t)sizeof(com_stack); for (uint8_t i = 0; i < MSGS_PER_COM_STACK; i++){ if (cmd_buffer_len == 0) { break; } else { cmd_buffer_len --; memcpy(&v_packets[i], &cmd_buffer[cmd_buffer_len], sizeof(various_msg)); ids[i] = CMD_PACKET; num_messages ++; } } } else { if (getBufferLength() == 0) { msg->len = 0; return; } msg->len = (uint8_t)sizeof(com_stack); for (uint8_t i = 0; i < MSGS_PER_COM_STACK; i++){ uint8_t id; if (getPacketFromBuffer(&v_packets[i], &ids[i])) { num_messages ++; } else { break; } // ids[i] = RANGE_PACKET; // memcpy(&v_packets[i], &range_array[range_array_pointer], sizeof(various_msg)); } } com_stack msg_com_stack = {.node_id = nodeNumber, .number_msgs = num_messages}; memcpy(&msg_com_stack.msg_id, &ids, MSGS_PER_COM_STACK); memcpy(&msg_com_stack.msg, &v_packets, sizeof(various_msg)*MSGS_PER_COM_STACK); memcpy(&msg->data, &msg_com_stack, sizeof(com_stack)); sprintf(medium_buf, ""Loaded %u packets into message"", num_messages); pcln(medium_buf, C_BLUE); } // uint8_t range_array_pointer = 0; // range_msg range_array[MAX_RANGE_MESSAGES]; // Get the length of a message object int getMessageLength(Message msg) { return MAC_LEN + msg.len; } // Create a message from the given message struct and place the result into // the given byte buffer void createMessage(byte data[], Message msg) { // Set the Check Byte data[0] = 0x9B; // Set byte 1 data[1] = (msg.from << 4) | (msg.seq >> 4); // Set byte 2 data[2] = (msg.seq << 4) | msg.type; // Create a pointer for data byte *ptr = (byte *)data; // Copy the data from msg.data to the byte array starting at its third // byte memcpy(ptr + 3, msg.data, msg.len); } void getRangeRecDelay(DW1000Time& t, uint8_t nodeNum, Settings s) { if (nodeNum == 0) { t.setTime((int32_t) 0); } else { t.setTime((int32_t) (s.t_rx + s.t_r * nodeNum)); } } uint32_t getRangeRecDelay(uint8_t nodeNum, Settings s) { if (nodeNum == 0) { return 0; } else { return (int32_t) (s.t_rx + s.t_r * nodeNum); } } // uint8_t buffer_start = 0; // uint8_t buffer_num = 0; // various_msg packet_buffer[MAX_RANGE_MESSAGES]; // uint8_t packet_buffer_IDs[MAX_RANGE_MESSAGES]; uint8_t getBufferLength() { return buffer_num; } void clearPacketBuffer() { buffer_num = 0; buffer_start = 0; } boolean getPacketFromBuffer(various_msg * packet, uint8_t * id) { if (buffer_num == 0) return false; // packet = &packet_buffer[buffer_start]; memcpy(packet, &packet_buffer[buffer_start], sizeof(various_msg)); *id = packet_buffer_IDs[buffer_start]; buffer_start++; if (buffer_start >= MAX_RANGE_MESSAGES) buffer_start = 0; buffer_num--; return true; } boolean putPacketInBuffer(various_msg * packet, uint8_t id) { boolean ret = true; if (buffer_num == MAX_RANGE_MESSAGES) { ret = false; buffer_start ++; buffer_num --; } uint8_t idx = buffer_start + buffer_num; if (idx >= MAX_RANGE_MESSAGES) { idx -= MAX_RANGE_MESSAGES; } memcpy(&packet_buffer[idx], packet, sizeof(various_msg)); packet_buffer_IDs[idx] = id; buffer_num ++; return ret; } void printSettings(Settings s) { section(""System Settings"", C_ORANGE); sprintf(medium_buf, ""%-8s%d"", ""n:"", s.n); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_rx:"", s.t_rx); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_s:"", s.t_s); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_fs:"", s.t_fs); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_c:"", s.t_c); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""n_com:"", s.n_com); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_b:"", s.t_b); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_r:"", s.t_r); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_cl:"", s.t_cl); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_br:"", s.t_br); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_fr:"", s.t_fr); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_bc:"", s.t_bc); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_fc:"", s.t_fc); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""t_rn:"", s.t_rn); pcln(medium_buf, C_RED); sprintf(medium_buf, ""%-8s%d"", ""bits_c:"", s.bits_c); pcln(medium_buf, C_RED); endSection(); pcln(""""); } float runningTotal; float computeRange(DW1000Time& rec, uint8_t fromId) { // The total time between our poll message being sent and the reply being // received. DW1000Time total = (rec - timePollSent).wrap(); // The time that the distant node was suppsed to wait to reply based on their // Node Id DW1000Time turn = DW1000Time(settings.t_r + (settings.t_r * fromId), DW1000Time::MICROSECONDS); DW1000Time tof = (total - turn) / 2; float distance = tof.getAsMeters(); // Serial.print(""Distance Data: Total(""); Serial.print(total.getAsNanoSeconds()); // Serial.print(""NodeID: ""); Serial.print(fromId); // Serial.print(""\\tTurn(""); Serial.print(turn.getAsNanoSeconds()); // Serial.print(""), TOF(""); Serial.print(tof.getAsNanoSeconds()); // Serial.print(""); Sent:""); Serial.print(timePollSent.getAsMicroSeconds()); // Serial.print("", Received:""); Serial.print(rec.getAsMicroSeconds()); // Serial.print("", Dist:""); Serial.println(distance); return distance; } // TODO Finish adjust clock boolean adjustClock(Message msg, uint32_t m0rx, float dwrx, boolean confirmCycle = true) { // Figure out what frame we are in Frame curFrame = getFrameFromSeq(msg.seq, settings); // Figure out if this is the start of this block boolean blockStart = isBlockStart(curFrame, msg.seq, settings); // If this message is the start of a block, // the we adjust our clocks if (blockStart) { // Reset our DWOffset based on the message we got. Usage of this offset value // us explained at its def. DWOffset = m0rx - dwrx; // From the message, get the exact micros at which that message should have // been received uint32_t curCycleTime = getTimeAtSeq(msg.seq); // At the exact moment that the message was recieved, the cycle was at cycle // time curCycleTime. Therefore the start of the cycle occured curCycleTime // micros before the message was received in M0 time. cycleStart = m0rx - curCycleTime; // Because we have just confirmed our cycle, set cycleValid to true if (confirmCycle) cycleValid = CYCLE_VALID_CAP; // Return true to denote a clock adjustment return true; } // Return false to denote no clock adjustment return false; } uint32_t getTimeAtSeq(uint8_t seq) { Settings s = settings; // Start with the sleep frame time (which is always at the start of the cycle) uint32_t ret = s.t_fs; // Find the very first sequence number of the COM frame uint8_t comFirstSeq = s.n * (s.n + 1); // See if we are before the first com seq number uint8_t isRangeFrame = seq < comFirstSeq; if (isRangeFrame) { // Find what block we are in within this frame. This relies on interger // truncation as a ""floor"" operation. uint8_t blockNum = seq / (s.n + 1); // Find what seq we are within this block. uint8_t seqIdx = (seq % (s.n + 1)); // For each block that we are already past, we add one block length. // Remember that the block number starts from zero. This means that if we // are in the 0th block, we should add no additional time. If we are the // 1st block, then we need only add the time of the 0th block. ret += (s.t_br * blockNum); // Now within our block, we add the time to get to the given sequence id. // Just as with the block numbers, the sequence index starts at zero. If // the 0th message comes through, then we only add in the rx time. If the // 1st message comes through, we add the rx time plus one range division // (t_r) ret += (s.t_r * seqIdx) + s.t_rx; } // If we are not in the range frame, then we are in the com frame else { // Because we are past the ENTIRE range frame, we can simply add the time // to compleate the whole thing now ret += s.t_fr; // Using the value we calculated earlier for the first seq number of the // com frame, we can see how many sequances we are into this frame. As with // the Range block number, this block number starts from 0 uint8_t blockNum = seq - comFirstSeq; // Add the time for all the blocks in the COM frame before this one. // Because the block number starts at 0, we need only do a simple // multiplication to achieve this. Finally we add a single t_rx to account // for the fact that each com message is t_rx deep into its block ret += (s.t_bc * blockNum) + s.t_rx; } return ret; } // Get the block that the given Node Id should be in, given that the current // message has the given sequence number. Block getBlockFromSeq(uint8_t seq, uint8_t nodeId, Settings s) { // Figure out what frame we are in Frame curFrame = getFrameFromSeq(seq, s); // If we are in the range frame, then use the following calculation if (curFrame == FRAME_RANGE) { // Figure out which block within the range frame we are in uint8_t blockNum = seq / (s.n + 1); // If our nodeid matches the block number, then it is our turn to be the // requester. Otherwise, we should be an accepter. if (nodeId == blockNum) { return BLOCK_RANGE_REQUEST; } else { return BLOCK_RANGE_ACCEPT; } } // if we are in the com frame, then we are always in a com block else if (curFrame == FRAME_COMS) { return BLOCK_COM; } // if we are in the com frame, then we are always in a com block else if (curFrame == FRAME_SLEEP) { return BLOCK_SLEEP; } // If not any others, then assume we are in the sleep block else { return BLOCK_NONE; } } // Gets a message's index within a single block uint8_t getMsgIdx(Frame frame, uint8_t seq, Settings s) { // When we are in the range frame, the following formula will result in the // message index if (frame == FRAME_RANGE) { return (seq % (s.n + 1)); } else { return 0; } } // Return whether or not the given message sequance number is the start of its // block boolean isBlockStart(Frame frame, uint8_t seq, Settings s) { return getMsgIdx(frame, seq, s) == 0; } // Return whether or not the given message sequance number is the end of its // block boolean isBlockEnd(Frame frame, uint8_t seq, Settings s) { if (frame == FRAME_RANGE) { return getMsgIdx(frame, seq, s) == s.n; } else { return true; } } // LEFT OFF: // Setting up get state to work. This will go in the decode states in order to // help figure out whether or not we need to move to a different state based on // the message we got. Also might help with moving us between blocks and frames // Gets state we should move to based on the given sequence number and message // type. This function will return the state to move to next. // To be execute if we do not receive the expected message state_fn * getState(Message msg) { Settings s = settings; state_fn * nextState; // See what we should be doing next sequence Frame curFrame = getFrameFromSeq(msg.seq + 1, s); Block curBlock = getBlockFromSeq(msg.seq + 1, nodeNumber, s); // If this message index is 0, then it is the first in this block boolean blockStart = isBlockStart(curFrame, msg.seq + 1, s); // If this messsage index is the number of nodes in the network, then it is // the last message in this block boolean blockEnd = isBlockEnd(curFrame, msg.seq + 1, s); if (curFrame == FRAME_RANGE) { // Check if we should be in the range accept block if (curBlock == BLOCK_RANGE_ACCEPT) { switch (msg.type) { // If we just got a range request, jump right to the ra_resp state case RANGE_REQ: nextState = { ra_resp }; break; // For all other message types (should only be RANGE_RESP), simply // enter the ra_init state default: nextState = { ra_init }; break; } } // If we are suposed to be in the range request block, the move to rb_range else if (curBlock == BLOCK_RANGE_REQUEST) { nextState = { rb_range }; } else { nextState = { ra_init }; } } else if (curFrame == FRAME_COMS) { nextState = { sleep }; } else { nextState = { sleep }; } return nextState; } // Get the frame the given sequence number falls in, given the current settings Frame getFrameFromSeq(uint8_t seq, Settings s) { // There are n * (n+1) messages required for a full ranging frame. Given that // the sequence numbers start from 0, we can get away with using a < operator // for this alone (Eg for n=5, the sequences in the Range frame would number // from 0 to 29 (accounting for one ""blank"" seq for the Request node). If our // current sequence is 29, that is less than 5*6. If our seq is 30, that is // equal to 5*6 and would therefore fail this if statement) if (seq < (s.n * (s.n + 1))) return FRAME_RANGE; else if (seq < (s.n * (s.n + 1) + s.n * s.n_com)) return FRAME_COMS; else return FRAME_SLEEP; } void stopTimers() { M0Timer.stop(_BLOCK_TIMER); M0Timer.stop(_FRAME_TIMER); if (M0Timer.getFired(_FRAME_TIMER)) { pcln(""Frame Timer Stopped Before Handle"", C_RED); } if (M0Timer.getFired(_BLOCK_TIMER)) { pcln(""Block Timer Stopped Before Handle"", C_RED); } blockTimerSet = false; frameTimerSet = false; } // Get the time from now until the event at cycleDelay micros from cycleStart // will occur. long getDelayMicros(uint32_t cycleDelay, uint32_t now) { long delay = (long) (cycleStart - now + cycleDelay); return delay; } // Set the frame timer based on the cycle delay and the offset. The cycle delay // should be the number of micros between the start of the cycle and when the // timer should fire. The offset should be the current time boolean setFrameTimer(uint32_t cycleDelay, uint32_t now, boolean wrapTime = false) { // inc(); // Set the delay based on the cycle start time, the offset (now time), and // the callback delay (referenced to the cycle start time) long delay = getDelayMicros(cycleDelay, now); // If wrapping is enabled, then we ensure that the delay is greater than // min delay by wrapping an ENTIRE cycle time onto it until that is the case. // The means that the time will always be the NEXT cycleDelay offset from a // cycleStart with a value greater than MIN_DELAY. IF wrapping is disabled // and the delay is less than MIN_DELAY, then we cannot set the timer if (wrapTime) { while (delay < MIN_DELAY) { // sprintf(medium_buf, ""| → Wrap: %lu"", delay); pcln(medium_buf); delay += settings.t_c; //settings.t_fs + settings.t_fr + settings.t_fc; } } else if (delay < MIN_DELAY) { // Serial.println(""FT False""); sprintf(medium_buf, ""> Frame Timer Delay too Short %ld"", delay); pcln(medium_buf); return false; } // pcln(""a""); // Start the frame timer with the given delay. Set it to calculate an internal // offset such that the timer starts as close as possible to right now. // TODO Should we use now instead of micros() for the offset? M0Timer.start(delay, _FRAME_TIMER, now); // pcln(""b""); frameTimerSet = true; sprintf(medium_buf, ""> Frame Timer set: %ld"", delay + now); pcln(medium_buf); sprintf(medium_buf, ""| → Delay: %lu"", delay); pcln(medium_buf); sprintf(medium_buf, ""| → CycleDelay: %lu"", cycleDelay); pcln(medium_buf); sprintf(medium_buf, ""| → Now: %ld"", now); pcln(medium_buf); // dec(); return true; } boolean setBlockTimer(uint32_t cycleDelay, uint32_t now) { // Set the delay based on the cycle start time, the offset (now time), and // the callback delay (referenced to the cycle start time) long delay = getDelayMicros(cycleDelay, now); if (delay < MIN_DELAY) { sprintf(medium_buf, ""> Block Timer Delay too Short %ld"", delay); pcln(medium_buf); return false; } // Start the block timer with the given delay. Set it to calculate an internal // offset such that the timer starts as close as possible to right now. // TODO Should we use now instead of micros() for the offset? M0Timer.start(delay, _BLOCK_TIMER, micros()); blockTimerSet = true; sprintf(medium_buf, ""> Block Timer set: %ld"", delay + now); pcln(medium_buf); sprintf(medium_buf, ""| → Delay: %lu"", delay); pcln(medium_buf); sprintf(medium_buf, ""| → Now: %ld"", now); pcln(medium_buf); return true; } boolean updateTimers(struct State * state, state_fn * frameState, state_fn * blockState, uint32_t frameDelay, uint32_t blockDelay, uint32_t now) { // Set the frame timer. IF we are too close to the frame timer's time, then we // set our state to the frameState value and return false to alert the user boolean prompt = setFrameTimer(frameDelay, now); if (!prompt) { M0Timer.stop(_BLOCK_TIMER); // TODO Not Needed? state->next = frameState; pcln(""> Frame Timer late!"", C_RED); return false; } // Check to see that we should set the timer if(blockDelay > 0){ // Set up the block timer to fire when it is time for us to move to our // ranging block. If that is too soon, then move to blockState and return // false to alert the user prompt = setBlockTimer(blockDelay, now); if (!prompt) { state->next = blockState; pcln(""> Block Timer late!"", C_RED); return false; } }else{ // Reset the timer M0Timer.stop(_BLOCK_TIMER); blockTimerSet = false; pcln(""> Disabled Block Timer"", C_BLUE); } // If both timers were set correctly, return true return true; } // Check the block and frame timers to see if they have fired. If they have, // then set the next state to one of the given states (frame and block). Returns // true if a timer fired. Returns false if no timer fired boolean checkTimers(struct State * state, state_fn * frameState, state_fn * blockState) { // Frame Timer if (M0Timer.getFired(_FRAME_TIMER)) { sprintf(medium_buf, ""> Frame Timer Fired: %lu"", micros()); pcln(medium_buf); state->next = frameState; return true; } if (M0Timer.getFired(_BLOCK_TIMER)) { sprintf(medium_buf, ""> Block Timer Fired: %lu"", micros()); pcln(medium_buf); state->next = blockState; return true; } if (millis() - milliTimer > MAX_STALL_TIME) { sprintf(medium_buf, ""> Stall Timer Fired (from checkTimers) %lu"", micros()); pcln(medium_buf); state->next = sleep; cycleValid = 0; return true; } return false; } boolean checkMillis(struct State * state) { if (millis() - milliTimer > MAX_STALL_TIME) { sprintf(medium_buf, ""> Stall Timer Fired %lu"", micros()); pcln(medium_buf); state->next = sleep; cycleValid = 0; return true; } return false; } uint8_t getMsgSeq(){ uint8_t tmp = msg_seq; msg_seq++; if(msg_seq > 31){ msg_seq = 0; } return tmp; } void hexDump(char *desc, void *addr, int len) { int i; unsigned char buff[17]; unsigned char *pc = (unsigned char *)addr; // Output description if given. if (desc != NULL) { sprintf(large_buf, ""%s:\\n\\r"", desc); Serial.print(large_buf); } if (len == 0) { Serial.print("" ZERO LENGTH\\n\\r""); return; } if (len < 0) { sprintf(large_buf, "" NEGATIVE LENGTH: %i\\n\\r"", len); Serial.print(large_buf); return; } // Process every byte in the data. for (i = 0; i < len; i++) { // Multiple of 16 means new line (with line offset). if ((i % 16) == 0) { // Just don't print ASCII for the zeroth line. if (i != 0) { sprintf(large_buf, "" %s\\n\\r"", buff); Serial.print(large_buf); } // Output the offset. sprintf(large_buf, "" %04x "", i); Serial.print(large_buf); } // Now the hex code for the specific character. sprintf(large_buf, "" %02x"", pc[i]); Serial.print(large_buf); // And store a printable ASCII character for later. if ((pc[i] < 0x20) || (pc[i] > 0x7e)) buff[i % 16] = '.'; else buff[i % 16] = pc[i]; buff[(i % 16) + 1] = '\\0'; } // Pad out last line if not exactly 16 characters. while ((i % 16) != 0) { Serial.print("" ""); i++; } // And print the final ASCII bit. sprintf(large_buf, "" %s\\n\\r"", buff); Serial.print(large_buf); } ",12309,False,2038.574690654982,median "/* This project is originally created by PADMALAYA RAWAL and you can support me here: * yt channel: https://www.youtube.com/PRROBOTICS * Patreon : https://www.patreon.com/PRROBOTICS * Instagram : https://www.instagram.com/PRROBOTICS DISCLAIMER: For this project I am using libraries from various awesome creators and you can checkout their work below: 1. creator of USB library: https://github.com/arduino-libraries/Keyboard/ 2. creator of Blekeyboard library: https://github.com/T-vK/ESP32-BLE-Keyboard 3. creator of Adafruit library: https://www.adafruit.com/ ** ** A message from Adafruit library creator ** ** Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries, with contributions from the open source community. BSD license, check license.txt for more information All text above, and the splash screen below must be included in any redistribution.*/ /* NOTE: * 1. Before using the fingerprint module make sure that you have already added your fingerprint * to it and then assign that number in this code. * * 2. Make sure that you have added all the required libraries. * * 3. You can replace the touch switch with slide switches as well and change the connections accordingly. */ //Before using it with any of your device, check the code and connections carefully because if something //goes wrong anything can happen with your connected device which may harm your device as it is a complete //keyboard. And I will not bw responsible for any type of loss or damage in any manner. Use it at your own RISK. #include ""Adafruit_Keypad.h"" #include #include #include #include #include #include #include #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 32 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) #define Keyboard_mode 35 //change the pin number #define shift 13 //change the pin number #define caps_lock 12 const byte ROWS = 5; //no of rows of keyboard const byte COLS = 10; //no of columns of keyboard int Read_Keyboard_mode; //to change the mode of Keyboard int Read_shift; //to read the value of shift key int Read_caps_lock; //to read the value of capslock key int flag1; //for mode change int flag2; //for mode change int con; //flag for bt connection int f_check; //flag for fingerprint sensor //Note here that these character doesn't represent their actual representation of the keypress char keys[ROWS][COLS] = { {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}, {'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'}, {'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3'}, {'4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D'}, {'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'} }; //These pin numbers should be changed according to connections of keypad with ESP32 board byte colPins[COLS] = {4,36,3,5,18,19,34,15,23,26}; byte rowPins[ROWS] = {25,27,14,33,32}; Adafruit_Keypad customKeypad = Adafruit_Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial2); BleKeyboard bleKeyboard; //___________________________________________________________________________ uint8_t getFingerprintID() { uint8_t p = finger.getImage(); switch (p) { case FINGERPRINT_OK: Serial.println(""Image taken""); break; case FINGERPRINT_NOFINGER: Serial.println(""No finger detected""); return p; case FINGERPRINT_PACKETRECIEVEERR: Serial.println(""Communication error""); return p; case FINGERPRINT_IMAGEFAIL: Serial.println(""Imaging error""); return p; default: Serial.println(""Unknown error""); return p; } // OK success! p = finger.image2Tz(); switch (p) { case FINGERPRINT_OK: Serial.println(""Image converted""); break; case FINGERPRINT_IMAGEMESS: Serial.println(""Image too messy""); return p; case FINGERPRINT_PACKETRECIEVEERR: Serial.println(""Communication error""); return p; case FINGERPRINT_FEATUREFAIL: Serial.println(""Could not find fingerprint features""); return p; case FINGERPRINT_INVALIDIMAGE: Serial.println(""Could not find fingerprint features""); return p; default: Serial.println(""Unknown error""); return p; } // OK converted! p = finger.fingerFastSearch(); if (p == FINGERPRINT_OK) { Serial.println(""Found a print match!""); } else if (p == FINGERPRINT_PACKETRECIEVEERR) { Serial.println(""Communication error""); return p; } else if (p == FINGERPRINT_NOTFOUND) { Serial.println(""Did not find a match""); return p; } else { Serial.println(""Unknown error""); return p; } // found a match! Serial.print(""Found ID #""); Serial.print(finger.fingerID); Serial.print("" with confidence of ""); Serial.println(finger.confidence); return finger.fingerID; } // returns -1 if failed, otherwise returns ID # int getFingerprintIDez() { uint8_t p = finger.getImage(); if (p != FINGERPRINT_OK) return -1; p = finger.image2Tz(); if (p != FINGERPRINT_OK) return -1; p = finger.fingerFastSearch(); if (p != FINGERPRINT_OK) return -1; // found a match! Serial.print(""Found ID #""); Serial.print(finger.fingerID); Serial.print("" with confidence of ""); Serial.println(finger.confidence); return finger.fingerID; } //_____________________________________________________________________ void setup() { Serial.begin(115200); Serial.println(""Starting BLE work!""); bleKeyboard.begin(); customKeypad.begin(); finger.begin(57600); if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 Serial.println(F(""SSD1306 allocation failed"")); for(;;); // Don't proceed, loop forever } display.setTextSize(2); // change the size of text on OLED display.setTextColor(SSD1306_WHITE); // Draw white text delay(1000); display.clearDisplay(); display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.setCursor(20 ,0); display.println(F(""Developed by:"")); display.setTextSize(2); display.setTextColor(SSD1306_WHITE); display.setCursor(5,15); display.println(""PADMALAYA""); display.display(); delay(3000); display.clearDisplay(); display.display(); pinMode(Keyboard_mode, INPUT_PULLUP); pinMode(shift, INPUT_PULLUP); pinMode(caps_lock, INPUT_PULLUP); } void loop() { Read_shift=digitalRead(shift); Read_caps_lock= digitalRead(caps_lock); Read_Keyboard_mode= digitalRead(Keyboard_mode); if(bleKeyboard.isConnected()) { if(con==0){ display.clearDisplay(); display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.setCursor(30,8); display.print(F(""Connected!! "")); display.setCursor(35,18); display.print(F(""Enjoy :-) "")); display.display(); con=1; delay(2000); } if((Read_Keyboard_mode)==HIGH){ while(flag1==0){ display.clearDisplay(); display.setCursor(5, 0); // Start at top-left corner display.setTextSize(2); display.write("" SUPER""); display.setCursor(0, 18); // Start at top-left corner display.write("" KEYBOARD""); display.display(); delay(3000); display.clearDisplay(); display.setTextSize(1); display.setCursor(28,8); display.write(""Press any key""); display.setCursor(33, 18); // Start at top-left corner display.write(""to continue""); display.display(); flag2=0; flag1=1; } customKeypad.tick(); while(customKeypad.available()) { keypadEvent e = customKeypad.read(); char out=(char)e.bit.KEY; if(e.bit.EVENT == KEY_JUST_PRESSED) { display.setTextSize(2); switch(out) { case 'a': if(Read_shift==LOW){ bleKeyboard.write(48); //print 0 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""0""); display.display();} else if(Read_caps_lock == LOW){ bleKeyboard.write(65); //print A display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""A""); display.display();} else { bleKeyboard.write(97); //print a display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""a""); display.display();} break; case 'b': if((Read_shift)==LOW){ bleKeyboard.write(49); //print 1 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""1""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(66); //print B display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""B""); display.display();} else { bleKeyboard.write(98); //print b display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""b""); display.display();} break; case 'c': if((Read_shift)==LOW){ bleKeyboard.write(50); //print 2 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""2""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(67); //print C display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""C""); display.display();} else{ bleKeyboard.write(99); //print c display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""c""); display.display();} break; case 'd': if((Read_shift)==LOW){ bleKeyboard.write(51); //print 3 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""3""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(68); //print D display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""D""); display.display();} else{ bleKeyboard.write(100); //print d display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""d""); display.display();} break; case 'e': if((Read_shift)==LOW){ bleKeyboard.write(52); //print 4 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""4""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(69); //print E display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""E""); display.display();} else{ bleKeyboard.write(101); //print e display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""e""); display.display();} break; case 'f': if((Read_shift)==LOW){ bleKeyboard.write(53); //print 5 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""5""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(70); //print F display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""F""); display.display();} else{ bleKeyboard.write(102); //print f display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""f""); display.display();} break; case 'g': if((Read_shift)==LOW){ bleKeyboard.write(54); //print 6 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""6""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(71); //print G display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""G""); display.display();} else{ bleKeyboard.write(103); //print g display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""g""); display.display();} break; case 'h': if((Read_shift)==LOW){ bleKeyboard.write(55); //print 7 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""7""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(72); //print H display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""H""); display.display();} else{ bleKeyboard.write(104); //print h display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""h""); display.display();} break; case 'i': if((Read_shift)==LOW){ bleKeyboard.write(56); //print 8 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""8""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(73); //print I display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""I""); display.display();} else{ bleKeyboard.write(105); //print i display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""i""); display.display();} break; case 'j': if((Read_shift)==LOW){ bleKeyboard.write(57); //print 9 display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""9""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(74); //print J display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""J""); display.display();} else{ bleKeyboard.write(106); //print j display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""j""); display.display();} break; case 'k': if((Read_shift)==LOW){ bleKeyboard.write(33); //print ! display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""!""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(75); //print K display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""K""); display.display();} else{ bleKeyboard.write(107); //print k display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""k""); display.display();} break; case 'l': if((Read_shift)==LOW){ bleKeyboard.write(64); //print @ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""@""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(76); //print L display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""L""); display.display();} else{ bleKeyboard.write(108); //print l display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""l""); display.display();} break; case 'm': if((Read_shift)==LOW){ bleKeyboard.write(35); //print # display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""#""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(77); //print M display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""M""); display.display();} else{ bleKeyboard.write(109); //print m display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""m""); display.display();} break; case 'n': if((Read_shift)==LOW){ bleKeyboard.write(36); //print $ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""$""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(78); //print N display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""N""); display.display();} else{ bleKeyboard.write(110); //print n display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""n""); display.display();} break; case 'o': if((Read_shift)==LOW){ bleKeyboard.write(37); //print % display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""%""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(79); //print O display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""O""); display.display();} else{ bleKeyboard.write(111); //print o display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""o""); display.display();} break; case 'p': if((Read_shift)==LOW){ bleKeyboard.write(94); //print ^ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""^""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(80); //print P display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""P""); display.display();} else{ bleKeyboard.write(112); //print p display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""p""); display.display();} break; case 'q': if((Read_shift)==LOW){ bleKeyboard.write(38); //print & display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""&""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(81); //print Q display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""Q""); display.display();} else{ bleKeyboard.write(113); //print q display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""q""); display.display();} break; case 'r': if((Read_shift)==LOW){ bleKeyboard.write(42); //print * display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""*""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(82); //print R display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""R""); display.display();} else{ bleKeyboard.write(114); //print r display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""r""); display.display();} break; case 's': if((Read_shift)==LOW){ bleKeyboard.write(40); //print ( display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""(""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(83); //print S display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""S""); display.display();} else{ bleKeyboard.write(115); //print s display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""s""); display.display();} break; case 't': if((Read_shift)==LOW){ bleKeyboard.write(41); //print ) display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write("")""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(84); //print T display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""T""); display.display();} else{ bleKeyboard.write(116); //print t display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""t""); display.display();} break; case 'u': if((Read_shift)==LOW){ bleKeyboard.write(45); //print - display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""-""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(85); //print U display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""U""); display.display();} else{ bleKeyboard.write(117); //print u display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""u""); display.display();} break; case 'v': if((Read_shift)==LOW){ bleKeyboard.write(95); //print _ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""_""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(86); //print V display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""V""); display.display();} else{ bleKeyboard.write(118); //print v display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""v""); display.display();} break; case 'w': if((Read_shift)==LOW){ bleKeyboard.write(61); //print = display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""=""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(87); //print W display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""W""); display.display();} else{ bleKeyboard.write(119); //print w display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""w""); display.display();} break; case 'x': if((Read_shift)==LOW){ bleKeyboard.write(43); //print + display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""+""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(88); //print X display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""X""); display.display();} else{ bleKeyboard.write(120); //print x display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""x""); display.display();} break; case 'y': if((Read_shift)==LOW){ bleKeyboard.write(96); //print ` display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""`""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(89); //print Y display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""Y""); display.display();} else{ bleKeyboard.write(121); //print y display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""y""); display.display();} break; case 'z': if((Read_shift)==LOW){ bleKeyboard.write(126); //print ~ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""~""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(90); //print Z display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""Z""); display.display();} else{ bleKeyboard.write(122); //print z display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""z""); display.display();} break; case '0': if((Read_shift)==LOW){ bleKeyboard.write(123); //print { display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""{""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(125); //print } display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""}""); display.display();} else{ bleKeyboard.write(124); //print | display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""|""); display.display();} break; case '1': if((Read_shift)==LOW){ bleKeyboard.write(91); //print [ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""[""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(93); //print ] display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""]""); display.display();} else{ bleKeyboard.write(63); //print ? display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""?""); display.display();} break; case '2': if((Read_shift)==LOW){ bleKeyboard.write(47); //print / display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""/""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(92); //print \\ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""B-SLASH""); display.display();} else{ bleKeyboard.write(44); //print , display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write("",""); display.display();} break; case '3': if((Read_shift)==LOW){ bleKeyboard.write(39); //print ' display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""'""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(34); //print "" display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""D-QUOTE""); display.display();} else{ bleKeyboard.write(46); //print . display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write("".""); display.display();} break; case '4': if((Read_shift)==LOW){ bleKeyboard.write(60); //print < display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""<""); display.display();} else if((Read_caps_lock)== LOW){ bleKeyboard.write(62); //print > display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write("">""); display.display();} else{ bleKeyboard.write(58); //print : display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write("":""); display.display();} break; case '5': bleKeyboard.write(128); //ctrl display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""CTRL""); display.display(); break; case '6': bleKeyboard.write(130); //alt display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""ALT""); display.display(); break; case '7': bleKeyboard.write(179); //tab display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""TAB""); display.display(); break; case '8': bleKeyboard.write(32); //space display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""SPACE""); display.display(); break; case '9': bleKeyboard.write(178); //backspace display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""BACKSPACE""); display.display(); break; case 'A': bleKeyboard.write(218); //up arrow display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""UP ARROW""); display.display(); break; case 'B': bleKeyboard.write(217); //down arrow display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""DOWN ARROW""); display.display(); break; case 'C': bleKeyboard.write(216); //left arrow display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""LEFT ARROW""); display.display(); break; case 'D': bleKeyboard.write(215); //right arrow display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""RIGHT ARROW""); display.display(); break; case 'E': bleKeyboard.write(KEY_MEDIA_VOLUME_UP); //volume+ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""VOL+""); display.display(); break; case 'F': bleKeyboard.write(KEY_MEDIA_VOLUME_DOWN); //volume- display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""VOL-""); display.display(); break; case 'G': bleKeyboard.write(KEY_MEDIA_MUTE); //mute display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""MUTE""); display.display(); break; case 'H': bleKeyboard.write(KEY_MEDIA_NEXT_TRACK); //next display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NEXT TRACK""); display.display(); break; case 'I': bleKeyboard.write(KEY_MEDIA_PREVIOUS_TRACK); //prev display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""PREV TRACK""); display.display(); break; case 'J': bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE); //play/pause display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""PLAY/PAUSE""); display.display(); break; case 'K': bleKeyboard.write(KEY_MEDIA_STOP); //stop display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""STOP""); display.display(); break; case 'L': bleKeyboard.write(176); //enter display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""ENTER""); display.display(); break; case 'M': bleKeyboard.write(212); //delete display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""DELETE""); display.display(); break; case 'N': //WRITE COMMANDS FOR SHUTING DOWN THE PC bleKeyboard.press(128); bleKeyboard.press(177); delay(500); bleKeyboard.releaseAll(); delay(1000); bleKeyboard.press(179); delay(100); bleKeyboard.release(179); delay(100); bleKeyboard.press(217); delay(100); bleKeyboard.release(217); delay(100); bleKeyboard.press(217); delay(100); bleKeyboard.release(217); delay(100); bleKeyboard.press(217); delay(100); bleKeyboard.release(217); delay(100); bleKeyboard.press(176); delay(100); bleKeyboard.release(176); delay(100); bleKeyboard.press(217); delay(100); bleKeyboard.release(217); delay(100); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""SHUT DOWN""); display.display(); } } } } //MODE 2: PASSWORD MANAGER //__________________________________________________________________________________ if((Read_Keyboard_mode)==LOW){ while(flag2==0){ display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.setTextSize(2); display.write("" PASSWORD""); display.setCursor(0, 18); // Start at top-left corner display.write("" MANAGER""); delay(2000); display.clearDisplay(); display.setTextSize(1); display.setCursor(28,8); display.write(""Place finger""); display.setCursor(10, 18); // Start at top-left corner display.write(""for authentication""); display.display(); getFingerprintIDez(); delay(50); f_check= finger.fingerID; while(f_check == 1){ display.clearDisplay(); display.setTextSize(1); display.setCursor(25,8); display.write(""Authentication""); display.setCursor(30, 18); // Start at top-left corner display.write(""completed!!""); display.display(); delay(2000); display.clearDisplay(); display.setTextSize(1); display.setCursor(28,8); display.write(""Press any key""); display.setCursor(33, 18); // Start at top-left corner display.write(""to continue""); display.display(); flag2=1; f_check=0; } flag1=0; } customKeypad.tick(); while(customKeypad.available()) { keypadEvent e = customKeypad.read(); char out=(char)e.bit.KEY; display.setTextSize(2); if(e.bit.EVENT == KEY_JUST_PRESSED) { switch(out) { case 'a': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""INSTAGRAM""); display.setCursor(0,18); display.display(); bleKeyboard.print(""PDKS54DFG""); //Print password break; case 'b': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""FACEBOOK""); display.setCursor(0,18); display.display(); bleKeyboard.print(""4634SEDGASD""); //Print password break; case 'c': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""REDDIT""); display.setCursor(0,18); display.display(); bleKeyboard.print(""^3452dfsghF""); //Print password break; case 'd': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""LINKEDIN""); display.setCursor(0,18); display.display(); bleKeyboard.print(""$@$%fhjd54""); //Print password break; case 'e': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""TWITTER""); display.setCursor(0,18); display.display(); bleKeyboard.print(""53456ASDFdgafd""); //Print password break; case 'f': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""SNAPCHAT""); display.setCursor(0,18); display.display(); bleKeyboard.print(""PDKS54DFG""); //Print password break; case 'g': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""PAYPAL""); display.setCursor(0,18); display.display(); bleKeyboard.print(""5DSSFDJKs(^&#$""); //Print password break; case 'h': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""GPAY""); display.setCursor(0,18); display.display(); bleKeyboard.print(""5DR(%^@!tWERT""); //Print password break; case 'i': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""OUTLOOK""); display.setCursor(0,18); display.display(); bleKeyboard.print(""Dsrf54676*(@!@$FG""); //Print password break; case 'j': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""BLYNK""); display.setCursor(0,18); display.display(); bleKeyboard.print(""Wredgt45653vg""); //Print password break; case 'k': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""PATREON""); display.setCursor(0,18); display.display(); bleKeyboard.print(""2#$%WG54fqSEDTd""); //Print password break; case 'l': display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""PINTEREST""); display.setCursor(0,18); display.display(); bleKeyboard.print(""asddfF3254@#$""); //Print password break; case 'm': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'n': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'o': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'p': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'q': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'r': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 's': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 't': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'u': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'v': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'w': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'x': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'y': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'z': bleKeyboard.print("" ""); //print a display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '0': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '1': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '2': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '3': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '4': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '5': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '6': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '7': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '8': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case '9': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'A': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'B': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'C': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'D': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'E': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'G': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'H': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'I': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'J': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'K': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'L': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'M': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; case 'N': bleKeyboard.print(""""); display.clearDisplay(); display.setCursor(0, 0); // Start at top-left corner display.write(""NOT Assigned""); display.display(); break; } } } } } else{ display.clearDisplay(); display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.setCursor(28,8); display.print(F(""Connect with "")); display.setCursor(33,18); display.print(F(""your device "")); display.display(); } } ",12061,True,3070.1973724939926,median "CLASS z2mse_main_test DEFINITION PUBLIC CREATE PUBLIC . PUBLIC SECTION. METHODS: setup, z2mse_test_initial_selection, z2mse_test_initial_selection2, specific_search_method, specific_search_attribute, specific_search_class, specific_search_program, specific_search_function, z2mse_test_2021. PROTECTED SECTION. PRIVATE SECTION. DATA: mse_model_act TYPE z2mse_model=>lines_type, fes_act TYPE z2mse_extr3_model_builder=>found_elements_type, fes_exp TYPE z2mse_extr3_model_builder=>found_elements_type, equalized_harmonized_mse_act TYPE z2mse_mse_harmonize=>harmonized_mse, equalized_harmonized_mse_exp TYPE z2mse_mse_harmonize=>harmonized_mse, maker TYPE REF TO z2mse_mse_harmonize_maker. METHODS _search_specific IMPORTING parent_name_filter TYPE z2mse_extr3_initial_elements=>ty_filter name_filter TYPE z2mse_extr3_initial_elements=>ty_filter dynamic_read TYPE string element_type_filter TYPE z2mse_extr3_initial_elements=>ty_filter i_search_up TYPE i i_search_down TYPE i. METHODS _check_found_elements IMPORTING msg TYPE string. METHODS _check_harmonized_mse IMPORTING msg TYPE string. ENDCLASS. CLASS z2mse_main_test IMPLEMENTATION. METHOD setup. "" This is mandatory to decouple the separate unit tests z2mse_extr3=>clear_all( ). CLEAR mse_model_act. CLEAR equalized_harmonized_mse_act. CLEAR equalized_harmonized_mse_exp. CLEAR fes_act. CLEAR fes_exp. equalized_harmonized_mse_exp = VALUE #( ). ENDMETHOD. METHOD specific_search_method. _search_specific( i_search_up = 1 i_search_down = 1 element_type_filter = z2mse_extr3_initial_elements=>select_class_method dynamic_read = |Z2MSE_TEST_DYNAMIC_USAGE| parent_name_filter = 'Z2MSE_TEST2_CL_A' name_filter = 'METHOD' ). fes_exp = VALUE #( ( where = |I| level = 0 alternate_level = 0 element_type = |ABAPClassMethod| parent_name = |Z2MSE_TEST2_CL_A| name = |METHOD| specific = |X| ) ( where = |I| level = 1 alternate_level = 0 element_type = |ABAPClassMethod| parent_name = |Z2MSE_TEST2_CL_A| name = |METHOD2| specific = |X| ) ( where = |S| level = 1 alternate_level = 0 element_type = |ABAPClassMethod| parent_name = |Z2MSE_TEST2_CL_B| name = |METHOD| specific = |X| ) ). _check_found_elements( 'Expect correct list of found elements' ). maker = NEW #( ). maker->to_change = equalized_harmonized_mse_exp. maker->add_custom_source_language( language = |SAP| ). maker->add_package( package = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_class( name = |Z2MSE_TEST2_CL_A| parentpackage = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_attribute( attribute = |ATTRIBUTE| at_line = 7 ). maker->add_method( method = |METHOD| at_line = 8 ). maker->add_method( method = |METHOD2| at_line = 9 ). maker->usage( used_group = |Z2MSE_TEST2_CL_A| used = |METHOD| ). maker->add_class( name = |Z2MSE_TEST2_CL_B| parentpackage = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_method( method = |METHOD| at_line = 7 ). maker->usage( used_group = |Z2MSE_TEST2_CL_A| used = |METHOD| ). _check_harmonized_mse( 'Wrong mse file for specific search class component' ). ENDMETHOD. METHOD specific_search_attribute. "" Search for usage of attributes _search_specific( i_search_up = 1 i_search_down = 1 element_type_filter = z2mse_extr3_initial_elements=>select_class_method dynamic_read = |Z2MSE_TEST_DYNAMIC_USAGE| parent_name_filter = 'Z2MSE_TEST2_CL_A' name_filter = 'ATTRIBUTE' ). fes_exp = VALUE #( ( where = |I| level = 0 alternate_level = 0 element_type = |ABAPClassAttribute| parent_name = |Z2MSE_TEST2_CL_A| name = |ATTRIBUTE| specific = |X| ) ( where = |S| level = 1 alternate_level = 0 element_type = |ABAPClassMethod| parent_name = |Z2MSE_TEST2_CL_B| name = |METHOD| specific = |X| ) ). _check_found_elements( 'Expect correct list of found elements' ). maker = NEW #( ). maker->to_change = equalized_harmonized_mse_exp. maker->add_custom_source_language( language = |SAP| ). maker->add_package( package = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_class( name = |Z2MSE_TEST2_CL_A| parentpackage = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_attribute( attribute = |ATTRIBUTE| at_line = 7 ). maker->add_method( method = |METHOD| at_line = 8 ). maker->add_method( method = |METHOD2| at_line = 9 ). maker->add_class( name = |Z2MSE_TEST2_CL_B| parentpackage = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_method( method = |METHOD| at_line = 7 ). * maker->usage( used_group = |Z2MSE_TEST2_CL_A| used = |METHOD| ). maker->access( used_group = |Z2MSE_TEST2_CL_A| used = |ATTRIBUTE| ). _check_harmonized_mse( 'Wrong mse file for specific search class component' ). ENDMETHOD. METHOD specific_search_class. "" Search for usage of all elements of a class * cl_abap_unit_assert=>fail( msg = 'Finalize test and coding to implement #122' ). _search_specific( i_search_up = 1 i_search_down = 1 element_type_filter = z2mse_extr3_initial_elements=>select_class_method dynamic_read = |Z2MSE_TEST_DYNAMIC_USAGE| parent_name_filter = '' name_filter = 'Z2MSE_TEST2_CL_A' ). fes_exp = VALUE #( ( where = |S| level = -1 alternate_level = 0 element_type = |ABAPDatabaseTable| parent_name = || name = |SFLIGHT| specific = |X| ) ( where = |I| level = 0 alternate_level = 0 element_type = |ABAPClass| parent_name = || name = |Z2MSE_TEST2_CL_A| specific = |X| ) ( where = |I| level = 0 alternate_level = 0 element_type = |ABAPClassAttribute| parent_name = |Z2MSE_TEST2_CL_A| name = |ATTRIBUTE| specific = |X| ) ( where = |I| level = 0 alternate_level = 0 element_type = |ABAPClassMethod| parent_name = |Z2MSE_TEST2_CL_A| name = |METHOD| specific = |X| ) ( where = |I| level = 0 alternate_level = 0 element_type = |ABAPClassMethod| parent_name = |Z2MSE_TEST2_CL_A| name = |METHOD2| specific = |X| ) ( where = |S| level = 1 alternate_level = 0 element_type = |ABAPClassMethod| parent_name = |Z2MSE_TEST2_CL_B| name = |METHOD| specific = |X| ) ). _check_found_elements( 'Expect correct list of found elements' ). maker = NEW #( ). maker->to_change = equalized_harmonized_mse_exp. maker->add_custom_source_language( language = |SAP| ). maker->add_package( package = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_package( package = |SAPBC_DATAMODEL| ). maker->add_db_table( name = |SFLIGHT| parentpackage = |SAPBC_DATAMODEL| ). maker->add_class( name = |Z2MSE_TEST2_CL_A| parentpackage = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_attribute( attribute = |ATTRIBUTE| at_line = 7 ). maker->add_method( method = |METHOD| at_line = 8 ). maker->add_method( method = |METHOD2| at_line = 9 ). maker->access( used_group = 'SFLIGHT' used = 'SFLIGHT' ). maker->usage( used_group = |Z2MSE_TEST2_CL_A| used = |METHOD| ). maker->add_class( name = |Z2MSE_TEST2_CL_B| parentpackage = |Z2MSE_TEST2_CLASS_SPEC| ). maker->add_method( method = |METHOD| at_line = 7 ). maker->usage( used_group = |Z2MSE_TEST2_CL_A| used = |METHOD| ). maker->access( used_group = |Z2MSE_TEST2_CL_A| used = |ATTRIBUTE| ). _check_harmonized_mse( 'Wrong mse file for specific search class component' ). ENDMETHOD. METHOD specific_search_function. DATA: mse_model_act TYPE z2mse_model=>lines_type. DATA: nothing_done_act TYPE abap_bool. DATA(initial_elements) = NEW z2mse_extr3_initial_elements( ). DATA(model_builder) = NEW z2mse_extr3_model_builder( ). DATA(element_manager) = NEW z2mse_extr3_element_manager( i_model_builder = model_builder i_exclude_found_sap_intf = abap_true i_interface_use_structure = abap_false ). model_builder->initialize( i_element_manager = element_manager i_dynamic_read = |Z2MSE_TEST_DYNAMIC_USAGE| ). initial_elements->select_specific( EXPORTING model_builder = model_builder element_manager = element_manager i_element_type_filter = z2mse_extr3_initial_elements=>select_function i_parent_name_filter = '' i_name_filter = 'Z2MSE_TEST2_I_FUNCTION_A' ). DATA(f_cut) = NEW z2mse_extract3( ). f_cut->extract( EXPORTING model_builder = model_builder element_manager = element_manager initial_elements = initial_elements i_search_up = 2 i_search_down = 2 i_exclude_found_sap_intf = abap_true IMPORTING mse_model = mse_model_act nothing_done = nothing_done_act ). DATA: fes_act TYPE z2mse_extr3_model_builder=>found_elements_type, fes_exp TYPE z2mse_extr3_model_builder=>found_elements_type. model_builder->write_found_elements( EXPORTING write = abap_false IMPORTING fes = fes_act ). fes_exp = VALUE #( ( where = |S| level = -2 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |F-Z2MSE_TEST2_M2_FUNCTION_A| specific = |X| ) ( where = |S| level = -1 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |F-Z2MSE_TEST2_M1_FUNCTION_A| specific = |X| ) ( where = |I| level = 0 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |F-Z2MSE_TEST2_I_FUNCTION_A| specific = |X| ) ( where = |S| level = 1 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |F-Z2MSE_TEST2_P1_FUNCTION_A| specific = |X| ) ( where = |S| level = 2 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |F-Z2MSE_TEST2_P2_FUNCTION_A| specific = |X| ) ). SORT fes_act. SORT fes_exp. cl_abap_unit_assert=>assert_equals( msg = 'Expect correct list of found elements' exp = fes_exp act = fes_act ). DATA: equalized_harmonized_mse_act TYPE z2mse_mse_harmonize=>harmonized_mse, equalized_harmonized_mse_exp TYPE z2mse_mse_harmonize=>harmonized_mse. equalized_harmonized_mse_act = z2mse_mse_harmonize=>mse_2_harmonized( mse = mse_model_act ). equalized_harmonized_mse_exp = VALUE #( ). DATA maker TYPE REF TO z2mse_mse_harmonize_maker. maker = NEW #( ). maker->to_change = equalized_harmonized_mse_exp. maker->add_custom_source_language( |SAP| ). maker->add_package( package = |Z2MSE_TEST2_INITIAL| ). maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_I_FGR_A| parentpackage = |Z2MSE_TEST2_INITIAL| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_I_FUNCTION_A| ). * "" This is to be found with the down search for functions * maker->add_package( package = |Z2MSE_TEST2_M1| ). * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_M1_FGR_A| parentpackage = |Z2MSE_TEST2_M1| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_M1_FUNCTION_A| ). * maker->usage( EXPORTING using_group = |FGR-Z2MSE_TEST2_I_FGR_A| using = |F-Z2MSE_TEST2_I_FUNCTION_A| used_group = |FGR-Z2MSE_TEST2_M1_FGR_A| used = |F-Z2MSE_TEST2_M1_FUNCTION_A| ). * "" This is now found with the up search for functions: * maker->add_package( package = |Z2MSE_TEST2_P1| ). * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_P1_FGR_A| parentpackage = |Z2MSE_TEST2_P1| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_P1_FUNCTION_A| ). maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_I_FGR_A| used = |F-Z2MSE_TEST2_I_FUNCTION_A| ). "" Test downsearch for programs * maker->add_program( EXPORTING name = |Z2MSE_TEST2_I_PROGRAM| * parentpackage = |Z2MSE_TEST2_INITIAL| ). "" Test function used by program is found * maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_M1_FGR_A| * used = |F-Z2MSE_TEST2_M1_FUNCTION_A| ). "" Test class used by program is found * maker->add_class( EXPORTING name = |Z2MSE_TEST2_M1_CL_A| * parentpackage = || ). ""Z2MSE_TEST2_M1 * maker->add_method( EXPORTING method = |STATIC_METHOD_A| * at_line = 7 ). * maker->usage( EXPORTING using_group = || * using = |Z2MSE_TEST2_I_PROGRAM| * used_group = |Z2MSE_TEST2_M1_CL_A| * used = |STATIC_METHOD_A| ). * "" Test function used by function is found in down search * maker->add_package( package = |Z2MSE_TEST2_M2| ). maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_M2_FGR_A| parentpackage = |Z2MSE_TEST2_M2| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_M2_FUNCTION_A| ). maker->usage( EXPORTING using_group = |FGR-Z2MSE_TEST2_M1_FGR_A| using = |F-Z2MSE_TEST2_M1_FUNCTION_A| used_group = |FGR-Z2MSE_TEST2_M2_FGR_A| used = |F-Z2MSE_TEST2_M2_FUNCTION_A| ). * "" Test function used by function is found in up search * maker->add_package( package = |Z2MSE_TEST2_P2| ). * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_P2_FGR_A| parentpackage = |Z2MSE_TEST2_P2| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_P2_FUNCTION_A| ). maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_P1_FGR_A| used = |F-Z2MSE_TEST2_P1_FUNCTION_A| ). "" Test program that uses a program is found in up search * maker->add_program( EXPORTING name = |Z2MSE_TEST2_P1_PROGRAM| * parentpackage = |Z2MSE_TEST2_P1| ). * * maker->usage( EXPORTING used_group = || * used = |Z2MSE_TEST2_I_PROGRAM| ). equalized_harmonized_mse_exp = maker->to_change. z2mse_mse_harmonize=>equalize_harmonized( CHANGING harmonized_mse = equalized_harmonized_mse_exp ). cl_abap_unit_assert=>assert_equals( EXPORTING act = equalized_harmonized_mse_act exp = equalized_harmonized_mse_exp msg = 'Wrong mse file for new class' ). ENDMETHOD. METHOD specific_search_program. DATA: mse_model_act TYPE z2mse_model=>lines_type. DATA: nothing_done_act TYPE abap_bool. DATA(initial_elements) = NEW z2mse_extr3_initial_elements( ). DATA(model_builder) = NEW z2mse_extr3_model_builder( ). DATA(element_manager) = NEW z2mse_extr3_element_manager( i_model_builder = model_builder i_exclude_found_sap_intf = abap_true i_interface_use_structure = abap_false ). model_builder->initialize( i_element_manager = element_manager i_dynamic_read = |Z2MSE_TEST_DYNAMIC_USAGE| ). initial_elements->select_specific( EXPORTING model_builder = model_builder element_manager = element_manager i_element_type_filter = z2mse_extr3_initial_elements=>select_program i_parent_name_filter = '' i_name_filter = 'Z2MSE_TEST2_I_PROGRAM' ). DATA(f_cut) = NEW z2mse_extract3( ). f_cut->extract( EXPORTING model_builder = model_builder element_manager = element_manager initial_elements = initial_elements i_search_up = 2 i_search_down = 2 i_exclude_found_sap_intf = abap_true IMPORTING mse_model = mse_model_act nothing_done = nothing_done_act ). DATA: fes_act TYPE z2mse_extr3_model_builder=>found_elements_type, fes_exp TYPE z2mse_extr3_model_builder=>found_elements_type. model_builder->write_found_elements( EXPORTING write = abap_false IMPORTING fes = fes_act ). fes_exp = VALUE #( ( where = |S| level = -2 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |F-Z2MSE_TEST2_M2_FUNCTION_A| specific = |X| ) ( where = |S| level = -1 alternate_level = 0 element_type = |ABAPClass| parent_name = || name = |Z2MSE_TEST2_M1_CL_A| specific = |X| ) ( where = |S| level = -1 alternate_level = 0 element_type = |ABAPClassMethod| parent_name = |Z2MSE_TEST2_M1_CL_A| name = |STATIC_METHOD_A| specific = |X| ) ( where = |S| level = -1 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |F-Z2MSE_TEST2_M1_FUNCTION_A| specific = |X| ) ( where = |I| level = 0 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |Z2MSE_TEST2_I_PROGRAM| specific = |X| ) ( where = |S| level = 1 alternate_level = 0 element_type = |ABAPProgramOrFunctionOrSAPBW| parent_name = || name = |Z2MSE_TEST2_P1_PROGRAM| specific = |X| ) ). SORT fes_act. SORT fes_exp. cl_abap_unit_assert=>assert_equals( msg = 'Expect correct list of found elements' exp = fes_exp act = fes_act ). DATA: equalized_harmonized_mse_act TYPE z2mse_mse_harmonize=>harmonized_mse, equalized_harmonized_mse_exp TYPE z2mse_mse_harmonize=>harmonized_mse. equalized_harmonized_mse_act = z2mse_mse_harmonize=>mse_2_harmonized( mse = mse_model_act ). equalized_harmonized_mse_exp = VALUE #( ). DATA maker TYPE REF TO z2mse_mse_harmonize_maker. maker = NEW #( ). maker->to_change = equalized_harmonized_mse_exp. maker->add_custom_source_language( |SAP| ). maker->add_package( package = |Z2MSE_TEST2_INITIAL| ). * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_I_FGR_A| * parentpackage = |Z2MSE_TEST2_INITIAL| ). * * maker->add_function( EXPORTING function = |Z2MSE_TEST2_I_FUNCTION_A| ). * "" This is to be found with the down search for functions * maker->add_package( package = |Z2MSE_TEST2_M1| ). * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_M1_FGR_A| parentpackage = |Z2MSE_TEST2_M1| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_M1_FUNCTION_A| ). * * maker->usage( EXPORTING using_group = |FGR-Z2MSE_TEST2_I_FGR_A| * using = |F-Z2MSE_TEST2_I_FUNCTION_A| * used_group = |FGR-Z2MSE_TEST2_M1_FGR_A| * used = |F-Z2MSE_TEST2_M1_FUNCTION_A| ). * "" This is now found with the up search for functions: * maker->add_package( package = |Z2MSE_TEST2_P1| ). * * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_P1_FGR_A| * parentpackage = |Z2MSE_TEST2_P1| ). * * maker->add_function( EXPORTING function = |Z2MSE_TEST2_P1_FUNCTION_A| ). * * maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_I_FGR_A| * used = |F-Z2MSE_TEST2_I_FUNCTION_A| ). "" Test downsearch for programs maker->add_program( EXPORTING name = |Z2MSE_TEST2_I_PROGRAM| parentpackage = |Z2MSE_TEST2_INITIAL| ). "" Test function used by program is found maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_M1_FGR_A| used = |F-Z2MSE_TEST2_M1_FUNCTION_A| ). "" Test class used by program is found maker->add_class( EXPORTING name = |Z2MSE_TEST2_M1_CL_A| parentpackage = |Z2MSE_TEST2_M1| ). "" maker->add_method( EXPORTING method = |STATIC_METHOD_A| at_line = 7 ). maker->usage( EXPORTING using_group = || using = |Z2MSE_TEST2_I_PROGRAM| used_group = |Z2MSE_TEST2_M1_CL_A| used = |STATIC_METHOD_A| ). * "" Test function used by function is found in down search * maker->add_package( package = |Z2MSE_TEST2_M2| ). maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_M2_FGR_A| parentpackage = |Z2MSE_TEST2_M2| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_M2_FUNCTION_A| ). maker->usage( EXPORTING using_group = |FGR-Z2MSE_TEST2_M1_FGR_A| using = |F-Z2MSE_TEST2_M1_FUNCTION_A| used_group = |FGR-Z2MSE_TEST2_M2_FGR_A| used = |F-Z2MSE_TEST2_M2_FUNCTION_A| ). * "" Test function used by function is found in up search * * maker->add_package( package = |Z2MSE_TEST2_P2| ). * * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_P2_FGR_A| * parentpackage = |Z2MSE_TEST2_P2| ). * * maker->add_function( EXPORTING function = |Z2MSE_TEST2_P2_FUNCTION_A| ). * * maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_P1_FGR_A| * used = |F-Z2MSE_TEST2_P1_FUNCTION_A| ). "" Test program that uses a program is found in up search maker->add_program( EXPORTING name = |Z2MSE_TEST2_P1_PROGRAM| parentpackage = |Z2MSE_TEST2_P1| ). maker->usage( EXPORTING used_group = || used = |Z2MSE_TEST2_I_PROGRAM| ). equalized_harmonized_mse_exp = maker->to_change. z2mse_mse_harmonize=>equalize_harmonized( CHANGING harmonized_mse = equalized_harmonized_mse_exp ). cl_abap_unit_assert=>assert_equals( EXPORTING act = equalized_harmonized_mse_act exp = equalized_harmonized_mse_exp msg = 'Wrong mse file for new class' ). ENDMETHOD. METHOD z2mse_test_initial_selection. DATA: message TYPE string, interface_use_structure TYPE abap_bool. DO 2 TIMES. setup( ). CASE sy-index. WHEN 1. message = 'Wrong mse file for complex selection'. interface_use_structure = abap_false. WHEN 2. message = 'Wrong mse file for complex selection - Option Interface use structure'. interface_use_structure = abap_true. WHEN OTHERS. ASSERT 1 = 2. ENDCASE. "" Variant, reverse usage of implementing method and implemented interface DATA: mse_model_act TYPE z2mse_model=>lines_type. CLEAR mse_model_act. DATA: nothing_done_act TYPE abap_bool. nothing_done_act = abap_false. DATA(top_packages) = VALUE z2mse_extr3_initial_elements=>ty_s_pack( ( sign = 'I' option = 'EQ' low = 'Z2MSE_TEST_INITIAL_SELECTION' ) ). DATA(sub_packages_filter) = VALUE z2mse_extr3_initial_elements=>ty_s_pack( ). DATA(initial_elements) = NEW z2mse_extr3_initial_elements( ). initial_elements->select_packages( EXPORTING top_packages = top_packages sub_packages_filter = sub_packages_filter including_sub_packages = abap_true ). DATA(model_builder) = NEW z2mse_extr3_model_builder( ). DATA(element_manager) = NEW z2mse_extr3_element_manager( i_model_builder = model_builder i_exclude_found_sap_intf = abap_true i_interface_use_structure = interface_use_structure ). model_builder->initialize( i_element_manager = element_manager i_dynamic_read = |Z2MSE_TEST_DYNAMIC_USAGE| ). DATA(f_cut) = NEW z2mse_extract3( ). f_cut->extract( EXPORTING model_builder = model_builder element_manager = element_manager initial_elements = initial_elements i_search_up = -1 i_search_down = 2 i_exclude_found_sap_intf = abap_true IMPORTING mse_model = mse_model_act nothing_done = nothing_done_act ). DATA: equalized_harmonized_mse_act TYPE z2mse_mse_harmonize=>harmonized_mse, equalized_harmonized_mse_exp TYPE z2mse_mse_harmonize=>harmonized_mse. CLEAR equalized_harmonized_mse_act. CLEAR equalized_harmonized_mse_exp. equalized_harmonized_mse_act = z2mse_mse_harmonize=>mse_2_harmonized( mse = mse_model_act ). equalized_harmonized_mse_exp = VALUE #( ). DATA maker TYPE REF TO z2mse_mse_harmonize_maker. maker = NEW #( ). maker->to_change = equalized_harmonized_mse_exp. maker->add_custom_source_language( |SAP| ). maker->add_package( package = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_package( package = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->add_db_table( name = |Z2MSE_TEST_A| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_db_table( name = |Z2MSE_TEST_DB_B| parentpackage = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->add_class( name = |Z2MSE_TEST_CL_A| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_attribute( attribute = |Z2MSE_TEST_IF_A_00000000000000~ATTRIBUTE_A_000000000000000000| ). maker->add_method( method = |CONSTRUCTOR| at_line = 11 ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |EVENTHANDLER_A| ). maker->add_method( method = |EVENTHANDLER_A| at_line = 13 ). maker->add_method( method = |EVENT_A| at_line = 9 ). maker->add_method( method = |METHOD_A| at_line = 12 ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |EVENT_A| ). maker->usage( used_group = |Z2MSE_TEST_CL_A2| used = |METHOD_A| ). maker->access( used_group = |Z2MSE_TEST_A| used = |Z2MSE_TEST_A| ). maker->add_method( method = |Z2MSE_TEST_IF_A_00000000000000~EVENT_A_0000000000000000000000| ). * BEGIN INSERT when Interfaces are reversed IF interface_use_structure EQ abap_true. maker->usage( used_group = |Z2MSE_TEST_IF_A_00000000000000| used = |EVENT_A_0000000000000000000000| ). ENDIF. * END INSERT when Interfaces are reversed maker->add_method( method = |Z2MSE_TEST_IF_A_00000000000000~METHOD_A_000000000000000000000| ). * BEGIN INSERT when Interfaces are reversed IF interface_use_structure EQ abap_true. maker->usage( used_group = |Z2MSE_TEST_IF_A_00000000000000| used = |METHOD_A_000000000000000000000| ). ENDIF. * END INSERT when Interfaces are reversed maker->usage( used_group = |Z2MSE_TEST_CL_B2| used = |METHOD_A| ). maker->add_class( name = |Z2MSE_TEST_CL_A2| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_method( method = |METHOD_A| at_line = 8 ). maker->usage( used_group = |Z2MSE_TEST_CL_B1| used = |METHOD_B| ). maker->add_class( name = |Z2MSE_TEST_CL_A3| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_method( method = |METHOD_A| at_line = 9 ). maker->usage( used_group = |Z2MSE_TEST_CL_B1| used = |METHOD_A| ). maker->access( used = |Z2MSE_TEST_DB_B| ). maker->add_class( name = |Z2MSE_TEST_CL_B1| parentpackage = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->add_method( method = |EVENT_A| at_line = 8 ). maker->add_attribute( attribute = |ATTRIBUTE_A| at_line = 13 ). maker->add_method( method = |METHOD_A| at_line = 10 ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |CONSTRUCTOR| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |METHOD_A| ). maker->usage( used_group = |Z2MSE_TEST_IF_A_00000000000000| used = |METHOD_A_000000000000000000000| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |Z2MSE_TEST_IF_A_00000000000000~METHOD_A_000000000000000000000| ). maker->access( used = |Z2MSE_TEST_A| ). maker->access( used_group = |Z2MSE_TEST_IF_A_00000000000000| used = |ATTRIBUTE_A_000000000000000000| ). maker->access( used_group = |Z2MSE_TEST_CL_A| used = |Z2MSE_TEST_IF_A_00000000000000~ATTRIBUTE_A_000000000000000000| ). maker->add_method( method = |METHOD_B| at_line = 11 ). maker->usage( used_group = |Z2MSE_TEST_CL_B1| used = |METHOD_A| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |CONSTRUCTOR| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |METHOD_A| ). maker->add_class( name = |Z2MSE_TEST_CL_B2| parentpackage = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->add_attribute( attribute = |Z2MSE_TEST_IF_A_00000000000000~ATTRIBUTE_A_000000000000000000| ). maker->add_method( method = |METHOD_A| at_line = 12 ). maker->usage( used_group = |Z2MSE_TEST_CL_B1| used = |METHOD_A| ). maker->add_method( method = |Z2MSE_TEST_IF_A_00000000000000~EVENT_A_0000000000000000000000| ). * BEGIN INSERT when Interfaces are reversed IF interface_use_structure EQ abap_true. maker->usage( used_group = |Z2MSE_TEST_IF_A_00000000000000| used = |EVENT_A_0000000000000000000000| ). ENDIF. * END INSERT when Interfaces are reversed maker->add_method( method = |Z2MSE_TEST_IF_A_00000000000000~METHOD_A_000000000000000000000| ). * BEGIN INSERT when Interfaces are reversed IF interface_use_structure EQ abap_true. maker->usage( used_group = |Z2MSE_TEST_IF_A_00000000000000| used = |METHOD_A_000000000000000000000| ). ENDIF. * END INSERT when Interfaces are reversed maker->add_interface( name = |Z2MSE_TEST_IF_A_00000000000000| parentpackage = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->add_interface_method( method = |EVENT_A_0000000000000000000000| at_line = 7 ). * BEGIN DELETE when Interfaces are reversed IF interface_use_structure EQ abap_false. maker->usage( used_group = |Z2MSE_TEST_CL_B2| used = |Z2MSE_TEST_IF_A_00000000000000~EVENT_A_0000000000000000000000| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |Z2MSE_TEST_IF_A_00000000000000~EVENT_A_0000000000000000000000| ). ENDIF. * END DELETE when Interfaces are reversed maker->add_interface_method( method = |METHOD_A_000000000000000000000| at_line = 9 ). * BEGIN DELETE when Interfaces are reversed IF interface_use_structure EQ abap_false. maker->usage( used_group = |Z2MSE_TEST_CL_B2| used = |Z2MSE_TEST_IF_A_00000000000000~METHOD_A_000000000000000000000| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |Z2MSE_TEST_IF_A_00000000000000~METHOD_A_000000000000000000000| ). ENDIF. * END DELETE when Interfaces are reversed maker->add_interface_attribute( attribute = |ATTRIBUTE_A_000000000000000000| at_line = 5 ). maker->add_interface( name = |ZIWCI_2MSE_TEST_WDY_A| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_interface_method( method = |WD_GET_API| at_line = 17 ). maker->add_web_dynpro_component( wda_name = |Z2MSE_TEST_WDY_A| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_web_dynpro_component_view( view = |COMPONENTCONTROLLER| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |METHOD_A| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |CONSTRUCTOR| ). maker->usage( used_group = |ZIWCI_2MSE_TEST_WDY_A| used = |WD_GET_API| ). maker->access( used = |Z2MSE_TEST_A| ). maker->add_web_dynpro_component_view( view = |EMPTYVIEW| ). maker->add_web_dynpro_component_view( view = |V_MAIN| ). maker->add_web_dynpro_component_view( view = |W_MAIN| ). maker->add_program( name = |Z2MSE_TEST_PROGRAM_A| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |METHOD_A| ). maker->usage( used_group = |Z2MSE_TEST_CL_B1| used = |METHOD_A| ). maker->access( used_group = |Z2MSE_TEST_CL_B1| used = |ATTRIBUTE_A| ). maker->access( used = |Z2MSE_TEST_DB_B| ). maker->usage( used = |Z2MSE_TEST_PROGRAM_B| ). maker->usage( used = |Z2MSE_TEST_PROGRAM_C| ). maker->usage( used = |Z2MSE_TEST_INCLUDE_A| ). maker->usage( used_group = |FGR-Z2MSE_TEST_FGR_A| used = |F-Z2MSE_TEST_FUNCTION_A| ). maker->usage( used_group = |FGR-Z2MSE_TEST_FGR_B| used = |F-Z2MSE_TEST_FUNCTION_B| ). maker->add_program( name = |Z2MSE_TEST_PROGRAM_B| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_program( name = |Z2MSE_TEST_PROGRAM_C| parentpackage = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->usage( used = |Z2MSE_TEST_PROGRAM_D| ). maker->add_program( name = |Z2MSE_TEST_PROGRAM_D| parentpackage = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->add_program( name = |Z2MSE_TEST_INCLUDE_A| parentpackage = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->add_function_group( name = |Z2MSE_TEST_FGR_B| parentpackage = |Z2MSE_TEST_NO_INITIAL_SELECTN| ). maker->add_function( function = |Z2MSE_TEST_FUNCTION_B| ). maker->add_bw_transformation( bw_transformation = |BW-ODSO-Z2MSET001-CUBE-Z2MSET002| at_line = 123 ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |CONSTRUCTOR| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |METHOD_A| ). maker->add_function_group( name = |Z2MSE_TEST_FGR_A| parentpackage = |Z2MSE_TEST_INITIAL_SELECTION| ). maker->add_function( function = |Z2MSE_TEST_FUNCTION_A| ). maker->usage( used_group = |Z2MSE_TEST_CL_A| used = |METHOD_A| ). maker->usage( used_group = |FGR-Z2MSE_TEST_FGR_B| used = |F-Z2MSE_TEST_FUNCTION_B| ). maker->add_function_group_include( include = |LZ2MSE_TEST_FGR_AF01| ). maker->usage( used_group = |Z2MSE_TEST_CL_B1| used = |METHOD_A| ). equalized_harmonized_mse_exp = maker->to_change. z2mse_mse_harmonize=>equalize_harmonized( CHANGING harmonized_mse = equalized_harmonized_mse_exp ). cl_abap_unit_assert=>assert_equals( EXPORTING act = equalized_harmonized_mse_act exp = equalized_harmonized_mse_exp msg = message ). ENDDO. ENDMETHOD. METHOD z2mse_test_initial_selection2. DATA: mse_model_act TYPE z2mse_model=>lines_type. DATA: nothing_done_act TYPE abap_bool. DATA(top_packages) = VALUE z2mse_extr3_initial_elements=>ty_s_pack( ( sign = 'I' option = 'EQ' low = 'Z2MSE_TEST2_INITIAL' ) ). DATA(sub_packages_filter) = VALUE z2mse_extr3_initial_elements=>ty_s_pack( ). DATA(initial_elements) = NEW z2mse_extr3_initial_elements( ). initial_elements->select_packages( EXPORTING top_packages = top_packages sub_packages_filter = sub_packages_filter including_sub_packages = abap_true ). DATA(model_builder) = NEW z2mse_extr3_model_builder( ). DATA(element_manager) = NEW z2mse_extr3_element_manager( i_model_builder = model_builder i_exclude_found_sap_intf = abap_true i_interface_use_structure = abap_false ). model_builder->initialize( i_element_manager = element_manager i_dynamic_read = |Z2MSE_TEST_DYNAMIC_USAGE| ). DATA(f_cut) = NEW z2mse_extract3( ). f_cut->extract( EXPORTING model_builder = model_builder element_manager = element_manager initial_elements = initial_elements i_search_up = 2 "" There are elements 3 layers up, these are not to be found here i_search_down = 2 "" There are elements 3 layers down, these are not to be found here i_exclude_found_sap_intf = abap_true IMPORTING mse_model = mse_model_act nothing_done = nothing_done_act ). DATA: equalized_harmonized_mse_act TYPE z2mse_mse_harmonize=>harmonized_mse, equalized_harmonized_mse_exp TYPE z2mse_mse_harmonize=>harmonized_mse. equalized_harmonized_mse_act = z2mse_mse_harmonize=>mse_2_harmonized( mse = mse_model_act ). equalized_harmonized_mse_exp = VALUE #( ). DATA maker TYPE REF TO z2mse_mse_harmonize_maker. maker = NEW #( ). maker->to_change = equalized_harmonized_mse_exp. maker->add_custom_source_language( |SAP| ). maker->add_package( package = |Z2MSE_TEST2_INITIAL| ). maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_I_FGR_A| parentpackage = |Z2MSE_TEST2_INITIAL| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_I_FUNCTION_A| ). "" This is to be found with the down search for functions maker->add_package( package = |Z2MSE_TEST2_M1| ). maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_M1_FGR_A| parentpackage = |Z2MSE_TEST2_M1| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_M1_FUNCTION_A| ). maker->usage( EXPORTING using_group = |FGR-Z2MSE_TEST2_I_FGR_A| using = |F-Z2MSE_TEST2_I_FUNCTION_A| used_group = |FGR-Z2MSE_TEST2_M1_FGR_A| used = |F-Z2MSE_TEST2_M1_FUNCTION_A| ). "" This is now found with the up search for functions: maker->add_package( package = |Z2MSE_TEST2_P1| ). maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_P1_FGR_A| parentpackage = |Z2MSE_TEST2_P1| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_P1_FUNCTION_A| ). maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_I_FGR_A| used = |F-Z2MSE_TEST2_I_FUNCTION_A| ). "" Test downsearch for programs maker->add_program( EXPORTING name = |Z2MSE_TEST2_I_PROGRAM| parentpackage = |Z2MSE_TEST2_INITIAL| ). "" Test function used by program is found maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_M1_FGR_A| used = |F-Z2MSE_TEST2_M1_FUNCTION_A| ). "" Test class used by program is found maker->add_class( EXPORTING name = |Z2MSE_TEST2_M1_CL_A| parentpackage = |Z2MSE_TEST2_M1| ). maker->add_method( EXPORTING method = |STATIC_METHOD_A| at_line = 7 ). maker->usage( EXPORTING using_group = || using = |Z2MSE_TEST2_I_PROGRAM| used_group = |Z2MSE_TEST2_M1_CL_A| used = |STATIC_METHOD_A| ). "" Test function used by function is found in down search maker->add_package( package = |Z2MSE_TEST2_M2| ). maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_M2_FGR_A| parentpackage = |Z2MSE_TEST2_M2| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_M2_FUNCTION_A| ). maker->usage( EXPORTING using_group = |FGR-Z2MSE_TEST2_M1_FGR_A| using = |F-Z2MSE_TEST2_M1_FUNCTION_A| used_group = |FGR-Z2MSE_TEST2_M2_FGR_A| used = |F-Z2MSE_TEST2_M2_FUNCTION_A| ). "" Test function used by function is found in up search maker->add_package( package = |Z2MSE_TEST2_P2| ). maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_P2_FGR_A| parentpackage = |Z2MSE_TEST2_P2| ). maker->add_function( EXPORTING function = |Z2MSE_TEST2_P2_FUNCTION_A| ). maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_P1_FGR_A| used = |F-Z2MSE_TEST2_P1_FUNCTION_A| ). "" Test program that uses a program is found in up search maker->add_program( EXPORTING name = |Z2MSE_TEST2_P1_PROGRAM| parentpackage = |Z2MSE_TEST2_P1| ). maker->usage( EXPORTING used_group = || used = |Z2MSE_TEST2_I_PROGRAM| ). equalized_harmonized_mse_exp = maker->to_change. z2mse_mse_harmonize=>equalize_harmonized( CHANGING harmonized_mse = equalized_harmonized_mse_exp ). cl_abap_unit_assert=>assert_equals( EXPORTING act = equalized_harmonized_mse_act exp = equalized_harmonized_mse_exp msg = 'Wrong mse file' ). ENDMETHOD. METHOD _search_specific. "" search specific DATA: nothing_done_act TYPE abap_bool. DATA(initial_elements) = NEW z2mse_extr3_initial_elements( ). DATA(model_builder) = NEW z2mse_extr3_model_builder( ). DATA(element_manager) = NEW z2mse_extr3_element_manager( i_model_builder = model_builder i_exclude_found_sap_intf = abap_true i_interface_use_structure = abap_false ). model_builder->initialize( i_element_manager = element_manager i_dynamic_read = dynamic_read ). initial_elements->select_specific( EXPORTING model_builder = model_builder element_manager = element_manager i_element_type_filter = element_type_filter i_parent_name_filter = parent_name_filter i_name_filter = name_filter ). DATA(f_cut) = NEW z2mse_extract3( ). f_cut->extract( EXPORTING model_builder = model_builder element_manager = element_manager initial_elements = initial_elements i_search_up = i_search_up i_search_down = i_search_down i_exclude_found_sap_intf = abap_true IMPORTING mse_model = mse_model_act nothing_done = nothing_done_act ). model_builder->write_found_elements( EXPORTING write = abap_false IMPORTING fes = fes_act ). ENDMETHOD. METHOD _check_found_elements. "" Check found elements SORT fes_act. SORT fes_exp. cl_abap_unit_assert=>assert_equals( msg = msg exp = fes_exp act = fes_act ). ENDMETHOD. METHOD _check_harmonized_mse. "" Check harmonized mse equalized_harmonized_mse_exp = maker->to_change. equalized_harmonized_mse_act = z2mse_mse_harmonize=>mse_2_harmonized( mse = mse_model_act ). z2mse_mse_harmonize=>equalize_harmonized( CHANGING harmonized_mse = equalized_harmonized_mse_exp ). z2mse_mse_harmonize=>equalize_harmonized( CHANGING harmonized_mse = equalized_harmonized_mse_exp ). cl_abap_unit_assert=>assert_equals( EXPORTING act = equalized_harmonized_mse_act exp = equalized_harmonized_mse_exp msg = msg ). ENDMETHOD. METHOD z2mse_test_2021. DATA: mse_model_act TYPE z2mse_model=>lines_type. DATA: nothing_done_act TYPE abap_bool. DATA(top_packages) = VALUE z2mse_extr3_initial_elements=>ty_s_pack( ( sign = 'I' option = 'EQ' low = 'Z2MSE_TEST_2021' ) ). DATA(sub_packages_filter) = VALUE z2mse_extr3_initial_elements=>ty_s_pack( ). DATA(initial_elements) = NEW z2mse_extr3_initial_elements( ). initial_elements->select_packages( EXPORTING top_packages = top_packages sub_packages_filter = sub_packages_filter including_sub_packages = abap_true ). DATA(model_builder) = NEW z2mse_extr3_model_builder( ). DATA(element_manager) = NEW z2mse_extr3_element_manager( i_model_builder = model_builder i_exclude_found_sap_intf = abap_true i_interface_use_structure = abap_false ). model_builder->initialize( i_element_manager = element_manager ). DATA(f_cut) = NEW z2mse_extract3( ). f_cut->extract( EXPORTING model_builder = model_builder element_manager = element_manager initial_elements = initial_elements i_search_up = 2 i_search_down = 2 i_exclude_found_sap_intf = abap_true IMPORTING mse_model = mse_model_act nothing_done = nothing_done_act ). DATA: equalized_harmonized_mse_act TYPE z2mse_mse_harmonize=>harmonized_mse, equalized_harmonized_mse_exp TYPE z2mse_mse_harmonize=>harmonized_mse. equalized_harmonized_mse_act = z2mse_mse_harmonize=>mse_2_harmonized( mse = mse_model_act ). equalized_harmonized_mse_exp = VALUE #( ). DATA maker TYPE REF TO z2mse_mse_harmonize_maker. maker = NEW #( ). maker->to_change = equalized_harmonized_mse_exp. maker->add_custom_source_language( |SAP| ). maker->add_package( package = |Z2MSE_TEST_2021| ). * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_I_FGR_A| * parentpackage = |Z2MSE_TEST2_INITIAL| ). * * maker->add_function( EXPORTING function = |Z2MSE_TEST2_I_FUNCTION_A| ). * * "" This is to be found with the down search for functions * * maker->add_package( package = |Z2MSE_TEST2_M1| ). * * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_M1_FGR_A| * parentpackage = |Z2MSE_TEST2_M1| ). * * maker->add_function( EXPORTING function = |Z2MSE_TEST2_M1_FUNCTION_A| ). * * maker->usage( EXPORTING using_group = |FGR-Z2MSE_TEST2_I_FGR_A| * using = |F-Z2MSE_TEST2_I_FUNCTION_A| * used_group = |FGR-Z2MSE_TEST2_M1_FGR_A| * used = |F-Z2MSE_TEST2_M1_FUNCTION_A| ). * * "" This is now found with the up search for functions: * * maker->add_package( package = |Z2MSE_TEST2_P1| ). * * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_P1_FGR_A| * parentpackage = |Z2MSE_TEST2_P1| ). * * maker->add_function( EXPORTING function = |Z2MSE_TEST2_P1_FUNCTION_A| ). * * maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_I_FGR_A| * used = |F-Z2MSE_TEST2_I_FUNCTION_A| ). * * "" Test downsearch for programs * * maker->add_program( EXPORTING name = |Z2MSE_TEST2_I_PROGRAM| * parentpackage = |Z2MSE_TEST2_INITIAL| ). * * "" Test function used by program is found * * maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_M1_FGR_A| * used = |F-Z2MSE_TEST2_M1_FUNCTION_A| ). "" Test class used by program is found maker->add_class( EXPORTING name = |Z2MSE_TEST_CL_CC| parentpackage = |Z2MSE_TEST_2021| ). maker->add_method( EXPORTING method = |Z2MSE_TEST_IF_C1~METHOD2| at_line = 8 ). maker->add_class( EXPORTING name = |Z2MSE_TEST_CL_CP| parentpackage = |Z2MSE_TEST_2021| ). maker->add_method( EXPORTING method = |Z2MSE_TEST_IF_C1~METHOD2| at_line = 8 ). maker->add_interface( EXPORTING name = |Z2MSE_TEST_IF_C1| parentpackage = |Z2MSE_TEST_2021| ). maker->add_interface_method( EXPORTING method = |METHOD2| at_line = 5 ). maker->usage( EXPORTING using_group = |Z2MSE_TEST_CL_CP| using = |Z2MSE_TEST_IF_C1~METHOD2| used_group = |Z2MSE_TEST_CL_CC| used = |Z2MSE_TEST_IF_C1~METHOD2| ). maker->usage( EXPORTING using_group = |Z2MSE_TEST_IF_C1| using = |METHOD2| used_group = |Z2MSE_TEST_CL_CC| used = |Z2MSE_TEST_IF_C1~METHOD2| ). * maker->usage( EXPORTING using_group = || * using = |Z2MSE_TEST2_I_PROGRAM| * used_group = |Z2MSE_TEST2_M1_CL_A| * used = |STATIC_METHOD_A| ). * "" Test function used by function is found in down search * * maker->add_package( package = |Z2MSE_TEST2_M2| ). * * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_M2_FGR_A| * parentpackage = |Z2MSE_TEST2_M2| ). * * maker->add_function( EXPORTING function = |Z2MSE_TEST2_M2_FUNCTION_A| ). * * maker->usage( EXPORTING using_group = |FGR-Z2MSE_TEST2_M1_FGR_A| * using = |F-Z2MSE_TEST2_M1_FUNCTION_A| * used_group = |FGR-Z2MSE_TEST2_M2_FGR_A| * used = |F-Z2MSE_TEST2_M2_FUNCTION_A| ). * * "" Test function used by function is found in up search * * maker->add_package( package = |Z2MSE_TEST2_P2| ). * * maker->add_function_group( EXPORTING name = |Z2MSE_TEST2_P2_FGR_A| * parentpackage = |Z2MSE_TEST2_P2| ). * * maker->add_function( EXPORTING function = |Z2MSE_TEST2_P2_FUNCTION_A| ). * * maker->usage( EXPORTING used_group = |FGR-Z2MSE_TEST2_P1_FGR_A| * used = |F-Z2MSE_TEST2_P1_FUNCTION_A| ). * * "" Test program that uses a program is found in up search * * maker->add_program( EXPORTING name = |Z2MSE_TEST2_P1_PROGRAM| * parentpackage = |Z2MSE_TEST2_P1| ). * * maker->usage( EXPORTING used_group = || * used = |Z2MSE_TEST2_I_PROGRAM| ). equalized_harmonized_mse_exp = maker->to_change. z2mse_mse_harmonize=>equalize_harmonized( CHANGING harmonized_mse = equalized_harmonized_mse_exp ). cl_abap_unit_assert=>assert_equals( EXPORTING act = equalized_harmonized_mse_act exp = equalized_harmonized_mse_exp msg = 'Wrong mse file' ). ENDMETHOD. ENDCLASS. ",14647,True,3656.346190294657,median "/* Clock.ino Demonstrates a clock-like display with a very huge font. Also shows usage of u8x8_u8toa(). 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 /* U8glib 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_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_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_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_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_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); //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_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_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_SSD1317_96X96_1_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1317_96X96_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_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //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_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_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_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_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_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_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_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_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=*/ 17, /*cs=*/ 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=*/ 17, /*cs=*/ 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=*/ 17, /*cs=*/ 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_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=*/ 16); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //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_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 // 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(); } uint8_t m = 24; void loop(void) { char m_str[3]; strcpy(m_str, u8x8_u8toa(m, 2)); /* convert m to a string with two digits */ u8g2.firstPage(); do { u8g2.setFont(u8g2_font_logisoso62_tn); u8g2.drawStr(0,63,""9""); u8g2.drawStr(33,63,"":""); u8g2.drawStr(50,63,m_str); } while ( u8g2.nextPage() ); delay(1000); m++; if ( m == 60 ) m = 0; } ",12514,True,3860.073826442393,median "#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include ""catch2/catch.hpp"" #include ""jg/dense_hash_map.hpp"" #include ""jg/details/type_traits.hpp"" #include #include #include #include namespace { struct increase_counter_on_copy_or_move { increase_counter_on_copy_or_move(std::size_t* counter_ptr) : counter_ptr{counter_ptr} {} increase_counter_on_copy_or_move(const increase_counter_on_copy_or_move& other) : counter_ptr(other.counter_ptr) { ++(*counter_ptr); } increase_counter_on_copy_or_move(increase_counter_on_copy_or_move&& other) : counter_ptr(std::move(other.counter_ptr)) { ++(*counter_ptr); } auto operator=(const increase_counter_on_copy_or_move& other) -> increase_counter_on_copy_or_move& { counter_ptr = other.counter_ptr; ++(*counter_ptr); return *this; } auto operator=(increase_counter_on_copy_or_move&& other) -> increase_counter_on_copy_or_move& { counter_ptr = std::move(other.counter_ptr); ++(*counter_ptr); return *this; } std::size_t* counter_ptr = nullptr; }; auto operator==(const increase_counter_on_copy_or_move&, const increase_counter_on_copy_or_move&) -> bool { return true; } struct collision_hasher { template auto operator()(T&&) const noexcept -> std::size_t { return 0; } }; template struct named_allocator { using value_type = T; using propagate_on_container_swap = propagateSwap; named_allocator() = default; named_allocator(std::string name) : name(std::move(name)) {} template constexpr named_allocator(const named_allocator& other) noexcept : name(other.name) {} auto allocate(std::size_t n) -> T* { return std::allocator{}.allocate(n); } void deallocate(T* p, std::size_t s) noexcept { std::allocator{}.deallocate(p, s); } std::string name; }; template auto operator==( const named_allocator& lhs, const named_allocator& rhs) -> bool { return lhs.name == rhs.name; } template auto operator!=( const named_allocator& lhs, const named_allocator& rhs) -> bool { return lhs.name != rhs.name; } struct nested_string { std::string value; }; struct string_hash { using transparent_key_equal = std::equal_to<>; using hash_type = std::hash; auto operator()(const std::string& s) const -> size_t { return hash_type{}(s); } auto operator()(const nested_string& s) const -> size_t { return hash_type{}(s.value); } }; auto operator==(const std::string& s, const nested_string& ns) -> bool { return s == ns.value; } template struct is_valid_container { private: template constexpr auto test_validity(int /* unused */) -> decltype(std::declval()(std::declval()...), std::true_type()) { return std::true_type(); } template constexpr auto test_validity(...) -> std::false_type { return std::false_type(); } public: template constexpr auto operator()(Params&&...) { return test_validity(int()); } }; template constexpr auto is_valid(UnnamedType&&) { return is_valid_container(); } struct counting_pmr_resource : std::pmr::memory_resource { counting_pmr_resource(int* alloc_counter) : alloc_counter(alloc_counter) {} auto do_allocate(std::size_t bytes, std::size_t alignment) -> void* override { ++(*alloc_counter); return std::pmr::get_default_resource()->allocate(bytes, alignment); } void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { std::pmr::get_default_resource()->deallocate(p, bytes, alignment); } auto do_is_equal(const std::pmr::memory_resource&) const noexcept -> bool override { return true; } int* alloc_counter = nullptr; }; } // namespace namespace std { template <> struct hash { auto operator()(const increase_counter_on_copy_or_move&) const noexcept -> std::size_t { return 0; } }; } // namespace std TEST_CASE(""member types"") { jg::dense_hash_map m; REQUIRE(std::is_same_v); REQUIRE(std::is_same_v); REQUIRE(std::is_same_v>); REQUIRE(sizeof(decltype(m)::size_type) > 1); REQUIRE(sizeof(decltype(m)::difference_type) > 1); REQUIRE(std::is_same_v>); REQUIRE(std::is_same_v>); REQUIRE(std::is_same_v< decltype(m)::allocator_type, std::allocator>>); REQUIRE(std::is_same_v&>); REQUIRE(std::is_same_v&>); REQUIRE(std::is_pointer_v); REQUIRE(std::is_pointer_v); REQUIRE(std::is_same_v); REQUIRE(std::is_same_v); REQUIRE(std::is_same_v); REQUIRE(std::is_same_v); } TEST_CASE(""constructors"") { jg::dense_hash_map m = {{""pikachu"", 40}, {""raichu"", 43}}; SECTION(""empty"") { REQUIRE(std::is_nothrow_default_constructible_v); jg::dense_hash_map m1; REQUIRE(m1.size() == 0); REQUIRE(m1.bucket_count() == 8); } SECTION(""bucket_count / hash / equal / alloc"") { jg::dense_hash_map m1{32}; REQUIRE(m1.size() == 0); REQUIRE(m1.bucket_count() == 32); jg::dense_hash_map m2{32, std::hash{}}; REQUIRE(m2.size() == 0); REQUIRE(m2.bucket_count() == 32); jg::dense_hash_map m3{6, std::hash{}, std::equal_to{}}; REQUIRE(m3.size() == 0); REQUIRE(m3.bucket_count() == 8); jg::dense_hash_map m4{ 0, std::hash{}, std::equal_to{}, std::allocator>{}}; REQUIRE(m4.size() == 0); REQUIRE(m4.bucket_count() == 8); } SECTION(""bucket_count / alloc"") { jg::dense_hash_map m1{ 64, std::allocator>{}}; REQUIRE(m1.size() == 0); REQUIRE(m1.bucket_count() == 64); } SECTION(""bucket_count / hash / alloc"") { jg::dense_hash_map m1{ 9, std::hash{}, std::allocator>{}}; REQUIRE(m1.size() == 0); REQUIRE(m1.bucket_count() == 16); } SECTION(""alloc"") { jg::dense_hash_map m1{ std::allocator>{}}; REQUIRE(m1.size() == 0); REQUIRE(m1.bucket_count() == 8); } SECTION(""input iterator / bucket_count / hash / equal / alloc"") { jg::dense_hash_map m1{m.begin(), m.end()}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""pikachu"")); REQUIRE(m1[""pikachu""] == 40); jg::dense_hash_map m2{m.begin(), m.end(), 32}; REQUIRE(m2.size() == 2); REQUIRE(m2.bucket_count() == 32); REQUIRE(m2.contains(""pikachu"")); REQUIRE(m2[""pikachu""] == 40); jg::dense_hash_map m3{m.begin(), m.end(), 32, std::hash{}}; REQUIRE(m3.size() == 2); REQUIRE(m3.bucket_count() == 32); REQUIRE(m3.contains(""raichu"")); REQUIRE(m3[""raichu""] == 43); jg::dense_hash_map m4{m.begin(), m.end(), 6, std::hash{}, std::equal_to{}}; REQUIRE(m4.size() == 2); REQUIRE(m4.bucket_count() == 8); REQUIRE(m4.contains(""pikachu"")); REQUIRE(m4[""pikachu""] == 40); jg::dense_hash_map m5{ m.begin(), m.end(), 0, std::hash{}, std::equal_to{}, std::allocator>{}}; REQUIRE(m5.size() == 2); REQUIRE(m5.bucket_count() == 8); REQUIRE(m5.contains(""pikachu"")); REQUIRE(m5[""pikachu""] == 40); } SECTION(""input iterator / alloc"") { jg::dense_hash_map m1{ m.begin(), m.end(), std::allocator>{}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""raichu"")); REQUIRE(m1[""raichu""] == 43); } SECTION(""input iterator / bucket_count / alloc"") { jg::dense_hash_map m1{ m.begin(), m.end(), 8, std::allocator>{}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""raichu"")); REQUIRE(m1[""raichu""] == 43); } SECTION(""input iterator / bucket_count / hash / alloc"") { jg::dense_hash_map m1{ m.begin(), m.end(), 8, std::hash{}, std::allocator>{}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""pikachu"")); REQUIRE(m1[""pikachu""] == 40); } SECTION(""copy constructor"") { jg::dense_hash_map m1{m}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""raichu"")); REQUIRE(m1[""raichu""] == 43); REQUIRE(m.size() == 2); REQUIRE(m.bucket_count() == 8); REQUIRE(m.contains(""raichu"")); REQUIRE(m[""raichu""] == 43); } SECTION(""copy constructor / alloc"") { jg::dense_hash_map m1{ m, std::allocator>{}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""raichu"")); REQUIRE(m1[""raichu""] == 43); } SECTION(""move constructor"") { jg::dense_hash_map m1{std::move(m)}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""raichu"")); REQUIRE(m1[""raichu""] == 43); REQUIRE(m.size() == 0); REQUIRE(m.bucket_count() == 0); // Moved dense_hash_map usable after clear. m.clear(); REQUIRE(m.bucket_count() == 8); REQUIRE(m.size() == 0); m[""spiderman""] = 43; REQUIRE(m.contains(""spiderman"")); } SECTION(""move constructor alloc"") { jg::dense_hash_map m1{ std::move(m), std::allocator>{}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""raichu"")); REQUIRE(m1[""raichu""] == 43); REQUIRE(m.size() == 0); REQUIRE(m.bucket_count() == 0); } SECTION(""initializer_list / bucket_count / hash / equal / alloc"") { jg::dense_hash_map m1{{{""pikachu"", 40}, {""raichu"", 43}}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""pikachu"")); REQUIRE(m1[""pikachu""] == 40); jg::dense_hash_map m2{{{""pikachu"", 40}, {""raichu"", 43}}, 32}; REQUIRE(m2.size() == 2); REQUIRE(m2.bucket_count() == 32); REQUIRE(m2.contains(""pikachu"")); REQUIRE(m2[""pikachu""] == 40); jg::dense_hash_map m3{ {{""pikachu"", 40}, {""raichu"", 43}}, 32, std::hash{}}; REQUIRE(m3.size() == 2); REQUIRE(m3.bucket_count() == 32); REQUIRE(m3.contains(""raichu"")); REQUIRE(m3[""raichu""] == 43); jg::dense_hash_map m4{{{""pikachu"", 40}, {""raichu"", 43}}, 6, std::hash{}, std::equal_to{}}; REQUIRE(m4.size() == 2); REQUIRE(m4.bucket_count() == 8); REQUIRE(m4.contains(""pikachu"")); REQUIRE(m4[""pikachu""] == 40); jg::dense_hash_map m5{ {{""pikachu"", 40}, {""raichu"", 43}}, 0, std::hash{}, std::equal_to{}, std::allocator>{}}; REQUIRE(m5.size() == 2); REQUIRE(m5.bucket_count() == 8); REQUIRE(m5.contains(""pikachu"")); REQUIRE(m5[""pikachu""] == 40); } SECTION(""initializer_list / alloc"") { jg::dense_hash_map m1{ {{""pikachu"", 40}, {""raichu"", 43}}, std::allocator>{}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""raichu"")); REQUIRE(m1[""raichu""] == 43); } SECTION(""initializer_list / bucket_count / alloc"") { jg::dense_hash_map m1{ {{""pikachu"", 40}, {""raichu"", 43}}, 8, std::allocator>{}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""raichu"")); REQUIRE(m1[""raichu""] == 43); } SECTION(""initializer_list / bucket_count / hash / alloc"") { jg::dense_hash_map m1{ {{""pikachu"", 40}, {""raichu"", 43}}, 8, std::hash{}, std::allocator>{}}; REQUIRE(m1.size() == 2); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.contains(""pikachu"")); REQUIRE(m1[""pikachu""] == 40); } } TEST_CASE(""assignment operator"") { jg::dense_hash_map m1 = {{""pikachu"", 40}, {""raichu"", 43}}; jg::dense_hash_map m2 = {{""picsou"", 13}}; SECTION(""copy"") { m2 = m1; REQUIRE(m2.size() == 2); REQUIRE(m2.bucket_count() == 8); REQUIRE(m2.contains(""pikachu"")); REQUIRE(m2[""pikachu""] == 40); REQUIRE(!m2.contains(""picsou"")); } SECTION(""move"") { REQUIRE(std::is_nothrow_move_assignable_v); m2 = std::move(m1); REQUIRE(m2.size() == 2); REQUIRE(m2.bucket_count() == 8); REQUIRE(m2.contains(""pikachu"")); REQUIRE(m2[""pikachu""] == 40); REQUIRE(!m2.contains(""picsou"")); REQUIRE(m1.size() == 0); REQUIRE(m1.bucket_count() == 0); // Moved dense_hash_map usable after clear. m1.clear(); REQUIRE(m1.bucket_count() == 8); REQUIRE(m1.size() == 0); m1[""spiderman""] = 43; REQUIRE(m1.contains(""spiderman"")); } SECTION(""assign initializer_list"") { m2 = {{""pikachu"", 40}, {""raichu"", 43}}; REQUIRE(m2.size() == 2); REQUIRE(m2.bucket_count() == 8); REQUIRE(m2.contains(""pikachu"")); REQUIRE(m2[""pikachu""] == 40); REQUIRE(!m2.contains(""picsou"")); } } TEST_CASE(""iterator"") { jg::dense_hash_map m = {{""pierre"", 1}, {""paul"", 2}, {""jacques"", 3}}; std::vector> expected = { {""pierre"", 1}, {""paul"", 2}, {""jacques"", 3}}; SECTION(""begin/end"") { static_assert(std::is_same_vsecond)), int&>); REQUIRE(std::equal(expected.begin(), expected.end(), m.begin(), m.end())); } SECTION(""const begin/end"") { const auto& m2 = m; static_assert(std::is_same_vsecond)), const int&>); REQUIRE(std::equal(expected.begin(), expected.end(), m2.begin(), m2.end())); } SECTION(""cbegin/cend"") { static_assert(std::is_same_vsecond)), const int&>); REQUIRE(std::equal(expected.cbegin(), expected.cend(), m.cbegin(), m.cend())); } } TEST_CASE(""clear"") { jg::dense_hash_map m; SECTION(""empty"") { m.clear(); REQUIRE(m.empty()); REQUIRE(m.size() == 0); REQUIRE(m.bucket_count() == 8u); REQUIRE(m.load_factor() == 0.0f); } SECTION(""not_empty"") { m.try_emplace(""sponge bob"", 10); m.try_emplace(""sponge bob2"", 10); REQUIRE(m.size() == 2); m.clear(); REQUIRE(m.empty()); REQUIRE(m.size() == 0); REQUIRE(m.bucket_count() == 8u); REQUIRE(m.load_factor() == 0.0f); } SECTION(""no_except"") { REQUIRE(noexcept(m.clear())); } } template using has_insert = decltype(std::declval().insert(std::declval())); template using has_insert_hint = decltype(std::declval().insert(std::declval().begin(), std::declval())); TEST_CASE(""insert"") { jg::dense_hash_map m; SECTION(""insert - lvalue"") { auto pair = std::pair(std::string(""test""), 42); const auto& [it, result] = m.insert(pair); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""insert - const lvalue"") { const auto pair = std::pair(std::string(""test""), 42); const auto& [it, result] = m.insert(pair); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""insert - rvalue"") { const auto& [it, result] = m.insert(std::pair(std::string(""test""), 42)); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""insert - conversion"") { auto pair = std::pair(""test"", 42); const auto& [it, result] = m.insert(pair); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""insert - conversion is SFINAE friendly"") { REQUIRE_FALSE(jg::details::is_detected< has_insert, jg::dense_hash_map, int>, std::pair>::value); } SECTION(""insert - lvalue - hint"") { auto pair = std::pair(std::string(""test""), 42); const auto& it = m.insert(m.begin(), pair); REQUIRE(it != m.end()); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""insert - const lvalue - hint"") { const auto pair = std::pair(std::string(""test""), 42); const auto& it = m.insert(m.begin(), pair); REQUIRE(it != m.end()); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""insert - rvalue - hint"") { const auto& it = m.insert(m.begin(), std::pair(std::string(""test""), 42)); REQUIRE(it != m.end()); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""insert - conversion - hint"") { auto pair = std::pair(""test"", 42); const auto& it = m.insert(m.begin(), pair); REQUIRE(it != m.end()); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""insert - conversion is SFINAE friendly - hint"") { REQUIRE_FALSE(jg::details::is_detected< has_insert_hint, jg::dense_hash_map, int>, std::pair>::value); } SECTION(""insert - iterator"") { std::vector> v{{""test"", 42}, {""test2"", 1337}}; m.insert(v.begin(), v.end()); REQUIRE(m.size() == 2); auto it = m.find(""test""); REQUIRE(it != m.end()); REQUIRE(it->second == 42); it = m.find(""test2""); REQUIRE(it != m.end()); REQUIRE(it->second == 1337); } SECTION(""insert - initializer_list"") { std::initializer_list> l{{""test"", 42}, {""test2"", 1337}}; m.insert(l); REQUIRE(m.size() == 2); auto it = m.find(""test""); REQUIRE(it != m.end()); REQUIRE(it->second == 42); it = m.find(""test2""); REQUIRE(it != m.end()); REQUIRE(it->second == 1337); } } TEST_CASE(""insert_or_assign"") { jg::dense_hash_map m1; jg::dense_hash_map, int> m2; SECTION(""l-value key"") { const auto& [it, result] = m1.insert_or_assign(""test"", 42); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); const auto& [it2, result2] = m1.insert_or_assign(""test"", 1337); REQUIRE_FALSE(result2); REQUIRE(it2 == it); REQUIRE(it2->first == ""test""); REQUIRE(it2->second == 1337); } SECTION(""r-value key"") { const auto& [it, result] = m2.insert_or_assign(nullptr, 42); REQUIRE(result); REQUIRE(it->first == nullptr); REQUIRE(it->second == 42); std::unique_ptr p = nullptr; const auto& [it2, result2] = m2.insert_or_assign(std::move(p), 1337); REQUIRE_FALSE(result2); REQUIRE(it2 == it); REQUIRE(it2->first == nullptr); REQUIRE(it2->second == 1337); } SECTION(""l-value key - hint"") { auto it = m1.insert_or_assign(m1.begin(), ""test"", 42); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); auto it2 = m1.insert_or_assign(m1.begin(), ""test"", 1337); REQUIRE(it == it); REQUIRE(it2->first == ""test""); REQUIRE(it2->second == 1337); } SECTION(""r-value key - hint"") { auto it = m2.insert_or_assign(m2.begin(), nullptr, 42); REQUIRE(it->first == nullptr); REQUIRE(it->second == 42); std::unique_ptr p = nullptr; auto it2 = m2.insert_or_assign(m2.begin(), std::move(p), 1337); REQUIRE(it2 == it); REQUIRE(it2->first == nullptr); REQUIRE(it2->second == 1337); } } TEST_CASE(""emplace"", ""[emplace]"") { jg::dense_hash_map m; SECTION(""default"") { const auto& [it, result] = m.emplace(); REQUIRE(result); REQUIRE(it->first == std::string()); REQUIRE(it->second == int{}); REQUIRE(m.size() == 1); } SECTION(""once - rvalues"") { const auto& [it, result] = m.emplace(""test"", 42); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""once - l-values"") { std::string key = ""test""; int value = 42; const auto& [it, result] = m.emplace(key, value); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""once - const l-values"") { const std::string key = ""test""; const int value = 42; const auto& [it, result] = m.emplace(key, value); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""pair - lvalue"") { auto pair = std::pair(std::string(""test""), 42); const auto& [it, result] = m.emplace(pair); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""pair - const lvalue"") { const auto pair = std::pair(std::string(""test""), 42); const auto& [it, result] = m.emplace(pair); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""pair - rvalue"") { const auto& [it, result] = m.emplace(std::pair(std::string(""test""), 42)); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""conversion"") { const auto& [it, result] = m.emplace(""test"", 42); // key: const char* ==> std::string REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""conversion pair"") { const auto& [it, result] = m.emplace(std::pair(""test"", 42)); // key: const char* ==> std::string REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""piecewise_construct"") { const auto& [it, result] = m.emplace( std::piecewise_construct, std::forward_as_tuple(""test""), std::forward_as_tuple(42)); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } } TEST_CASE(""emplace key rvalue"") { jg::dense_hash_map, int> m; SECTION(""Successfull emplace"") { auto ptr = std::make_unique(37); const auto& [it, result] = m.emplace(std::move(ptr), 42); REQUIRE(result); REQUIRE(*it->first == 37); REQUIRE(it->second == 42); REQUIRE(ptr == nullptr); } } TEST_CASE(""emplace twice"", ""[emplace]"") { jg::dense_hash_map m; SECTION(""twice same"") { const auto& [it, result] = m.emplace(""test"", 42); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); const auto& [it2, result2] = m.emplace(""test"", 42); REQUIRE_FALSE(result2); REQUIRE(it == it2); REQUIRE(it2->first == ""test""); REQUIRE(it2->second == 42); REQUIRE(m.size() == 1); } SECTION(""twice different"") { const auto& [it, result] = m.emplace(""test"", 42); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); const auto& [it2, result2] = m.emplace(""test2"", 1337); REQUIRE(result2); REQUIRE(it != it2); REQUIRE(it2->first == ""test2""); REQUIRE(it2->second == 1337); REQUIRE(m.size() == 2); } } TEST_CASE(""emplace optimization"", ""[emplace]"") { std::size_t counter{}; jg::dense_hash_map m; const auto& [it, result] = m.emplace(&counter, 42); REQUIRE(result); REQUIRE(counter > 0); auto counter_after_insertion = counter; SECTION(""key not copied if not inserted"") { increase_counter_on_copy_or_move key{&counter}; m.emplace(key, 42); REQUIRE(counter_after_insertion == counter); } SECTION(""pair's key copied moved if not inserted"") { increase_counter_on_copy_or_move key{&counter}; std::pair p(key, 42); m.emplace(p); REQUIRE(counter_after_insertion == counter); } SECTION(""key not moved if not inserted"") { increase_counter_on_copy_or_move key{&counter}; m.emplace(std::move(key), 42); REQUIRE(counter_after_insertion == counter); } SECTION(""pair's key not moved if not inserted"") { std::pair p(&counter, 42); m.emplace(std::move(p)); REQUIRE(counter_after_insertion == counter); } } TEST_CASE(""emplace_hint"") { jg::dense_hash_map m; SECTION(""one"") { const auto& it = m.emplace_hint(m.begin(), ""bob"", 666); REQUIRE(it != m.end()); REQUIRE(it->first == ""bob""); REQUIRE(it->second == 666); REQUIRE(m.size() == 1); } SECTION(""twice"") { const auto& it1 = m.emplace_hint(m.begin(), ""bob"", 666); const auto& it2 = m.emplace_hint(m.begin(), ""bob"", 444); REQUIRE(it1 == it2); REQUIRE(it2->first == ""bob""); REQUIRE(it2->second == 666); REQUIRE(m.size() == 1); } } TEST_CASE(""try emplace"", ""[try_emplace]"") { jg::dense_hash_map m; SECTION(""rvalues"") { const auto& [it, result] = m.try_emplace(""test"", 42); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""l-values"") { std::string key = ""test""; int value = 42; const auto& [it, result] = m.try_emplace(key, value); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } SECTION(""const l-values"") { const std::string key = ""test""; const int value = 42; const auto& [it, result] = m.try_emplace(key, value); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); REQUIRE(m.size() == 1); } } TEST_CASE(""try_emplace twice"", ""[try_emplace]"") { jg::dense_hash_map m; SECTION(""twice same"") { const auto& [it, result] = m.try_emplace(""test"", 42); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); const auto& [it2, result2] = m.try_emplace(""test"", 42); REQUIRE_FALSE(result2); REQUIRE(it == it2); REQUIRE(it2->first == ""test""); REQUIRE(it2->second == 42); REQUIRE(m.size() == 1); } SECTION(""twice different"") { const auto& [it, result] = m.try_emplace(""test"", 42); REQUIRE(result); REQUIRE(it->first == ""test""); REQUIRE(it->second == 42); const auto& [it2, result2] = m.try_emplace(""test2"", 1337); REQUIRE(result2); REQUIRE(it != it2); REQUIRE(it2->first == ""test2""); REQUIRE(it2->second == 1337); REQUIRE(m.size() == 2); } } TEST_CASE(""try_emplace effects guarantees"", ""[try_emplace]"") { std::size_t counter{}; jg::dense_hash_map m; const auto& [it, result] = m.emplace(&counter, 42); REQUIRE(result); REQUIRE(counter > 0); auto counter_after_insertion = counter; SECTION(""key not copied if not inserted"") { increase_counter_on_copy_or_move key{&counter}; m.try_emplace(key, 42); REQUIRE(counter_after_insertion == counter); } SECTION(""key not moved if not inserted"") { increase_counter_on_copy_or_move key{&counter}; m.try_emplace(std::move(key), 42); REQUIRE(counter_after_insertion == counter); } } TEST_CASE(""erase iterator"", ""[erase]"") { jg::dense_hash_map m; const auto& [useless1, result1] = m.emplace(""bob"", 42); const auto& [useless2, result2] = m.emplace(""jacky"", 42); const auto& [useless3, result3] = m.emplace(""snoop"", 42); REQUIRE(result1); REQUIRE(result2); REQUIRE(result3); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") != m.end()); REQUIRE(m.size() == 3); SECTION(""using first iterator"") { auto new_it = m.erase(m.begin()); REQUIRE(new_it != m.end()); REQUIRE(m.size() == 2); REQUIRE(new_it->first == ""snoop""); REQUIRE(m.find(""bob"") == m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") != m.end()); } SECTION(""using middle iterator"") { auto it = m.find(""jacky""); REQUIRE(it != m.end()); auto new_it = m.erase(it); REQUIRE(new_it != m.end()); REQUIRE(m.size() == 2); REQUIRE(new_it->first == ""snoop""); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") == m.end()); REQUIRE(m.find(""snoop"") != m.end()); } SECTION(""using last iterator"") { auto new_it = m.erase(std::prev(m.end())); REQUIRE(new_it == m.end()); REQUIRE(m.size() == 2); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") == m.end()); } } TEST_CASE(""erase key"", ""[erase]"") { jg::dense_hash_map m; const auto& [useless1, result1] = m.emplace(""bob"", 42); const auto& [useless2, result2] = m.emplace(""jacky"", 42); const auto& [useless3, result3] = m.emplace(""snoop"", 42); REQUIRE(result1); REQUIRE(result2); REQUIRE(result3); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") != m.end()); REQUIRE(m.size() == 3); SECTION(""success"") { REQUIRE(m.erase(""bob"") > 0); REQUIRE(m.size() == 2); REQUIRE(m.find(""bob"") == m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") != m.end()); } SECTION(""failure"") { REQUIRE(m.erase(""bobby"") == 0); REQUIRE(m.size() == 3); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") != m.end()); } } TEST_CASE(""erase with collisions"", ""[erase]"") { jg::dense_hash_map m; const auto& [useless1, result1] = m.emplace(""bob"", 42); const auto& [useless2, result2] = m.emplace(""jacky"", 42); const auto& [useless3, result3] = m.emplace(""snoop"", 42); REQUIRE(result1); REQUIRE(result2); REQUIRE(result3); auto bob_it = m.find(""bob""); auto jacky_it = m.find(""jacky""); auto snoop_it = m.find(""snoop""); REQUIRE(bob_it != m.end()); REQUIRE(jacky_it != m.end()); REQUIRE(snoop_it != m.end()); REQUIRE(m.size() == 3); SECTION(""remove first in bucket"") { REQUIRE(m.erase(""snoop"") > 0); REQUIRE(m.size() == 2); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") == m.end()); } SECTION(""remove mid in bucket"") { REQUIRE(m.erase(""jacky"") > 0); REQUIRE(m.size() == 2); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") == m.end()); REQUIRE(m.find(""snoop"") != m.end()); } SECTION(""remove last in bucket"") { REQUIRE(m.erase(""bob"") > 0); REQUIRE(m.size() == 2); REQUIRE(m.find(""bob"") == m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") != m.end()); } } TEST_CASE(""range erase"") { jg::dense_hash_map m; const auto& [useless1, result1] = m.emplace(""bob"", 42); const auto& [useless2, result2] = m.emplace(""jacky"", 42); const auto& [useless3, result3] = m.emplace(""snoop"", 42); REQUIRE(result1); REQUIRE(result2); REQUIRE(result3); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") != m.end()); REQUIRE(m.size() == 3); SECTION(""all"") { auto it = m.erase(m.begin(), m.end()); REQUIRE(it == m.end()); REQUIRE(m.size() == 0); REQUIRE(m.find(""bob"") == m.end()); REQUIRE(m.find(""jacky"") == m.end()); REQUIRE(m.find(""snoop"") == m.end()); } SECTION(""two first"") { auto it = m.erase(m.begin(), std::prev(m.end())); REQUIRE(it->first == ""snoop""); REQUIRE(m.size() == 1); REQUIRE(m.find(""bob"") == m.end()); REQUIRE(m.find(""jacky"") == m.end()); REQUIRE(m.find(""snoop"") != m.end()); } SECTION(""two last"") { auto it = m.erase(std::next(m.begin()), m.end()); REQUIRE(it == m.end()); REQUIRE(m.size() == 1); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") == m.end()); REQUIRE(m.find(""snoop"") == m.end()); } SECTION(""none"") { auto it = m.erase(m.begin(), m.begin()); REQUIRE(it == m.begin()); REQUIRE(m.size() == 3); REQUIRE(m.find(""bob"") != m.end()); REQUIRE(m.find(""jacky"") != m.end()); REQUIRE(m.find(""snoop"") != m.end()); } } TEST_CASE(""rehash"") { jg::dense_hash_map m; SECTION(""by insertion"") { const int amount = 1000; const auto old_bucket_count = m.bucket_count(); for (int i = 0; i < amount; ++i) { m.emplace(""test"" + std::to_string(i), i); } REQUIRE(m.size() == amount); REQUIRE(m.bucket_count() != old_bucket_count); REQUIRE(m.bucket_count() >= std::ceil(1000 / m.max_load_factor())); for (int i = 0; i < amount; ++i) { const std::string key = ""test"" + std::to_string(i); auto it = m.find(key); REQUIRE(it != m.end()); REQUIRE(it->first == key); REQUIRE(it->second == i); } } SECTION(""rehash member function"") { m.try_emplace(""tarzan"", 42); m.try_emplace(""spirou"", 1337); const auto old_load_factor = m.load_factor(); m.rehash(1000); REQUIRE(m.load_factor() < old_load_factor); REQUIRE(m.bucket_count() == 1024); auto it = m.find(""tarzan""); REQUIRE(it != m.end()); REQUIRE(it->first == ""tarzan""); REQUIRE(it->second == 42); it = m.find(""spirou""); REQUIRE(it != m.end()); REQUIRE(it->first == ""spirou""); REQUIRE(it->second == 1337); } SECTION(""reserve"") { m.try_emplace(""tarzan"", 42); m.try_emplace(""spirou"", 1337); const auto old_load_factor = m.load_factor(); m.reserve(1000); REQUIRE(m.load_factor() < old_load_factor); REQUIRE(m.bucket_count() >= std::ceil(1000 / m.max_load_factor())); auto it = m.find(""tarzan""); REQUIRE(it != m.end()); REQUIRE(it->first == ""tarzan""); REQUIRE(it->second == 42); it = m.find(""spirou""); REQUIRE(it != m.end()); REQUIRE(it->first == ""spirou""); REQUIRE(it->second == 1337); } SECTION(""max_load_factor"") { m.try_emplace(""tarzan"", 42); m.try_emplace(""spirou"", 1337); REQUIRE(m.bucket_count() == 8); REQUIRE(m.load_factor() == 0.25); // We have 2/8 == 0.25 load factor. m.max_load_factor(0.2f); // So this should trigger a regrowth. REQUIRE(m.max_load_factor() == 0.2f); REQUIRE(m.bucket_count() == 16); // Doubling the size will work. auto it = m.find(""tarzan""); REQUIRE(it != m.end()); REQUIRE(it->first == ""tarzan""); REQUIRE(it->second == 42); it = m.find(""spirou""); REQUIRE(it != m.end()); REQUIRE(it->first == ""spirou""); REQUIRE(it->second == 1337); } } TEST_CASE(""swap"", ""[swap]"") { jg::dense_hash_map m1 = {{""batman"", 42}, {""robin"", 666}}; jg::dense_hash_map m2 = {{""superman"", 64}}; SECTION(""member"") { m1.swap(m2); REQUIRE(m1.size() == 1); REQUIRE(m2.size() == 2); auto it = m1.find(""superman""); REQUIRE(it != m1.end()); REQUIRE(it->first == ""superman""); REQUIRE(it->second == 64); it = m1.find(""batman""); REQUIRE(it == m1.end()); it = m2.find(""robin""); REQUIRE(it != m2.end()); REQUIRE(it->first == ""robin""); REQUIRE(it->second == 666); } SECTION(""std::swap"") { REQUIRE(std::is_nothrow_swappable_v); std::swap(m1, m2); REQUIRE(m1.size() == 1); REQUIRE(m2.size() == 2); auto it = m1.find(""superman""); REQUIRE(it != m1.end()); REQUIRE(it->first == ""superman""); REQUIRE(it->second == 64); it = m1.find(""batman""); REQUIRE(it == m1.end()); it = m2.find(""robin""); REQUIRE(it != m2.end()); REQUIRE(it->first == ""robin""); REQUIRE(it->second == 666); } } TEST_CASE(""swap allocator"", ""[swap]"") { SECTION(""no swap"") { using alloc = named_allocator; jg::dense_hash_map, std::equal_to, alloc> m1{alloc{""a1""}}; jg::dense_hash_map, std::equal_to, alloc> m2{alloc{""a2""}}; REQUIRE(m1.get_allocator().name == ""a1""); REQUIRE(m2.get_allocator().name == ""a2""); std::swap(m1, m2); REQUIRE(m1.get_allocator().name == ""a1""); REQUIRE(m2.get_allocator().name == ""a2""); } SECTION(""swap"") { using alloc = named_allocator; jg::dense_hash_map, std::equal_to, alloc> m1{alloc{""a1""}}; jg::dense_hash_map, std::equal_to, alloc> m2{alloc{""a2""}}; REQUIRE(m1.get_allocator().name == ""a1""); REQUIRE(m2.get_allocator().name == ""a2""); std::swap(m1, m2); REQUIRE(m1.get_allocator().name == ""a2""); REQUIRE(m2.get_allocator().name == ""a1""); } } TEST_CASE(""at"") { jg::dense_hash_map m1 = {{""batman"", 42}, {""robin"", 666}}; SECTION(""non-const"") { static_assert(std::is_same_v); REQUIRE(m1.at(""batman"") == 42); m1.at(""batman"") = 1337; REQUIRE(m1.at(""batman"") == 1337); #if !JG_NO_EXCEPTION REQUIRE_THROWS(m1.at(""winnie"")); #endif } SECTION(""const"") { const auto& m2 = m1; static_assert(std::is_same_v); REQUIRE(m2.at(""batman"") == 42); #if !JG_NO_EXCEPTION REQUIRE_THROWS(m1.at(""the pooh"")); #endif } } TEST_CASE(""subscript operator"") { jg::dense_hash_map m1 = {}; SECTION(""copy-key"") { std::string key = ""RPC""; m1[key] = 4; REQUIRE(m1.size() == 1); auto it = m1.find(""RPC""); REQUIRE(it != m1.end()); REQUIRE(it->second == 4); } SECTION(""move-key"") { std::string key = ""PRC""; m1[std::move(key)] = 748; REQUIRE(m1.size() == 1); auto it = m1.find(""PRC""); REQUIRE(it != m1.end()); REQUIRE(it->second == 748); REQUIRE(key.empty()); } SECTION(""twice"") { m1[""CRP""] = 1; REQUIRE(m1.size() == 1); auto it = m1.find(""CRP""); REQUIRE(it != m1.end()); REQUIRE(it->second == 1); m1[""CRP""] = 2; REQUIRE(it->second == 2); } } TEST_CASE(""count simple hash"", ""[count]"") { jg::dense_hash_map m1 = {}; SECTION(""key"") { REQUIRE(m1.count(""queen"") == 0); m1.try_emplace(""queen"", 42); REQUIRE(m1.count(""queen"") == 1); } SECTION(""no generic count"") { auto v = is_valid([](const auto& m) -> decltype(m.count(nested_string{""queen""})) {}); REQUIRE_FALSE(v(m1)); } } TEST_CASE(""count transparent hash"", ""[count]"") { jg::dense_hash_map m1 = {}; SECTION(""key"") { REQUIRE(m1.count(nested_string{""pink floyd""}) == 0); m1.try_emplace(""pink floyd"", 42); REQUIRE(m1.count(nested_string{""pink floyd""}) == 1); } } TEST_CASE(""find simple hash"", ""[find]"") { jg::dense_hash_map m1 = {}; SECTION(""non-const"") { auto it = m1.find(""queen""); REQUIRE(it == m1.end()); m1.try_emplace(""queen"", 42); it = m1.find(""queen""); REQUIRE(it != m1.end()); REQUIRE(it->second == 42); static_assert(std::is_same_vsecond)), int&>); } SECTION(""const"") { const auto& m2 = m1; auto it = m2.find(""queen""); REQUIRE(it == m2.end()); m1.try_emplace(""queen"", 42); it = m2.find(""queen""); REQUIRE(it != m2.end()); REQUIRE(it->second == 42); static_assert(std::is_same_vsecond)), const int&>); } SECTION(""no generic find"") { auto v = is_valid([](const auto& m) -> decltype(m.find(nested_string{""queen""})) {}); REQUIRE_FALSE(v(m1)); } } TEST_CASE(""find transparent hash"", ""[find]"") { jg::dense_hash_map m1 = {}; SECTION(""non-const"") { auto it = m1.find(nested_string{""queen""}); REQUIRE(it == m1.end()); m1.try_emplace(""queen"", 42); it = m1.find(nested_string{""queen""}); REQUIRE(it != m1.end()); REQUIRE(it->second == 42); static_assert(std::is_same_vsecond)), int&>); } SECTION(""const"") { const auto& m2 = m1; auto it = m2.find(nested_string{""queen""}); REQUIRE(it == m2.end()); m1.try_emplace(""queen"", 42); it = m2.find(nested_string{""queen""}); REQUIRE(it != m2.end()); REQUIRE(it->second == 42); static_assert(std::is_same_vsecond)), const int&>); } } TEST_CASE(""contains simple hash"", ""[contains]"") { jg::dense_hash_map m1 = {}; SECTION(""key"") { REQUIRE_FALSE(m1.contains(""queen"")); m1.try_emplace(""queen"", 42); REQUIRE(m1.contains(""queen"")); } SECTION(""no generic contains"") { auto v = is_valid([](const auto& m) -> decltype(m.contains(nested_string{""queen""})) {}); REQUIRE_FALSE(v(m1)); } } TEST_CASE(""contains transparent hash"", ""[contains]"") { jg::dense_hash_map m1 = {}; SECTION(""key"") { REQUIRE_FALSE(m1.contains(nested_string{""pink floyd""})); m1.try_emplace(""pink floyd"", 42); REQUIRE(m1.contains(nested_string{""pink floyd""})); } } TEST_CASE(""equal_range simple hash"", ""[equal_range]"") { jg::dense_hash_map m1 = {}; SECTION(""non-const"") { auto [it, end] = m1.equal_range(""queen""); REQUIRE(it == m1.end()); REQUIRE(end == m1.end()); m1.try_emplace(""queen"", 42); auto [it2, end2] = m1.equal_range(""queen""); REQUIRE(it2 != m1.end()); REQUIRE(it2->second == 42); REQUIRE(std::distance(it2, end2) == 1); static_assert(std::is_same_vsecond)), int&>); } SECTION(""const"") { const auto& m2 = m1; auto [it, end] = m2.equal_range(""queen""); REQUIRE(it == m2.end()); REQUIRE(end == m1.end()); m1.try_emplace(""queen"", 42); auto [it2, end2] = m2.equal_range(""queen""); REQUIRE(it2 != m2.end()); REQUIRE(it2->second == 42); REQUIRE(std::distance(it2, end2) == 1); static_assert(std::is_same_vsecond)), const int&>); } SECTION(""no generic equal_range"") { auto v = is_valid([](const auto& m) -> decltype(m.equal_range(nested_string{""queen""})) {}); REQUIRE_FALSE(v(m1)); } } TEST_CASE(""equal_range transparent hash"", ""[equal_range]"") { jg::dense_hash_map m1 = {}; SECTION(""non-const"") { auto [it, end] = m1.equal_range(nested_string{""queen""}); REQUIRE(it == m1.end()); REQUIRE(end == m1.end()); m1.try_emplace(""queen"", 42); auto [it2, end2] = m1.equal_range(nested_string{""queen""}); REQUIRE(it2 != m1.end()); REQUIRE(it2->second == 42); REQUIRE(std::distance(it2, end2) == 1); static_assert(std::is_same_vsecond)), int&>); } SECTION(""const"") { const auto& m2 = m1; auto [it, end] = m2.equal_range(nested_string{""queen""}); REQUIRE(it == m2.end()); m1.try_emplace(""queen"", 42); auto [it2, end2] = m2.equal_range(nested_string{""queen""}); REQUIRE(it2 != m2.end()); REQUIRE(it2->second == 42); REQUIRE(std::distance(it2, end2) == 1); static_assert(std::is_same_vsecond)), const int&>); } } TEST_CASE(""bucket iterator"") { jg::dense_hash_map m = { {""pierre"", 1}, {""paul"", 2}, {""jacques"", 3}}; std::vector> expected = { {""jacques"", 3}, {""paul"", 2}, {""pierre"", 1}}; SECTION(""begin/end"") { static_assert(std::is_same_vsecond)), int&>); REQUIRE(std::equal(expected.begin(), expected.end(), m.begin(0), m.end(0))); } SECTION(""const begin/end"") { const auto& m2 = m; static_assert(std::is_same_vsecond)), const int&>); REQUIRE(std::equal(expected.begin(), expected.end(), m2.begin(0), m2.end(0))); } SECTION(""cbegin/cend"") { static_assert(std::is_same_vsecond)), const int&>); REQUIRE(std::equal(expected.cbegin(), expected.cend(), m.cbegin(0), m.cend(0))); } } TEST_CASE(""bucket_count"") { jg::dense_hash_map m; const auto& m2 = m; REQUIRE(m2.bucket_count() > 0); REQUIRE(m2.bucket_count() < m2.max_bucket_count()); } TEST_CASE(""bucket index"") { jg::dense_hash_map m = { {""pierre"", 1}, {""paul"", 2}, {""jacques"", 3}}; REQUIRE(m.bucket(""pierre"") == 0); REQUIRE(m.bucket(""paul"") == 0); REQUIRE(m.bucket(""jacques"") == 0); } TEST_CASE(""load_factor"") { jg::dense_hash_map m = {{""pierre"", 1}, {""paul"", 2}, {""jacques"", 3}}; const auto& cm = m; REQUIRE(cm.load_factor() < cm.max_load_factor()); REQUIRE(cm.load_factor() < cm.max_load_factor()); } TEST_CASE(""observers"") { const jg::dense_hash_map m = {}; SECTION(""hash_function"") { REQUIRE(std::is_same_v>); } SECTION(""key_eq"") { REQUIRE(std::is_same_v>); } } TEST_CASE(""comparison"") { jg::dense_hash_map m1 = {{""pierre"", 1}, {""paul"", 2}, {""jacques"", 3}}; SECTION(""equal"") { auto m2 = m1; REQUIRE(m2 == m1); REQUIRE_FALSE(m2 != m1); } SECTION(""not the same value"") { auto m2 = m1; m2[""pierre""] = 42; REQUIRE_FALSE(m2 == m1); REQUIRE(m2 != m1); } SECTION(""extra entry"") { auto m2 = m1; m2[""santa""] = 666; REQUIRE_FALSE(m2 == m1); REQUIRE(m2 != m1); } } TEST_CASE(""erase_if"") { jg::dense_hash_map m1 = {{""tintin"", 42}, {""milou"", 666}, {""haddock"", 13}}; SECTION(""on value"") { std::erase_if(m1, [](auto& pair) { if (pair.second > 40) { return true; } return false; }); std::vector> expected = {{""haddock"", 13}}; REQUIRE(std::equal(m1.begin(), m1.end(), expected.begin(), expected.end())); } SECTION(""on key"") { std::erase_if(m1, [](auto& pair) { if (pair.first[0] == 'h') { return true; } return false; }); std::vector> expected = {{""tintin"", 42}, {""milou"", 666}}; REQUIRE(std::equal(m1.begin(), m1.end(), expected.begin(), expected.end())); } } TEST_CASE(""deduction guides"") { jg::dense_hash_map m; jg::dense_hash_map m1(m.begin(), m.end()); REQUIRE(std::is_same_v>); jg::dense_hash_map m2({std::pair{""foo"", 2}, {""bar"", 3}}); REQUIRE(std::is_same_v>); jg::dense_hash_map m3(m.begin(), m.end(), 42u, named_allocator{""test""}); REQUIRE(std::is_same_v< decltype(m3), jg::dense_hash_map< std::string, int, std::hash, std::equal_to, named_allocator>>); // Rule 4 works thanks to https://cplusplus.github.io/LWG/issue2713 jg::dense_hash_map m4(m.begin(), m.end(), named_allocator{""test""}); REQUIRE(std::is_same_v< decltype(m4), jg::dense_hash_map< std::string, int, std::hash, std::equal_to, named_allocator>>); jg::dense_hash_map m5( m.begin(), m.end(), 42u, collision_hasher{}, named_allocator{""test""}); REQUIRE(std::is_same_v< decltype(m5), jg::dense_hash_map< std::string, int, collision_hasher, std::equal_to, named_allocator>>); jg::dense_hash_map m6( {std::pair{""foo"", 2}, {""bar"", 3}}, 42u, named_allocator{""test""}); REQUIRE(std::is_same_v< decltype(m6), jg::dense_hash_map< const char*, int, std::hash, std::equal_to, named_allocator>>); // Rule 7 also works thanks to https://cplusplus.github.io/LWG/issue2713 jg::dense_hash_map m7({std::pair{""foo"", 2}, {""bar"", 3}}, named_allocator{""test""}); REQUIRE(std::is_same_v< decltype(m7), jg::dense_hash_map< const char*, int, std::hash, std::equal_to, named_allocator>>); jg::dense_hash_map m8( {std::pair{""foo"", 2}, {""bar"", 3}}, 42u, collision_hasher{}, named_allocator{""test""}); REQUIRE(std::is_same_v< decltype(m7), jg::dense_hash_map< const char*, int, std::hash, std::equal_to, named_allocator>>); } TEST_CASE(""allocator propagation"") { int counter = 0; auto r = counting_pmr_resource(&counter); jg::pmr::dense_hash_map m(8u, &r); m.reserve(100); int old_counter_value = counter; // buckets_ creation + reserve of buckets_ and nodes_ == 3 allocations REQUIRE(counter >= 3); SECTION(""nested other container"") { m.try_emplace( ""a_super_long_string_to_disable_short_string_optimization"", ""a_super_long_string_to_disable_short_string_optimization""); REQUIRE((counter - old_counter_value) == 2); // two strings == 2 allocations. REQUIRE( m[""a_super_long_string_to_disable_short_string_optimization""] == ""a_super_long_string_to_disable_short_string_optimization""); std::pmr::string s(""lalalalalahihohohohohohohohohoho"", &r); m.insert_or_assign( ""a_super_long_string_to_disable_short_string_optimization"", std::move(s)); REQUIRE(s.empty()); } SECTION(""nested dense_hash_map"") { jg::pmr::dense_hash_map< std::string, jg::pmr::dense_hash_map> m2(8u, &r); // one alloc m2.reserve(100); // 2 allocs for reserve of buckets_ and nodes_ m2.try_emplace(""test"", m); // 1 alloc for the copy of buckets_ from m. nodes_ is not copied // as empty... so no allocation. REQUIRE((counter - old_counter_value) == 4); // string + dense_hash_map == 2 allocations. } } TEST_CASE(""Move only types"") { struct key { std::string value; key(std::string value) : value(std::move(value)) {} key(const key& other) = delete; key(key&& other) : value(std::move(other.value)) {} auto operator=(const key& other) -> key& = default; auto operator=(key&& other) -> key& { value = std::move(other.value); return *this; } auto operator==(const key& other) const -> bool { return other.value == value; } }; struct key_hasher { auto operator()(const key& k) const noexcept -> std::size_t { return std::hash()(k.value); } }; jg::dense_hash_map, key_hasher> m{}; m.emplace(std::pair{key{""test1""}, std::make_unique(""1"")}); m.try_emplace(key{""test2""}, std::make_unique(""2"")); REQUIRE(m.contains(key{""test1""})); auto it = m.find(key{""test1""}); REQUIRE(it != m.end()); REQUIRE(*it->second == ""1""); REQUIRE(m.contains(key{""test2""})); REQUIRE(m[key{""test2""}]); m[key{""test3""}] = std::make_unique(""3""); it = m.find(key{""test3""}); REQUIRE(it != m.end()); REQUIRE(*it->second == ""3""); m[key{""test1""}] = std::make_unique(""11""); it = m.find(key{""test1""}); REQUIRE(*it->second == ""11""); m.erase(key{""test3""}); REQUIRE_FALSE(m.contains(key{""test3""})); jg::dense_hash_map, key_hasher> m2{}; m2 = std::move(m); REQUIRE(m2.size() == 2); REQUIRE(m.size() == 0); REQUIRE(m != m2); std::swap(m2, m); REQUIRE(m2.size() == 0); REQUIRE(m.size() == 2); REQUIRE(m != m2); } TEST_CASE(""growth policy"") { struct dumb_growth_policy { static constexpr auto compute_index(std::size_t hash, std::size_t capacity) -> std::size_t { return hash % capacity; } static constexpr auto compute_closest_capacity(std::size_t min_capacity) -> std::size_t { return min_capacity; } static constexpr auto minimum_capacity() -> std::size_t { return 2u; } }; jg::dense_hash_map< int, int, std::hash, std::equal_to, std::allocator>, dumb_growth_policy> m{}; REQUIRE(m.bucket_count() == 2); m.try_emplace(1, 1); m.try_emplace(2, 2); REQUIRE(m.bucket_count() == 4); m.rehash(500); REQUIRE(m.bucket_count() == 500); } ",16336,True,3108.9140627935026,median "CLASS zcl_abapgit_object_tabl DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super FINAL. PUBLIC SECTION. INTERFACES zif_abapgit_object. ALIASES mo_files FOR zif_abapgit_object~mo_files. PROTECTED SECTION. TYPES: BEGIN OF ty_segment_definition, segmentheader TYPE edisegmhd, segmentdefinition TYPE edisegmdef, segmentstructures TYPE STANDARD TABLE OF edisegstru WITH DEFAULT KEY, END OF ty_segment_definition. TYPES: ty_segment_definitions TYPE STANDARD TABLE OF ty_segment_definition WITH DEFAULT KEY. ""! Serialize IDoc Segment type/definition if exits ""! @parameter io_xml | XML writer ""! @raising zcx_abapgit_exception | Exceptions METHODS serialize_idoc_segment IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception. ""! Deserialize IDoc Segment type/definition if exits ""! @parameter io_xml | XML writer ""! @parameter iv_package | Target package ""! @parameter rv_deserialized | It's a segment and was desserialized ""! @raising zcx_abapgit_exception | Exceptions METHODS deserialize_idoc_segment IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_input iv_package TYPE devclass RETURNING VALUE(rv_deserialized) TYPE abap_bool RAISING zcx_abapgit_exception. ""! Delete the IDoc Segment type if exists ""! @parameter rv_deleted | It's a segment and was deleted ""! @raising zcx_abapgit_exception | Exceptions METHODS delete_idoc_segment RETURNING VALUE(rv_deleted) TYPE abap_bool RAISING zcx_abapgit_exception. PRIVATE SECTION. TYPES: ty_dd03p_tt TYPE STANDARD TABLE OF dd03p . CONSTANTS c_longtext_id_tabl TYPE dokil-id VALUE 'TB' ##NO_TEXT. CONSTANTS: BEGIN OF c_s_dataname, segment_definition TYPE string VALUE 'SEGMENT_DEFINITION' ##NO_TEXT, END OF c_s_dataname . METHODS clear_dd03p_fields CHANGING !ct_dd03p TYPE ty_dd03p_tt . ""! Check if structure is an IDoc segment ""! @parameter rv_is_idoc_segment | It's an IDoc segment or not METHODS is_idoc_segment RETURNING VALUE(rv_is_idoc_segment) TYPE abap_bool. METHODS clear_dd03p_fields_common CHANGING !cs_dd03p TYPE dd03p . METHODS clear_dd03p_fields_dataelement CHANGING !cs_dd03p TYPE dd03p . ENDCLASS. CLASS zcl_abapgit_object_tabl IMPLEMENTATION. METHOD is_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. lv_segment_type = ms_item-obj_name. SELECT SINGLE segtyp FROM edisegment INTO lv_segment_type WHERE segtyp = lv_segment_type. rv_is_idoc_segment = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD clear_dd03p_fields. CONSTANTS lc_comptype_dataelement TYPE comptype VALUE 'E' ##NO_TEXT. DATA: lv_masklen TYPE c LENGTH 4. FIELD-SYMBOLS: TYPE dd03p. * remove nested structures DELETE ct_dd03p WHERE depth <> '00'. * remove fields from .INCLUDEs DELETE ct_dd03p WHERE adminfield <> '0'. LOOP AT ct_dd03p ASSIGNING WHERE NOT rollname IS INITIAL. clear_dd03p_fields_common( CHANGING cs_dd03p = ). lv_masklen = -masklen. IF lv_masklen = '' OR NOT lv_masklen CO '0123456789'. * make sure the field contains valid data, or the XML will dump CLEAR -masklen. ENDIF. IF -comptype = lc_comptype_dataelement. clear_dd03p_fields_dataelement( CHANGING cs_dd03p = ). ENDIF. IF -shlporigin = 'D'. * search help from domain CLEAR: -shlpfield, -shlpname. ENDIF. * XML output assumes correct field content IF -routputlen = ' '. CLEAR -routputlen. ENDIF. ENDLOOP. ENDMETHOD. METHOD clear_dd03p_fields_common. CLEAR: cs_dd03p-ddlanguage, cs_dd03p-dtelmaster, cs_dd03p-logflag, cs_dd03p-ddtext, cs_dd03p-reservedte, cs_dd03p-reptext, cs_dd03p-scrtext_s, cs_dd03p-scrtext_m, cs_dd03p-scrtext_l. ENDMETHOD. METHOD clear_dd03p_fields_dataelement. * type specified via data element CLEAR: cs_dd03p-domname, cs_dd03p-inttype, cs_dd03p-intlen, cs_dd03p-mask, cs_dd03p-memoryid, cs_dd03p-headlen, cs_dd03p-scrlen1, cs_dd03p-scrlen2, cs_dd03p-scrlen3, cs_dd03p-datatype, cs_dd03p-leng, cs_dd03p-outputlen, cs_dd03p-deffdname, cs_dd03p-convexit, cs_dd03p-entitytab, cs_dd03p-dommaster, cs_dd03p-domname3l, cs_dd03p-decimals, cs_dd03p-lowercase, cs_dd03p-signflag. ENDMETHOD. METHOD delete_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. DATA lv_result LIKE sy-subrc. IF is_idoc_segment( ) = abap_false. rv_deleted = abap_false. RETURN. ""previous XML version or no IDoc segment ENDIF. rv_deleted = abap_true. lv_segment_type = ms_item-obj_name. CALL FUNCTION 'SEGMENT_DELETE' EXPORTING segmenttyp = lv_segment_type IMPORTING result = lv_result EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDMETHOD. METHOD deserialize_idoc_segment. DATA lv_result LIKE sy-subrc. DATA lt_segment_definitions TYPE ty_segment_definitions. DATA lv_package TYPE devclass. DATA lv_uname TYPE sy-uname. FIELD-SYMBOLS TYPE ty_segment_definition. rv_deserialized = abap_false. TRY. io_xml->read( EXPORTING iv_name = c_s_dataname-segment_definition CHANGING cg_data = lt_segment_definitions ). CATCH zcx_abapgit_exception ##no_handler. RETURN. ""previous XML version or no IDoc segment ENDTRY. IF lines( lt_segment_definitions ) = 0. RETURN. ""no IDoc segment ENDIF. rv_deserialized = abap_true. lv_package = iv_package. LOOP AT lt_segment_definitions ASSIGNING . -segmentheader-presp = -segmentheader-pwork = cl_abap_syst=>get_user_name( ). CALL FUNCTION 'SEGMENT_READ' EXPORTING segmenttyp = -segmentheader-segtyp IMPORTING result = lv_result EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. CALL FUNCTION 'SEGMENT_CREATE' IMPORTING segmentdefinition = -segmentdefinition TABLES segmentstructure = -segmentstructures CHANGING segmentheader = -segmentheader devclass = lv_package EXCEPTIONS OTHERS = 1. ELSE. CALL FUNCTION 'SEGMENT_MODIFY' CHANGING segmentheader = -segmentheader devclass = lv_package EXCEPTIONS OTHERS = 1. IF sy-subrc = 0. CALL FUNCTION 'SEGMENTDEFINITION_MODIFY' TABLES segmentstructure = -segmentstructures CHANGING segmentdefinition = -segmentdefinition EXCEPTIONS OTHERS = 1. ENDIF. ENDIF. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDLOOP. lv_uname = cl_abap_syst=>get_user_name( ). CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_test_modus = abap_false wi_tadir_pgmid = 'R3TR' wi_tadir_object = ms_item-obj_type wi_tadir_obj_name = ms_item-obj_name wi_tadir_author = lv_uname wi_tadir_devclass = iv_package wi_tadir_masterlang = mv_language iv_set_edtflag = abap_true iv_delflag = abap_false EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from TR_TADIR_INTERFACE' ). ENDIF. ENDMETHOD. METHOD serialize_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. DATA lv_result LIKE sy-subrc. DATA lv_devclass TYPE devclass. DATA lt_segmentdefinitions TYPE STANDARD TABLE OF edisegmdef. DATA ls_segment_definition TYPE ty_segment_definition. DATA lt_segment_definitions TYPE ty_segment_definitions. FIELD-SYMBOLS: TYPE edisegmdef. IF is_idoc_segment( ) = abap_false. RETURN. ENDIF. lv_segment_type = ms_item-obj_name. CALL FUNCTION 'SEGMENT_READ' EXPORTING segmenttyp = lv_segment_type IMPORTING result = lv_result TABLES segmentdefinition = lt_segmentdefinitions EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. LOOP AT lt_segmentdefinitions ASSIGNING . CLEAR ls_segment_definition. CALL FUNCTION 'SEGMENTDEFINITION_READ' EXPORTING segmenttyp = -segtyp IMPORTING result = lv_result devclass = lv_devclass segmentheader = ls_segment_definition-segmentheader segmentdefinition = ls_segment_definition-segmentdefinition TABLES segmentstructure = ls_segment_definition-segmentstructures CHANGING version = -version EXCEPTIONS no_authority = 1 segment_not_existing = 2 OTHERS = 3. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. zcl_abapgit_object_idoc=>clear_idoc_segement_fields( CHANGING cs_structure = ls_segment_definition-segmentdefinition ). zcl_abapgit_object_idoc=>clear_idoc_segement_fields( CHANGING cs_structure = ls_segment_definition-segmentheader ). APPEND ls_segment_definition TO lt_segment_definitions. ENDLOOP. io_xml->add( iv_name = c_s_dataname-segment_definition ig_data = lt_segment_definitions ). ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_data, as4user TYPE as4user, as4date TYPE as4date, as4time TYPE as4time, END OF ty_data. DATA: lt_data TYPE STANDARD TABLE OF ty_data WITH DEFAULT KEY, ls_data LIKE LINE OF lt_data. SELECT as4user as4date as4time FROM dd02l INTO TABLE lt_data WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SELECT as4user as4date as4time APPENDING TABLE lt_data FROM dd09l WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SELECT as4user as4date as4time APPENDING TABLE lt_data FROM dd12l WHERE sqltab = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SORT lt_data BY as4date DESCENDING as4time DESCENDING. READ TABLE lt_data INDEX 1 INTO ls_data. IF sy-subrc = 0. rv_user = ls_data-as4user. ELSE. rv_user = c_user_unknown. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lv_objname TYPE rsedd0-ddobjname, lv_tabclass TYPE dd02l-tabclass, lv_no_ask TYPE abap_bool, lv_subrc TYPE sy-subrc, lr_data TYPE REF TO data. FIELD-SYMBOLS: TYPE any. IF zif_abapgit_object~exists( ) = abap_false. "" Proxies e.g. delete on its own, nothing todo here then. RETURN. ENDIF. lv_objname = ms_item-obj_name. IF delete_idoc_segment( ) = abap_false. lv_no_ask = abap_true. SELECT SINGLE tabclass FROM dd02l INTO lv_tabclass WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. IF sy-subrc = 0 AND lv_tabclass = 'TRANSP'. * Avoid dump in dynamic SELECT in case the table does not exist on database CALL FUNCTION 'DB_EXISTS_TABLE' EXPORTING tabname = lv_objname IMPORTING subrc = lv_subrc. IF lv_subrc = 0. * it cannot delete table with table without asking CREATE DATA lr_data TYPE (lv_objname). ASSIGN lr_data->* TO . SELECT SINGLE * FROM (lv_objname) INTO . IF sy-subrc = 0. lv_no_ask = abap_false. ENDIF. ENDIF. ENDIF. CALL FUNCTION 'RS_DD_DELETE_OBJ' EXPORTING no_ask = lv_no_ask objname = lv_objname objtype = 'T' EXCEPTIONS not_executed = 1 object_not_found = 2 object_not_specified = 3 permission_failure = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from RS_DD_DELETE_OBJ, TABL,' && sy-subrc ). ENDIF. delete_longtexts( c_longtext_id_tabl ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: lv_name TYPE ddobjname, lv_tname TYPE trobj_name, ls_dd02v TYPE dd02v, ls_dd09l TYPE dd09l, lt_dd03p TYPE TABLE OF dd03p, lt_dd05m TYPE TABLE OF dd05m, lt_dd08v TYPE TABLE OF dd08v, lt_dd12v TYPE dd12vtab, lt_dd17v TYPE dd17vtab, ls_dd17v LIKE LINE OF lt_dd17v, lt_secondary LIKE lt_dd17v, lt_dd35v TYPE TABLE OF dd35v, lt_dd36m TYPE dd36mttyp, ls_dd12v LIKE LINE OF lt_dd12v. IF deserialize_idoc_segment( io_xml = io_xml iv_package = iv_package ) = abap_false. io_xml->read( EXPORTING iv_name = 'DD02V' CHANGING cg_data = ls_dd02v ). io_xml->read( EXPORTING iv_name = 'DD09L' CHANGING cg_data = ls_dd09l ). io_xml->read( EXPORTING iv_name = 'DD03P_TABLE' CHANGING cg_data = lt_dd03p ). io_xml->read( EXPORTING iv_name = 'DD05M_TABLE' CHANGING cg_data = lt_dd05m ). io_xml->read( EXPORTING iv_name = 'DD08V_TABLE' CHANGING cg_data = lt_dd08v ). io_xml->read( EXPORTING iv_name = 'DD12V' CHANGING cg_data = lt_dd12v ). io_xml->read( EXPORTING iv_name = 'DD17V' CHANGING cg_data = lt_dd17v ). io_xml->read( EXPORTING iv_name = 'DD35V_TALE' CHANGING cg_data = lt_dd35v ). io_xml->read( EXPORTING iv_name = 'DD36M' CHANGING cg_data = lt_dd36m ). corr_insert( iv_package = iv_package iv_object_class = 'DICT' ). lv_name = ms_item-obj_name. "" type conversion CALL FUNCTION 'DDIF_TABL_PUT' EXPORTING name = lv_name dd02v_wa = ls_dd02v dd09l_wa = ls_dd09l TABLES dd03p_tab = lt_dd03p dd05m_tab = lt_dd05m dd08v_tab = lt_dd08v dd35v_tab = lt_dd35v dd36m_tab = lt_dd36m EXCEPTIONS tabl_not_found = 1 name_inconsistent = 2 tabl_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_TABL_PUT' ). ENDIF. zcl_abapgit_objects_activation=>add_item( ms_item ). * handle indexes LOOP AT lt_dd12v INTO ls_dd12v. * todo, call corr_insert? CLEAR lt_secondary. LOOP AT lt_dd17v INTO ls_dd17v WHERE sqltab = ls_dd12v-sqltab AND indexname = ls_dd12v-indexname. APPEND ls_dd17v TO lt_secondary. ENDLOOP. CALL FUNCTION 'DDIF_INDX_PUT' EXPORTING name = ls_dd12v-sqltab id = ls_dd12v-indexname dd12v_wa = ls_dd12v TABLES dd17v_tab = lt_secondary EXCEPTIONS indx_not_found = 1 name_inconsistent = 2 indx_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_INDX_PUT' ). ENDIF. CALL FUNCTION 'DD_DD_TO_E071' EXPORTING type = 'INDX' name = ls_dd12v-sqltab id = ls_dd12v-indexname IMPORTING obj_name = lv_tname. zcl_abapgit_objects_activation=>add( iv_type = 'INDX' iv_name = lv_tname ). ENDLOOP. deserialize_longtexts( io_xml ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_tabname TYPE dd02l-tabname. SELECT SINGLE tabname FROM dd02l INTO lv_tabname WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. rv_bool = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. DATA: lo_local_version_output TYPE REF TO zcl_abapgit_xml_output, lo_local_version_input TYPE REF TO zcl_abapgit_xml_input. CREATE OBJECT lo_local_version_output. me->zif_abapgit_object~serialize( lo_local_version_output ). CREATE OBJECT lo_local_version_input EXPORTING iv_xml = lo_local_version_output->render( ). CREATE OBJECT ri_comparator TYPE zcl_abapgit_object_tabl_compar EXPORTING io_local = lo_local_version_input. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. DATA: ls_meta TYPE zif_abapgit_definitions=>ty_metadata. ls_meta = zif_abapgit_object~get_metadata( ). IF ls_meta-late_deser = abap_true. APPEND zif_abapgit_object=>gc_step_id-late TO rt_steps. ELSEIF ls_meta-ddic = abap_true. APPEND zif_abapgit_object=>gc_step_id-ddic TO rt_steps. ELSE. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). rs_metadata-ddic = abap_true. ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. rv_is_locked = exists_a_lock_entry_for( iv_lock_object = 'ESDICT' iv_argument = |{ ms_item-obj_type }{ ms_item-obj_name }| ). ENDMETHOD. METHOD zif_abapgit_object~jump. jump_se11( iv_radio = 'RSRD1-DDTYPE' iv_field = 'RSRD1-DDTYPE_VAL' ). ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: lv_name TYPE ddobjname, ls_dd02v TYPE dd02v, ls_dd09l TYPE dd09l, lt_dd03p TYPE ty_dd03p_tt, lt_dd05m TYPE TABLE OF dd05m, lt_dd08v TYPE TABLE OF dd08v, lt_dd12v TYPE dd12vtab, lt_dd17v TYPE dd17vtab, lt_dd35v TYPE TABLE OF dd35v, lv_index LIKE sy-index, lt_dd36m TYPE dd36mttyp. FIELD-SYMBOLS: LIKE LINE OF lt_dd12v, LIKE LINE OF lt_dd05m, LIKE LINE OF lt_dd36m, TYPE any. lv_name = ms_item-obj_name. CALL FUNCTION 'DDIF_TABL_GET' EXPORTING name = lv_name langu = mv_language IMPORTING dd02v_wa = ls_dd02v dd09l_wa = ls_dd09l TABLES dd03p_tab = lt_dd03p dd05m_tab = lt_dd05m dd08v_tab = lt_dd08v dd12v_tab = lt_dd12v dd17v_tab = lt_dd17v dd35v_tab = lt_dd35v dd36m_tab = lt_dd36m EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_TABL_GET' ). ENDIF. IF ls_dd02v IS INITIAL. RETURN. "" object does not exits ENDIF. CLEAR: ls_dd02v-as4user, ls_dd02v-as4date, ls_dd02v-as4time. * reset numeric field, so XML does not crash IF ls_dd02v-prozpuff = ''. CLEAR ls_dd02v-prozpuff. ENDIF. IF ls_dd02v-datmin = ''. CLEAR ls_dd02v-datmin. ENDIF. IF ls_dd02v-datmax = ''. CLEAR ls_dd02v-datmax. ENDIF. IF ls_dd02v-datavg = ''. CLEAR ls_dd02v-datavg. ENDIF. CLEAR: ls_dd09l-as4user, ls_dd09l-as4date, ls_dd09l-as4time. ASSIGN COMPONENT 'ROWORCOLST' OF STRUCTURE ls_dd09l TO . IF sy-subrc = 0 AND = 'C'. CLEAR . ""To avoid diff errors. This field doesn't exists in all releases ENDIF. LOOP AT lt_dd12v ASSIGNING . CLEAR: -as4user, -as4date, -as4time. ENDLOOP. clear_dd03p_fields( CHANGING ct_dd03p = lt_dd03p ). * remove foreign keys inherited from .INCLUDEs DELETE lt_dd08v WHERE noinherit = 'N'. LOOP AT lt_dd05m ASSIGNING . lv_index = sy-tabix. READ TABLE lt_dd08v WITH KEY fieldname = -fieldname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_dd05m INDEX lv_index. ENDIF. ENDLOOP. * remove inherited search helps DELETE lt_dd35v WHERE shlpinher = abap_true. LOOP AT lt_dd36m ASSIGNING . lv_index = sy-tabix. READ TABLE lt_dd35v WITH KEY fieldname = -fieldname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_dd36m INDEX lv_index. ENDIF. ENDLOOP. io_xml->add( iv_name = 'DD02V' ig_data = ls_dd02v ). IF NOT ls_dd09l IS INITIAL. io_xml->add( iv_name = 'DD09L' ig_data = ls_dd09l ). ENDIF. io_xml->add( ig_data = lt_dd03p iv_name = 'DD03P_TABLE' ). io_xml->add( ig_data = lt_dd05m iv_name = 'DD05M_TABLE' ). io_xml->add( ig_data = lt_dd08v iv_name = 'DD08V_TABLE' ). io_xml->add( iv_name = 'DD12V' ig_data = lt_dd12v ). io_xml->add( iv_name = 'DD17V' ig_data = lt_dd17v ). io_xml->add( ig_data = lt_dd35v iv_name = 'DD35V_TALE' ). io_xml->add( iv_name = 'DD36M' ig_data = lt_dd36m ). serialize_longtexts( io_xml = io_xml iv_longtext_id = c_longtext_id_tabl ). serialize_idoc_segment( io_xml ). ENDMETHOD. ENDCLASS. ",6523,False,1363.3079310543403,median "/* 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 /* U8glib 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. */ // Please UNCOMMENT one of the contructor lines below // U8g2 Contructor List (Frame 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_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition) //U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_128X64_ALT0_F_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_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display //U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 16, /* data=*/ 17, /* reset=*/ U8X8_PIN_NONE); // ESP32 Thing, pure SW emulated I2C //U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 16, /* data=*/ 17); // ESP32 Thing, HW I2C with pin remapping //U8G2_SSD1306_128X64_NONAME_F_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_NONAME_F_8080 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8G2_SSD1306_128X64_VCOMH0_F_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_F_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_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SH1106_128X64_VCOMH0_F_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_F_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_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_64X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1107_128X128_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); //U8G2_SH1107_SEEED_96X96_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1108_160X160_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SH1122_256X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8G2_SSD1306_64X48_ER_F_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_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_64X32_1F_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1306_96X16_ER_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" OLED //U8G2_SSD1322_NHD_256X64_F_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_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8G2_16BIT in u8g2.h //U8G2_SSD1322_NHD_128X64_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1322_NHD_128X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1325_NHD_128X64_F_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_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_SEEED_96X96_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8G2_SSD1327_EA_W128128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_EA_W128128_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_EA_W128128_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); //U8G2_SSD1327_MIDAS_128X128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1327_MIDAS_128X128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1329_128X96_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1305_128X32_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_ADAFRUIT_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1306_128X64_ADAFRUIT_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME0_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_SSD1309_128X64_NONAME2_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LD7032_60X32_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 9, /* dc=*/ 10, /* reset=*/ 8); // SW SPI Nano Board //U8G2_LD7032_60X32_F_4W_SW_I2C u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* reset=*/ U8X8_PIN_NONE); // NOT TESTED! //U8G2_UC1701_EA_DOGS102_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1701_EA_DOGS102_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_PCD8544_84X48_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCD8544_84X48_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8G2_PCF8812_96X65_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_PCF8812_96X65_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8G2_HX1230_96X68_F_3W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8G2_HX1230_96X68_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_KS0108_128X64_F 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_F 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_F_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_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_F_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_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18 /* A4 */ , /* data=*/ 16 /* A2 */, /* CS=*/ 17 /* A3 */, /* reset=*/ U8X8_PIN_NONE); //U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7920_128X64_F_HW_SPI u8g2(U8G2_R0, /* CS=*/ 10, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_64128N_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_EA_DOGM132_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_EA_DOGM132_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8G2_ST7565_ZOLEN_128X64_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ZOLEN_128X64_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LM6059_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LM6059_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8G2_ST7565_LX12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_LX12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_ERC12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12832_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_NHD_C12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7565_JLX12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_PI_132X64_F_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_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8G2_ST7567_JLX12864_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_JLX12864_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7567_ENH_DG128064I_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX172104_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX256128_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256128_F_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_F_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_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX256160_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Enable U8g2 16 bit mode for this display //U8G2_ST75256_JLX240160_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX240160_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST75256_JLX25664_F_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, enable U8g2 16 bit mode for this display //U8G2_NT7534_TG12864R_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_NT7534_TG12864R_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_ST7588_JLX12864_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8G2_ST7588_JLX12864_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ 5); //U8G2_IST3020_ERC19264_F_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_F_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_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_LC7981_160X80_F_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_F_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_F_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_F_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_F 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_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_256X64_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_T6963_160X80_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FS0 and FS1 with GND //U8G2_SED1330_240X128_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 17, /*cs=*/ 14, /*dc=*/ 15, /*reset=*/ 16); // Connect RD with +5V, FG with GND //U8G2_SED1330_240X128_F_6800 u8g2(U8G2_R0, 13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); // A0 is dc pin! //U8G2_RA8835_NHD_240X128_F_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_F_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_UC1604_JLX19264_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1604_JLX19264_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_ERC24064_F_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_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8G2_UC1608_240X128_F_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_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1610_EA_DOGXL160_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8G2_UC1611_EA_DOGM240_F_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8G2_UC1611_EA_DOGM240_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Due, SW SPI, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_F_2ND_HW_I2C u8g2(U8G2_R0, /* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8G2_UC1611_EA_DOGXL240_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Due, SW SPI, DOGXL240 Test Board //U8G2_UC1611_EW50850_F_8080 u8g2(U8G2_R0, 8, 9, 10, 11, 4, 5, 6, 7, /*enable=*/ 18, /*cs=*/ 3, /*dc=*/ 16, /*reset=*/ 16); // 240x160, Connect RD/WR1 pin with 3.3V, CS is aktive high //U8G2_UC1638_160X128_F_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8G2_SSD1606_172X72_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8G2_SSD1607_200X200_F_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_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8G2_IL3820_296X128_F_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_F_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_MAX7219_32X8_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); //U8G2_MAX7219_8X8_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 11, /* data=*/ 12, /* cs=*/ 10, /* dc=*/ U8X8_PIN_NONE, /* reset=*/ U8X8_PIN_NONE); // End of constructor list void setup(void) { // DOGS102 Shield (http://shieldlist.org/controlconnection/dogs102) // u8g2.begin(/* menu_select_pin= */ 5, /* menu_next_pin= */ 4, /* menu_prev_pin= */ 2, /* 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_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 = 0; 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 ""); } } ",12142,True,3586.843081889916,median "// christmas-tree.ino - Firmware for a Christmas decoration // Copyright (C) 2018 Joel Ray Holveck // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or (at // your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see `http://www.gnu.org/licenses/'. //#define NDEBUG 1 #include #include #include #pragma GCC diagnostic warning ""-Wall"" #pragma GCC diagnostic warning ""-Wextra"" #ifdef NDEBUG #define assert(e) do {} while (0) #else void AssertFail(int lineno); #define assert(e) ((e) ? (void)0 : AssertFail(__LINE__)) #endif // I could make this inherit from Print to get printf, etc. But the // decimal print routines take up too much flash space (about 300 // bytes), so I print in hex, which is much cheaper. class CTDebugger final { #ifdef NDEBUG public: void write(uint8_t) {} template void print(T) {} template void println(T) {} #else private: const char hexdigs[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; void PrintByte(uint8_t val) { write(hexdigs[val >> 4]); write(hexdigs[val & 0x0f]); } public: void write(uint8_t); void print(uint8_t val) { PrintByte(val); } void print(uint16_t val) { PrintByte(val >> 8); PrintByte(val); } void print(uint32_t val) { PrintByte(val >> 24); PrintByte(val >> 16); PrintByte(val >> 8); PrintByte(val); } void print(const char* val) { while (*val) { write(*(val++)); } } void print(int8_t val) { if (val < 0) { write('-'); print(static_cast(-val)); } else { print(static_cast(val)); } } void print(int16_t val) { if (val < 0) { write('-'); print(static_cast(-val)); } else { print(static_cast(val)); } } void print(int32_t val) { if (val < 0) { write('-'); print(static_cast(-val)); } else { print(static_cast(val)); } } void print(float val); void print(double val) { print(static_cast(val)); } void println() { write('\\r'); write('\\n'); } template void println(T val) { print(val); println(); } private: void Clock(bool val); #endif } Debugger; //#define DO_TRACE 1 #ifdef DO_TRACE #define TRACELINE(arg) do { \\ Debugger.write('t'); Debugger.println(__LINE__); \\ } while (0) #else #define TRACELINE(arg) do {} while (0) #endif #include ""capsense.h"" #include ""tlc5947.h"" // This is smaller than the built-in memset. void MyMemSet(void* addr, uint8_t size, uint8_t val) { for (uint8_t i = 0; i < size; i++) { static_cast(addr)[i] = val; } } // The Arduino doesn't have a built-in random float function, so I // have this instead. It ain't perfect by a long shot, but it works // for my needs. float RandomFloat(float max) { return (max * static_cast(random()) / static_cast(LONG_MAX)); } constexpr uint16_t kNumGpios = 10; // Is this in a #defined constant? constexpr float kBrightChangeRate = 1.0 / 32; // Note that CANARY takes about 132 bytes. #define CANARY 1 constexpr uint8_t kStackCanaryVal = 105; constexpr uint8_t kStackCanarySweepFreq = 64; // Regarding kCsSamps: Larger is more stable but slower. The speed // also depends on the capacitance present; lower capacitance resolves // more quickly. With four sensors (well, as of this writing, one // sensor being probed 4 times), a 1M resistor, and a 3.3v supply, // kCsSamps=16 samples gives a loop rate of about 42 Hz when there's // no finger present, and about 20 Hz when all sensors are triggered. constexpr uint8_t kCsSamps = 16; // When tuning kCsThres, make sure your hand isn't over the laptop! constexpr unsigned int kCsThres = kCsSamps * 6; constexpr unsigned int kCsThrL = kCsThres / 2; constexpr unsigned int kCsThrH = kCsThres * 3 / 2; // For mappings between package pin numbers and GPIO pin numbers, // see http://highlowtech.org/?p=1695 specifically // http://highlowtech.org/wp-content/uploads/2011/10/ATtiny44-84.png constexpr uint8_t kPinCsChg = 0; constexpr uint8_t kPinCsO1S = 1; constexpr uint8_t kPinCsO2S = 2; constexpr uint8_t kPinCsO3S = 3; constexpr uint8_t kPinCsO4S = 7; constexpr uint8_t kPinCsO5S = 4; constexpr uint8_t kPinCsO6S = 6; // We use the same pin for kPinDbgMosi as kPinLedMosi. // This is the MISO (not MOSI) line on the ICSP header. constexpr uint8_t kPinDbgMosi = 5; constexpr uint8_t kPinDbgSclk = 4; // The debug protocol seems stable at about 100uS hold time in initial // experiments. It may be related to the time I spend on the slave // doing serial writes, since my writes are amplified a lot. I might // also try a direct port read in the slave, which is about 25x // faster. Note that this is only the hold time for high or low; the // total clock period is about twice this. Note that the debug host // will resync if there's no clock for 10ms, to make sure it doesn't // get its bits out of phase. constexpr unsigned int kDbgClkHoldMicros = 250; constexpr uint8_t kPinLedMosi = 5; constexpr uint8_t kPinLedSclk = 8; constexpr uint8_t kPinLedLat = 9; constexpr uint8_t kPinLedBlank = 10; constexpr int kPostFailBlinks = 3; TLC5947<1, // Number of drivers kPinLedSclk, // SPI clock pin kPinLedMosi, // SPI data pin kPinLedLat> leds; // Latch pin #define LED_PHASE1 0 #define LED_PHASE2 1 #define LED_PHASE3 2 constexpr float kLoveStarMaxRamp = 0.75; constexpr float kPhaseIncrPeace = 0.005; constexpr float kPhaseIncr = 0.05; //#define LED_SCHMITT 3 //#define LED_COUNT0 3 // Note that COUNT0 == Q //#define LED_COUNT1 4 //#define LED_COUNT2 5 //#define LED_COUNT3 6 //#define LED_Q 9 //#define LED_NQ 10 //#define LED_CYCLE 11 //#define LED_CAP 12 #define LED_METER_START 15 constexpr uint16_t kLedMeterCount = 5; constexpr long kLedMeterMax = kCsThres * 2; constexpr int kNumLedColors = 4; // The instance, and the referenced arrays, must be in PROGMEM. class LedStars { private: class PgmArrayReader { public: explicit PgmArrayReader(uint8_t const* pgm_array_ptr) : pgm_array_ptr_(pgm_array_ptr) {} explicit PgmArrayReader(uint8_t const* const* pgm_array_pgm_ptr) : pgm_array_ptr_(pgm_read_word(pgm_array_pgm_ptr)) {} uint8_t operator[] (size_t i) const { return pgm_read_byte(pgm_array_ptr_ + i); } PgmArrayReader& operator+=(size_t increment) { pgm_array_ptr_ += increment; return *this; } private: const uint8_t* pgm_array_ptr_; }; public: void Setup() const { count_ = pgm_read_byte(&pgm_count_); } PgmArrayReader by_pos() const { return PgmArrayReader(&pgm_by_pos_); } PgmArrayReader by_color() const { return PgmArrayReader(&pgm_by_color_); } PgmArrayReader color_counts() const { return PgmArrayReader(pgm_color_counts_); } uint8_t Count() const { return count_; } public: // FIXME Make these private const uint8_t* pgm_by_pos_; const uint8_t* pgm_by_color_; const uint8_t pgm_color_counts_[kNumLedColors]; const uint8_t pgm_count_; static uint8_t count_; // Updated once at start of program }; uint8_t LedStars::count_; #ifndef NDEBUG const uint8_t led_stars_dev_by_pos[] PROGMEM = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 23, 20, 21, 22 }; const uint8_t led_stars_dev_by_color[] PROGMEM = { 6, 10, 14, 22, // green 3, 7, 11, 23, // red 4, 8, 12, 20, // yellow 5, 9, 13, 21 // blue }; constexpr LedStars led_stars_dev PROGMEM = { .pgm_by_pos_ = led_stars_dev_by_pos, .pgm_by_color_ = led_stars_dev_by_color, .pgm_color_counts_ = { 4, 4, 4, 4 }, .pgm_count_ = 16, }; #endif const uint8_t led_stars_norm_by_pos[] PROGMEM = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16, 17, 18, 19, 23, 20, 21, 22 }; const uint8_t led_stars_norm_by_color[] PROGMEM = { 6, 10, 14, 18, 22, // green 3, 7, 11, 15, 19, 23, // red 4, 8, 12, 16, 20, // yellow 5, 9, 13, 17, 21, // blue }; constexpr LedStars led_stars_norm PROGMEM = { .pgm_by_pos_ = led_stars_norm_by_pos, .pgm_by_color_ = led_stars_norm_by_color, .pgm_color_counts_ = { 5, 6, 5, 5 }, .pgm_count_ = 21, }; #ifndef NDEBUG const LedStars* led_stars; #else constexpr const LedStars* led_stars = &led_stars_norm; #endif constexpr int kNumLedStarsMax = led_stars_norm.pgm_count_; // Constants for Peace and Love modes. constexpr float kLedStarMinMotion = 0.005; constexpr float kLedStarDeltaMotion = 0.01; constexpr long kLedStarPeriod = 64; constexpr long kLedStarBurstPeriod = 128; #ifndef NDEBUG bool dev_mode; #endif enum DisplayMode { kModeLove, kModePeace, kModeJoy } display_mode = kModeLove; enum JoySubMode { kSubModeDoubleChase, kSubModeCylon, kSubModeCylonFill, kSubModeLast }; JoySubMode joy_sub_mode = kSubModeDoubleChase; // FIXME Why are these separate from the top-level variables? struct __attribute__ ((__packed__)) { bool uninitialized; // Erased EEPROM reads as all 1s float bright_pct; DisplayMode display_mode; JoySubMode joy_sub_mode; } persistent_data; unsigned long update_persistent_data_at_millis = ULONG_MAX; // We use the LED on the debugging dongle to tell us if we've ever // gotten a high reading. That lets me leave it alone for a long time // and see if it ever got a false reading. This tells us if we need // to send the latch signal. To prevent spamming the LED latch // signal, but still let us reset it just by resetting the debug board, // we only send it at most once per second. unsigned long debug_led_latch_at_millis; constexpr unsigned long kDbgLedLatchDelayMs = 1000; uint16_t bright; // Calculated during startup float bright_pct = 0.5; void __attribute__((noinline)) TwinkleBool(uint16_t ledno, bool val) { // The twinkling of boolean outputs in debug mode is cute, but it takes // 90 bytes or so of code space. #ifdef DO_TWINKLE_BOOL long delta = display_mode == kModeLove ? random(bright/128) : 0; // The ""16 * delta"" is because we totally ignore the gamma curve here. leds.setPWM(ledno, val ? bright - (16 * delta) : delta); #else leds.setPWM(ledno, val ? bright : 0); #endif } #ifndef NDEBUG void __attribute__((noinline)) CTDebugger::Clock(bool val) { digitalWrite(kPinDbgSclk, val); delayMicroseconds(kDbgClkHoldMicros); } void CTDebugger::write(uint8_t byte) { pinMode(kPinDbgSclk, OUTPUT); for (int i = 0; i < 8; i++) { digitalWrite(kPinDbgMosi, byte & 0x80); byte <<= 1; Clock(true); Clock(false); } } // Takes about 186 bytes (if it's actually called) void CTDebugger::print(float value_in) { union { // Essentially defines the IEEE 784-2008 binary16 layout struct { unsigned int significand: 10; unsigned int exponent: 5; unsigned int sign: 1; } bits; float flo; } value; value.flo = value_in; // Print the sign even if it's a NaN. This saves some code space, // and also distinguishes between quiet (negative) and signaling // (positive) NaNs. if (value.bits.sign) { write('-'); } // Check NaN and infinity if (value.bits.exponent == 0x1f) { if (value.bits.significand != 0) { print(""nan""); } else { print(""inf""); } return; } if (value.bits.exponent == 0) { write('0'); } else { write('1'); } write('.'); print(value.bits.significand >> 2); print(value.bits.significand << 6); // We use 'x' to separate the significand from the exponent. The // C++ %a modifier uses 'p', but it prints the exponent in decimal, // so we avoid that. write('x'); int8_t norm_exponent = value.bits.exponent - 15; print(norm_exponent); } #endif void DidFail(void) { // Use this if you want to halt the board after failures (e.g., during // overnight testing). //wdt_disable(); //while(1); } #ifndef NDEBUG void AssertFail(int lineno) { Debugger.write('A'); Debugger.println(lineno); DidFail(); } #endif void PostFail(uint8_t code, uint8_t aux) { uint16_t combined_code = (aux << 8) | code; for (uint16_t i = 4; i < 20; i++) { leds.setPWM(i, combined_code & 1 ? leds.kPwmMax : 0); combined_code >>= 1; } digitalWrite(kPinLedBlank, LOW); #ifndef NDEBUG Debugger.write('\\x0c'); Debugger.write('X'); Debugger.print(code); Debugger.write(':'); Debugger.println(aux); for (uint8_t i = 0; i < kPostFailBlinks; i++) { leds.setPWM(1, 0); // Red LED leds.write(); delay(1000); leds.setPWM(1, bright); leds.write(); delay(1000); } #endif DidFail(); } class CapOrnament { public: CapOrnament(char name, uint16_t sense_pin) : cs_(sense_pin), name_(name), sense_pin_(sense_pin) {} bool level() const { return state_.level; }; void set_led_diagnostic(bool d) { state_.led_diagnostic = d; } bool led_diagnostic() const { return state_.led_diagnostic; } bool offline() const { return state_.offline; } void set_offline(bool offline) { state_.offline = offline; } void Post(uint8_t code); bool SenseEdge(); bool SenseLevel() { SenseEdge(); return level(); } static uint8_t count(void) { return count_; } #ifndef NDEBUG static void SweepDbgSensor(); #endif private: #ifndef NDEBUG static constexpr int kDbgSensorPinShift = 1; static constexpr uint16_t kDbgSensorSweepLength = kNumGpios << kDbgSensorPinShift; static uint8_t dbg_sensor_; #endif static uint8_t count_; void PostOneWay(uint8_t code, bool value); #ifndef NDEBUG bool Dbg() { return dbg_sensor_ == (sense_pin_ << kDbgSensorPinShift); } #endif template bool Schmitt(unsigned int input); bool CheckRisingEdge(bool input); CapacitiveSensor cs_; char name_; uint8_t sense_pin_; struct { bool offline : 1; bool led_diagnostic : 1; bool level : 1; } state_; }; #ifndef NDEBUG uint8_t CapOrnament::dbg_sensor_ = 0; #endif uint8_t CapOrnament::count_ = 0; template bool CapOrnament::Schmitt(unsigned int input) { if (state_.level) { return input > threshold_l; } else if (input >= threshold_h) { return true; } else { return false; } } #ifndef NDEBUG void CapOrnament::SweepDbgSensor() { dbg_sensor_++; if (dbg_sensor_ >= kDbgSensorSweepLength) { dbg_sensor_ = 0; } } #endif bool CapOrnament::SenseEdge() { if (state_.offline) { #ifndef NDEBUG if (Dbg()) { Debugger.write(name_); Debugger.println('P'); } #endif return false; } // I tell the Sense routine that it doesn't need to bother after measuring // kLedMeterMax, which I assume is going to be greater than kCsThrH. uint16_t csval = cs_.Sense(); // Add a slight delay if we're using the debugging CLK line, to make // sure we didn't just clock in trash. This will timeout the // debugging board's SPI reader. if (sense_pin_ == kPinDbgSclk) delay(1); bool new_level = Schmitt(csval); #ifndef NDEBUG bool any_edge = new_level != state_.level; #endif bool rising_edge = new_level && !state_.level; state_.level = new_level; #ifndef NDEBUG if (csval > kCsThres && debug_led_latch_at_millis <= millis()) { Debugger.write('\\x0c'); debug_led_latch_at_millis = millis() + kDbgLedLatchDelayMs; } if (rising_edge) { count_++; Debugger.write('#'); Debugger.println(count_); } if (Dbg() || any_edge) { Debugger.write(name_); Debugger.write('F'); Debugger.print(cs_.floor_); Debugger.write('C'); Debugger.print(csval); Debugger.write(new_level ? '*' : '_'); Debugger.write(rising_edge ? '*' : '_'); Debugger.println(); } #endif #if !defined(NDEBUG) && (defined(LED_CAP) || defined(LED_METER_START) || defined(LED_SCHMITT)) if (state_.led_diagnostic) { #ifdef LED_CAP long brightval = constrain(map(csval, 0, kLedMeterMax, 0, bright), 0, bright); leds.setPWM(LED_CAP, brightval); #endif #ifdef LED_SCHMITT TwinkleBool(LED_SCHMITT, triggered); #endif #ifdef LED_METER_START float meter_value = static_cast(csval) * kLedMeterCount / kLedMeterMax; for (uint16_t ledno = 0; ledno < kLedMeterCount; ledno++) { if (meter_value < ledno) { TwinkleBool(LED_METER_START + ledno, false); } else if (meter_value >= ledno + 1) { TwinkleBool(LED_METER_START + ledno, true); } else { uint16_t pwm = bright * (meter_value - ledno); leds.setPWM(LED_METER_START + ledno, pwm); } } #endif leds.write(); } #endif // !NDEBUG && (LED_CAP || LED_METER_START || LED_SCHMITT) return rising_edge; } // Only call this in the POST; I haven't reviewed the CapacitiveSensor // library to tell whether this will mess with the pin state it uses. // (I did review the constructor.) // Note that this will POST with code to code+3, depending on the // failure mode. (I haven't allocated all of these failure codes.) void __attribute__((always_inline)) CapOrnament::PostOneWay(uint8_t code, bool val) { pinMode(sense_pin_, INPUT); digitalWrite(kPinCsChg, val); delay(1); if (digitalRead(sense_pin_) != val) { PostFail(code, name_); set_offline(true); } } void CapOrnament::Post(uint8_t code) { PostOneWay(code, HIGH); PostOneWay(code + 1, LOW); } CapOrnament csBrightUp('+', kPinCsO2S); CapOrnament csBrightDn('-', kPinCsO1S); CapOrnament csJoy('J', kPinCsO3S); CapOrnament csOnOff('O', kPinCsO4S); CapOrnament csPeace('P', kPinCsO5S); CapOrnament csLove('L', kPinCsO6S); uint16_t LedPctToPwm(float pct) { pct = constrain(pct, 0.0, 1.0); // I use a gamma of 3, since I don't need this to be terribly good, // and a gamma of 3 can be implemented without needing pow() (which // takes a lot of space). pct *= bright_pct; return leds.kPwmMax * pct * pct * pct; } void UpdateBrightnessFromPct() { // We keep bright_pct over 0 to prevent this from having an apparent // malfunction (that would persist once it writes to EEPROM) if // somebody holds it by the ""BRIGHT-"" button. 0.15 is about the // minumum to ensure that the RGB LED is always on regardless of // mode. bright_pct = constrain(bright_pct, 0.15, 1.0); bright = LedPctToPwm(1.0); Debugger.write('B'); Debugger.println(bright); } void LedAll(uint16_t value) { for (uint16_t i = 0; i < 24; i++) { leds.setPWM(i, value); } leds.write(); } #ifndef NDEBUG void LedFastBurn() { // See if we can turn all the LEDs on at once. digitalWrite(kPinLedBlank, HIGH); delay(20); LedAll(bright); digitalWrite(kPinLedBlank, LOW); delay(3000); } void LedSlowBurn() { // (To be used to turn up the LEDs slowly during startup) // Turn off all LEDs before deasserting BLANK; the PWM controller // often sees them as all on during startup, and when it // immediately turns them on, it messes with our voltage and // causes a BOR. // We don't clear them intially, since our caller does that. digitalWrite(kPinLedBlank, LOW); // Turn them on slowly. for (uint16_t i = 0; i < 24; i++) { leds.setPWM(i, bright); leds.write(); delay(10); } } #endif // NDEBUG #ifndef NDEBUG // Various startup functions can be requested by holding a finger on // ON/OFF at the same time as a different pad during reset. This probes // for those. bool ProbeForStartupMode(uint8_t pin) { // Normally, the setup will be: // ON/OFF ---/\\/\\/\\--- Charge ---/\\/\\/\\--- Pin // Both resistors are 1M. We'll put one signal on ON/OFF and a // different one on Charge, and see which one gets sensed on Pin. // If a user is holding a finger between two of these, we'll see // ON/OFF; otherwise, we'll see Charge. bool rv = false; pinMode(kPinCsO4S, OUTPUT); // ON/OFF digitalWrite(kPinCsChg, LOW); digitalWrite(kPinCsO4S, HIGH); delay(1); if (digitalRead(pin)) { digitalWrite(kPinCsChg, HIGH); digitalWrite(kPinCsO4S, LOW); delay(1); if (!digitalRead(pin)) { rv = true; } } // Return the pins to their normal states. pinMode(pin, INPUT); return rv; } #endif void setup() { // Save the reset cause, and disable the watchdog. (We have to // clear MCUSR's WDT flag to disable the watchdog.) uint8_t old_mcusr = MCUSR; MCUSR = 0; wdt_disable(); #ifdef CANARY // Fill the canary space extern char *__bss_end; uint8_t *canary_ptr = (uint8_t *)&__bss_end; while (canary_ptr <= SP) *(canary_ptr++) = kStackCanaryVal; #endif // Blank the LEDs, since they're undefined at startup digitalWrite(kPinLedBlank, HIGH); pinMode(kPinLedBlank, OUTPUT); #ifndef NDEBUG // Set up the debugging output digitalWrite(kPinDbgSclk, LOW); //pinMode(kPinDbgSclk, OUTPUT); // Happens during the debugger write pinMode(kPinDbgMosi, OUTPUT); #endif // Read the EEPROM so we can get our initial brightness. Debugger.write('E'); EEPROM.get(0, persistent_data); if (persistent_data.uninitialized) { Debugger.println('-'); } else { Debugger.println('+'); bright_pct = persistent_data.bright_pct; display_mode = persistent_data.display_mode; joy_sub_mode = persistent_data.joy_sub_mode; } UpdateBrightnessFromPct(); Debugger.write('P'); leds.begin(); // FIXME During the POST, instead of halting operation, we should // make a visual indication and then recover (if possible). For // instance, if a particular touch sensor is inoperative, we should // just disable that sensor. // POST the reset cause Debugger.write('1'); if ((!(old_mcusr & 0x01)) && (old_mcusr != 0x02)) { // Often, the brown-out reset will be asserted on the first // boot along with the power-on reset. From what I can tell // from the datasheet, the power-on reset finishes above // Vcc=1.4V, while my BOR is programmed to 2.7V. So, if // power-on reset is still asserted, I don't check any of the // other reset causes. PostFail(1, old_mcusr); } // POST the fuses Debugger.write('3'); if ((CLKPR & 0x0f) != 0) { // Clock divider incorrect; set ""clock speed"" to ""8 MHz internal"" // and reburn bootloader. PostFail(3, CLKPR); } cli(); uint8_t fuse_low = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS); uint8_t fuse_high = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS); sei(); Debugger.write('5'); if (fuse_low != 0xe2) { // Other low fuse bits incorrect; probably reburn bootloader. PostFail(5, fuse_low); } Debugger.write('6'); if (fuse_high != 0xdd) { // I changed the fuse values in the ATtiny defaults in // ~/.arduino15/packages/attiny/hardware/avr/1.0.2/boards.txt // from 0xdf to 0xdd, which enables the brown-out detector and // sets it to 2.7V. (At 8 MHz, the ATtiny84A needs about // 2.5V.) // High fuse bits incorrect; probably reburn bootloader. // Also can use this, but I had problems with it on a // factory-fresh ATtiny84A: // avrdude -p t84 -c usbtiny -U hfuse:w:0xdd:m -u PostFail(6, fuse_high); } // We don't care about the extended fuse bit. // Set up the charge line so we can probe for the startup mode. // It will remain in OUTPUT mode for the duration of the program. pinMode(kPinCsChg, OUTPUT); #ifndef NDEBUG dev_mode = ProbeForStartupMode(kPinCsO3S); Debugger.print(dev_mode ? 'D' : 'd'); if (dev_mode) { led_stars = &led_stars_dev; } else { led_stars = &led_stars_norm; } #endif led_stars->Setup(); #if defined(ENABLE_DIM_MODE) && !defined(NDEBUG) // dim_mode determines the initial brightness (which is used for // the POST, and if the EEPROM is empty). bool dim_mode = ProbeForStartupMode(kPinCsO2S); Debugger.print(dim_mode ? 'B' : 'b'); if (dim_mode) { bright_pct = 0.25; UpdateBrightnessFromPct(); } #endif // POST the capacitive sensor path, testing for shorts and opens. // Note that these will POST with codes +0 or +1 depending on the // failure. Debugger.write('+'); csBrightUp.Post(8); Debugger.print('-'); csBrightDn.Post(12); #ifndef NDEBUG if (!dev_mode) { #endif Debugger.print('J'); csJoy.Post(16); Debugger.print('O'); csOnOff.Post(20); #ifndef NDEBUG } #endif Debugger.print('L'); csLove.Post(28); Debugger.print('P'); csPeace.Post(36); // FIXME We don't have any feedback from the LED driver. If we // connected its DOUT line to a GPIO, we could verify that we can // shift through it, but I don't want to waste a GPIO pin. // Only do the visible or slow tests in dev mode; otherwise, just // initialize to a blank display. leds.clear(); // This is mostly useful for testing how the power supply can manage // sudden demand changes, but it's also handy to get confirmation of // dev_mode. if (dev_mode) { // Test LEDs // In particular, I want to see if there's a voltage drop at Vcc // based on the LED power usage. If there's over about 4 ohms DC // resistance on the ground line that's shared with the LED return, // then the ground pin can go up and we hit our BOR threshold. The // PCB (as of rev 2 at least) has only 0.05 ohms on the ground line // between the PWM controller and the power regulator, but my // breadboard can hit 4 ohms pretty easily. (As of this writing, I // only get about a 0.16V drop between all LEDs on and all LEDs off, // but an earlier breadboard with a dodgy jumper got a 1V drop.) Debugger.write('S'); LedSlowBurn(); delay(1000); Debugger.write('F'); // See if we can turn all the LEDs on at once. digitalWrite(kPinLedBlank, HIGH); delay(1000); } digitalWrite(kPinLedBlank, LOW); #ifndef NDEBUG #ifdef LED_Q leds.setPWM(LED_Q, 0); #endif #ifdef LED_NQ leds.setPWM(LED_NQ, 0); #endif #ifdef LED_CONST00 leds.setPWM(LED_CONST00, 0); leds.setPWM(LED_CONST25, (bright+1)/4); leds.setPWM(LED_CONST50, (bright+1)/2); leds.setPWM(LED_CONST75, (3*(bright+1))/4); leds.setPWM(LED_CONST100, bright); #endif leds.write(); #endif // NDEBUG #ifndef NDEBUG if (dev_mode) csLove.set_led_diagnostic(true); #endif // NDEBUG wdt_enable(WDTO_8S); } float rgbphase; // Range is [0,3) static union { struct { float phase; int8_t direction; uint8_t cycle; uint8_t cycle_minor; } joy; struct { float star_brightness[kNumLedStarsMax]; float star_motion[kNumLedStarsMax]; uint8_t star_ramping_up[(kNumLedStarsMax+7)/8]; } peace_love; } display_state; #ifndef NDEBUG #define sanity() DoSanity(__LINE__) void DoSanity(int lineno __attribute__((unused))) { //if (/* whatever you're troubleshooting */) // AssertFail(lineno); } #else // !NDEBUG #define sanity() do {} while (0) #endif void __attribute__((noinline)) SetLoveRGBPin(uint8_t pin, float phase) { leds.setPWM(pin, LedPctToPwm( phase * kLoveStarMaxRamp * kLoveStarMaxRamp)); } void JoyCylonHandlePhaseLed() { display_state.joy.cycle++; if (display_state.joy.cycle == 8) // Blackout is unappealing; skip it display_state.joy.cycle = 1; leds.setPWM(LED_PHASE1, display_state.joy.cycle & 1 ? bright >> 2 : 0); leds.setPWM(LED_PHASE2, display_state.joy.cycle & 2 ? bright >> 2 : 0); leds.setPWM(LED_PHASE3, display_state.joy.cycle & 4 ? bright >> 2 : 0); } void RotateRgb() { // The RGB LED's phase goes through the half-open interval [0,3). // In each unit interval along there, two colors are on triangle // waves. This is much, much cheaper than doing cosine waves, // since I don't need to link in all the floating-point math // stuff! It also looks nice; if you've seen one of Adafruit's // sample ""rotating NeoPixel"" sketch that comes loaded in // CircuitPython from the factory, that's what it does; see // https://learn.adafruit.com/adafruit-circuit-playground-express/circuitpython-neopixel float phase_r, phase_g, phase_b; // Range is [0,1] if (rgbphase < 1.0) { phase_r = rgbphase; phase_g = 1.0 - rgbphase; phase_b = 0; } else if (rgbphase < 2.0) { phase_r = 2.0 - rgbphase; phase_g = 0; phase_b = rgbphase - 1.0; } else { phase_r = 0; phase_g = rgbphase - 2.0; phase_b = 3.0 - rgbphase; } rgbphase += display_mode == kModePeace ? kPhaseIncrPeace : kPhaseIncr; // The color wheel looks better if we don't do the gamma // correction here. However, we do back off by a constant factor, // since the RGB LED is otherwise too bright for comfort. The // constant is different depending on the mode, since the ramp on // Peace mode is twice as high as the ramp on Love mode. float rgb_backoff = display_mode == kModePeace ? 0.4 : 0.2; leds.setPWM(LED_PHASE1, phase_r * rgb_backoff * bright); leds.setPWM(LED_PHASE2, phase_g * rgb_backoff * bright); leds.setPWM(LED_PHASE3, phase_b * rgb_backoff * bright); if (rgbphase >= 3.0) rgbphase -= 3.0; } void loop() { wdt_reset(); static uint8_t loop_count; loop_count++; #ifndef NDEBUG CapOrnament::SweepDbgSensor(); #endif bool bright_down_edge = csBrightDn.SenseEdge(); bool bright_up_edge = csBrightUp.SenseEdge(); bool bright_down_level = csBrightDn.level(); bool bright_up_level = csBrightUp.level(); if (bright_down_level || bright_up_level) { if (bright_down_edge) bright_pct -= kBrightChangeRate * 3; if (bright_down_level) bright_pct -= kBrightChangeRate; if (bright_up_edge) bright_pct += kBrightChangeRate * 3; if (bright_up_level) bright_pct += kBrightChangeRate; UpdateBrightnessFromPct(); update_persistent_data_at_millis = millis() + 2000; } bool toggle_onoff = csOnOff.SenseEdge(); if (toggle_onoff) { static bool blank_state = false; blank_state = !blank_state; digitalWrite(kPinLedBlank, blank_state); Debugger.println(blank_state ? 'o' : 'O'); } bool gotLove = csLove.SenseEdge(); bool gotJoy = csJoy.SenseEdge(); bool gotPeace = csPeace.SenseEdge(); // We always reset the display, even if we're in the right mode, to // give visual feedback to the user. Otherwise, the user might // start fiddling with buttons by pressing the current mode and // think that the button does nothing. if (gotLove) { display_mode = kModeLove; } else if (gotPeace) { display_mode = kModePeace; } else if (gotJoy) { if (display_mode == kModeJoy) { joy_sub_mode = static_cast(static_cast(joy_sub_mode) + 1); if (joy_sub_mode == kSubModeLast) { joy_sub_mode = static_cast(0); } } display_mode = kModeJoy; } if (gotLove || gotPeace || gotJoy) { MyMemSet(&display_state, sizeof(display_state), 0); #if 0 // This doesn't work yet if (display_mode != kModeJoy) { // Filling a float16 with the byte 0x38 works out to about .5; // the byte 0x21 is about 0.01. static_assert(sizeof(display_state.peace_love.star_brightness) == sizeof(display_state.peace_love.star_motion), ""size mismatch""); for (uint8_t i = 0; i < sizeof(display_state.peace_love.star_brightness); i++) { static_cast(static_cast(&display_state.peace_love.star_brightness))[i] = 0x38; static_cast(static_cast(&display_state.peace_love.star_motion))[i] = 0x21; } MyMemSet(&display_state.peace_love.star_ramping_up, sizeof(display_state.peace_love.star_ramping_up), 0x55); } #endif persistent_data.display_mode = display_mode; persistent_data.joy_sub_mode = joy_sub_mode; update_persistent_data_at_millis = millis() + 2000; } #ifdef LED_CYCLE if (dev_mode) leds.setPWM(LED_CYCLE, (loop_count & 1) ? 0 : bright); #endif if (display_mode == kModeJoy) { auto by_pos = led_stars->by_pos(); switch (joy_sub_mode) { case kSubModeDoubleChase: { for (uint16_t i = 0; i < led_stars->Count(); i++) { uint8_t i_8bit = i * 256 / led_stars->Count(); // Compute the absolute value of i_8bit - cycle uint8_t mag_major = i_8bit - display_state.joy.cycle; if (mag_major & 0x80) mag_major = ~mag_major; uint8_t mag_minor = i_8bit - display_state.joy.cycle_minor; if (mag_minor & 0x80) mag_minor = ~mag_minor; // mag_major and mag_minor now hold 7 bits of data each. It's // a little tricky to do gamma correction in integer space // without losing too much precision. Unfortunately, 32-bit // arithmetic is quite expensive on an AVR, and 16-bit only // slightly less so. Our inputs are only 8 bits, so we're ok // with some loss of magnitude precision during this stage, // as long as we don't lose it all up-front. uint8_t bright_8bit = bright / 16; // 0-255 uint16_t mag_14bit = mag_major * mag_minor; // 0-16129 uint16_t mag_gamma = mag_14bit / 64; // 0-252 mag_gamma *= bright_8bit; // 0-64260 mag_gamma /= 256; // 0-251 mag_gamma *= bright_8bit; // 0-64005 uint16_t pwm = mag_gamma / 16; // 0-4000 uint8_t ledno = by_pos[i]; leds.setPWM(ledno, pwm); } #if 1 RotateRgb(); #else // This version is about 230-240 bytes, so I'm just using // RotateRgb(). // This pretty much sets LED_PHASE1 to cycle^2 * bright^2, // scaled accordingly and in stages to prevent overflow. uint8_t bright15 = bright / 256; // 0-15 bright15 *= bright15; // 0-225 bright15 /= 16; // 0-14 bright15 += 2; // 2-16 uint16_t phase1 = ((display_state.joy.cycle * bright15) // 0-4080 / 16) // 0-255 * (display_state.joy.cycle / 8); // 0-8128 // Then, the sawtooth is transformed to a triangle: values // above the brightness become a descending value within the // brightness. if (phase1 > bright * 2) phase1 = bright; else if (phase1 > bright) phase1 = (bright * 2) - phase1; // We scale back the brightness since the RGB LED is pretty // bright. leds.setPWM(LED_PHASE1, phase1 / 4); // LED_PHASE2 is similar to LED_PHASE1, but uses cycle_minor. uint16_t phase2 = ((display_state.joy.cycle_minor * bright15) / 16) * (display_state.joy.cycle_minor / 8); if (phase2 > bright * 2) phase2 = bright; else if (phase2 > bright) phase2 = (bright * 2) - phase2; leds.setPWM(LED_PHASE2, phase2 / 4); // LED_PHASE3 roughly inverts the other two phases. uint16_t phase3 = bright - ((phase1 + phase2) / 2); leds.setPWM(LED_PHASE3, phase3 / 4); #endif display_state.joy.cycle += 1; display_state.joy.cycle_minor -= 2; } break; case kSubModeCylon: case kSubModeCylonFill: { for (int i = 0; i < led_stars->Count(); i++) { float pct; if (joy_sub_mode == kSubModeCylon) { pct = 1.0 - abs(display_state.joy.phase - i); } else { pct = constrain(display_state.joy.phase - i, 0, 1); if (display_state.joy.direction) { pct = 1.0 - pct; } } int ledno = by_pos[i]; leds.setPWM(ledno, LedPctToPwm(pct)); } if (joy_sub_mode == kSubModeCylon) { display_state.joy.phase += (display_state.joy.direction ? 0.6 : -0.6); if (display_state.joy.direction == 1 && display_state.joy.phase >= led_stars->Count() - 1) { display_state.joy.direction = 0; display_state.joy.phase = led_stars->Count() - 1; JoyCylonHandlePhaseLed(); } else if (display_state.joy.direction == 0 && display_state.joy.phase <= 0) { display_state.joy.direction = 1; display_state.joy.phase = 0; JoyCylonHandlePhaseLed(); } } else { display_state.joy.phase += 0.6; if (display_state.joy.phase >= led_stars->Count() - 1) { display_state.joy.direction = !display_state.joy.direction; display_state.joy.phase = 0; JoyCylonHandlePhaseLed(); } } } break; case kSubModeLast: // CANTHAPPEN break; } } else { // PEACE and LOVE modes are handled by mostly-common code. RotateRgb(); for (int i = 0; i < led_stars->Count(); i++) { bool swap_direction = random(kLedStarPeriod) == 0; if ((display_state.peace_love.star_ramping_up[i/8] & (1<<(i%8)))) { display_state.peace_love.star_brightness[i] += display_state.peace_love.star_motion[i]; if (display_state.peace_love.star_brightness[i] >= 1.0) { display_state.peace_love.star_brightness[i] = 1.0; swap_direction = true; } } else { display_state.peace_love.star_brightness[i] -= display_state.peace_love.star_motion[i]; if (display_state.peace_love.star_brightness[i] <= 0) { display_state.peace_love.star_brightness[i] = 0; swap_direction = true; } } if (swap_direction) { display_state.peace_love.star_motion[i] = RandomFloat(kLedStarDeltaMotion) + kLedStarMinMotion; display_state.peace_love.star_ramping_up[i/8] ^= 1 << (i%8); } } auto by_color = led_stars->by_color(); if (display_mode == kModePeace) { // In kModePeace, the goal is to not be distracting in a room // while you're reading a book or something. One part of that // is that we have each color have a constant total // illumination. FIXME We should do the averaging after gamma // correction (i.e., in PWM space) since the gamma correction is // only for human perception issues; with PWM modulation, LEDs // are (I think) pretty linear in actual power output. auto color_counts = led_stars->color_counts(); uint8_t color_idx_ofs = 0; for (int color = 0; color < kNumLedColors; color++) { uint8_t color_count = color_counts[color]; float total = 0; for (uint8_t star_idx = 0; star_idx < color_count; star_idx++) { float pct = display_state.peace_love.star_brightness[ color_idx_ofs + star_idx]; total += pct; } float bias = (color_count * 0.5 - total) / color_count; for (uint8_t star_idx = 0; star_idx < color_count; star_idx++) { float pct = display_state.peace_love.star_brightness[ color_idx_ofs + star_idx]; pct += bias; uint8_t ledno = by_color[star_idx + color_idx_ofs]; uint16_t pwm = LedPctToPwm(pct); leds.setPWM(ledno, pwm); } color_idx_ofs += color_count; } } else { // kModeLove for (int i = 0; i < led_stars->Count(); i++) { bool burst = random(kLedStarBurstPeriod) == 0; uint16_t half_bright = bright >> 1; uint16_t pwm; if (burst) { pwm = random(half_bright, bright); } else { uint16_t nominal = LedPctToPwm( kLoveStarMaxRamp * display_state.peace_love.star_brightness[i]); uint16_t half_nominal = nominal >> 1; pwm = random(half_nominal) + half_nominal; if (nominal < half_bright) { pwm += half_nominal; } } int ledno = by_color[i]; leds.setPWM(ledno, pwm); } } } // kModePeace and kModeLove #ifndef NDEBUG if (dev_mode) { #ifdef LED_Q TwinkleBool(LED_Q, CapOrnament::count() % 2); #endif #ifdef LED_NQ TwinkleBool(LED_NQ, !(CapOrnament::count() % 2)); #endif #ifdef LED_COUNT4 TwinkleBool(LED_COUNT4, CapOrnament::count() & 0x10); #endif #ifdef LED_COUNT3 TwinkleBool(LED_COUNT3, CapOrnament::count() & 0x08); #endif #ifdef LED_COUNT2 TwinkleBool(LED_COUNT2, CapOrnament::count() & 0x04); #endif #ifdef LED_COUNT1 TwinkleBool(LED_COUNT1, CapOrnament::count() & 0x02); #endif #ifdef LED_COUNT0 TwinkleBool(LED_COUNT0, CapOrnament::count() & 0x01); #endif } #endif //NDEBUG leds.write(); if (update_persistent_data_at_millis < millis()) { persistent_data.uninitialized = false; persistent_data.bright_pct = bright_pct; Debugger.println('E'); EEPROM.put(0, persistent_data); update_persistent_data_at_millis = ULONG_MAX; } #ifdef CANARY // Check the canary space if (loop_count % kStackCanarySweepFreq == 0) { extern char *__bss_end; extern uint8_t __stack; uint8_t *canary_ptr = (uint8_t *)&__bss_end; uint16_t canary_bytes = 0; while (*canary_ptr == kStackCanaryVal && canary_ptr <= (uint8_t *)&__stack) { canary_ptr++; canary_bytes++; } Debugger.write('C'); Debugger.println(canary_bytes); assert(canary_bytes > 8); } #endif #if 0 if (loop_count % 8 == 0) { for (int i = 0; i < 24; i++) { Debugger.print(i); Debugger.write(':'); Debugger.println(leds.pwmbuffer[i]); } } #endif sanity(); } // Local Variables: // compile-command: ""arduino --upload --board attiny:avr:ATtinyX4:cpu=attiny84,clock=internal8 --preserve-temp-files --pref build.path=build/ christmas-tree.ino -v"" // End: ",12463,False,2134.838311944937,median "//LIST OF COMMANDS TO CHANGE COMPASS UPDATE RATE //compass.writeMagReg(LSM303_1::CRA_REG_M, 0x18); //75Hz Update Rate //compass.writeMagReg(LSM303::CRA_REG_M, 0x14); //30Hz Update Rate //compass.writeMagReg(LSM303::CRA_REG_M, 0x0C); //Default 7.5Hz Update Rate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Calibration Menu Setup and Handler ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // void CalibrateMenuSetup() { drawStatusBar(""Calibration""); drawInfoBar(""""); btn1 = ctGUI.addButton(20,33,280,66,BUTTON_STD,""COMPASS CALIBRATION"",caveatron.FONT_22,optVisible,1); btn2 = ctGUI.addButton(20,114,280,66,BUTTON_STD,""Check Azimuth Calibration"",caveatron.FONT_22,optVisible,2); btn3 = ctGUI.addButton(20,195,280,66,BUTTON_STD,""View Calibration Values"",caveatron.FONT_22,optVisible,3); btn4 = ctGUI.addButton(20,276,280,66,BLACK_STD,""Advanced Calibration"", ""For Expert Use Only"",caveatron.FONT_22,optVisible,4); ctGUI.addButton(20,357,280,84,BLUE_STD,""RETURN TO SETTINGS"",caveatron.FONT_28,optVisible,5); } void CalibrateMenuHandler(int URN) { switch (URN) { case 1: //User Compass Calibration CreateScreen(screenCompassCalibrate); break; case 2: //Check if Azimuth Calibration is Good CreateScreen(screenCheckCalibration); break; case 3: //View Compass Calibration Parameters ViewCalParameters(); break; case 4: //Advanced Calibration - for system setup and verification currentMode = modeRawLive; CreateScreen(screenAdvancedCal); break; case 5: //Exit guiStep--; currentMode = modeNull; CreateScreen(screenSettingsMenu); break; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // User Compass Calibration Routines ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // void CompassCalibrateSetup() { drawStatusBar(""Compass Calibration""); drawInfoBar(""""); btn1 = ctGUI.addButton(20,145,280,200,GREEN_DRK,""START"", ""CALIBRATION"", caveatron.FONT_28, optVisible, 1); pbar1 = ctGUI.addProgressBar(20,300,280,40,64,""Points Collected"", caveatron.FONT_22, WHITE_STD, optInvisible, 2); pbar2 = ctGUI.addProgressBar(20,300,280,40,4040,""Time Remaining"", caveatron.FONT_22, WHITE_STD, optInvisible, 3); btn4 = ctGUI.addButton(20,145,280,200,GREEN_DRK,""CONTINUE"", ""CALIBRATION"", caveatron.FONT_28, optInvisible, 4); btn2 = ctGUI.addButton(20,364,130,84,RED_DRK,""CANCEL"",caveatron.FONT_22, optVisible, 5); btn3 = ctGUI.addButton(170,364,130,84,BLUE_STD,""SAVE"",""& EXIT"",caveatron.FONT_22, optInvisible, 6); myGLCD.setColor(YELLOW_STD); myGLCD.setBackColor(BLACK_STD); ctGUI.print(""Step 1: Find Mag Center"", 160, 30, caveatron.FONT_22, 2, CENTER_J); ctGUI.print(""Continuously rotate box in"", 160, 55, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""all possible orientations"", 160, 75, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""to keep blue progress bar"", 160, 95, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""full as long as possible"", 160, 115, caveatron.FONT_19, 2, CENTER_J); } void CompassCalibrateHandler(int URN) { switch (URN) { case 1: //Start Calibration - Step 1: Find approximate center of magnetic sphere ctGUI.makeObjectInvisible(btn1); ctGUI.makeObjectInvisible(btn2); //theFile.open(""EIGDATA.TXT"", O_RDWR | O_CREAT | O_AT_END); //theFile.println(""**********"");theFile.println(""NEW DATASET""); ctGUI.print(""FINDING CENTER..."", 160, 200, caveatron.FONT_34, 3, CENTER_J, YELLOW_STD, BLACK_STD); ctGUI.print(""Center:"", 20, 380, caveatron.FONT_19, 2, LEFT_J, YELLOW_STD, BLACK_STD); ctGUI.makeObjectVisible(pbar2); Timer4.stop(); ctGUI.updateProgressBar(pbar2, 4000); BuzzerBEEP(800, 200); delay(1300); FindMagSphereCenter(); myGLCD.setColor(BLACK_STD); myGLCD.fillRect(20,30,300,415); ctGUI.makeObjectInvisible(pbar2); ctGUI.makeObjectVisible(btn2); ctGUI.makeObjectVisible(btn4); myGLCD.setColor(YELLOW_STD); myGLCD.setBackColor(BLACK_STD); BuzzerBEEP(800, 200); ctGUI.print(""Step 2: Get Calibration Pts"", 160, 30, caveatron.FONT_22, 2, CENTER_J); ctGUI.print(""Continuously rotate box in"", 160, 55, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""all possible orientations"", 160, 75, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""to fill blue progress bar"", 160, 95, caveatron.FONT_19, 2, CENTER_J); Timer4.start(); break; case 4: //Continue Calibration - Step 2: Gather the hard and soft iron data, calculate the eigenvectors, and soft for the coefficients ctGUI.makeObjectInvisible(btn4); ctGUI.makeObjectInvisible(btn2); //theFile.open(""EIGDATA.TXT"", O_RDWR | O_CREAT | O_AT_END); //theFile.println(""**********"");theFile.println(""NEW DATASET""); ctGUI.print(""CALIBRATING..."", 160, 200, caveatron.FONT_34, 3, CENTER_J, YELLOW_STD, BLACK_STD); ctGUI.makeObjectVisible(pbar1); Timer4.stop(); BuzzerBEEP(800, 200); delay(1300); EigenCalibration(); myGLCD.setColor(BLACK_STD); myGLCD.fillRect(20,30,300,235); ctGUI.makeObjectVisible(btn2); ctGUI.makeObjectVisible(btn3); myGLCD.setBackColor(BLACK_STD); myGLCD.setColor(YELLOW_STD); ctGUI.print(""Hard Iron Calibration"", 160, 40, caveatron.FONT_22, 2, CENTER_J); ctGUI.print(""Soft Iron Calibration"", 160, 150, caveatron.FONT_22, 2, CENTER_J); ctGUI.print(""X="", 80, 70, caveatron.FONT_19, 2, LEFT_J); ctGUI.print(""Y="", 80, 90, caveatron.FONT_19, 2, LEFT_J); ctGUI.print(""Z="", 80, 110, caveatron.FONT_19, 2, LEFT_J); myGLCD.setColor(WHITE_STD); ctGUI.printNumF(hardIronCal[0], 4, 240, 70, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(hardIronCal[1], 4, 240, 90, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(hardIronCal[2], 4, 240, 110, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(softIronCal[0], 6, 5, 180, caveatron.FONT_19, 2, LEFT_J); ctGUI.printNumF(softIronCal[1], 6, 160, 180, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumF(softIronCal[2], 6, 315, 180, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(softIronCal[3], 6, 5, 200, caveatron.FONT_19, 2, LEFT_J); ctGUI.printNumF(softIronCal[4], 6, 160, 200, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumF(softIronCal[5], 6, 315, 200, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(softIronCal[6], 6, 5, 220, caveatron.FONT_19, 2, LEFT_J); ctGUI.printNumF(softIronCal[7], 6, 160, 220, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumF(softIronCal[8], 6, 315, 220, caveatron.FONT_19, 2, RIGHT_J); BuzzerBEEP(800, 1000); Timer4.start(); break; case 6: //Save & Exit SaveCalibration(); case 5: //Cancel guiStep--; currentMode = modeNull; CreateScreen(screenSettingsMenu); break; } } //FIND CENTER OF MAGNETIC SPHERE FOR HARD AND SOFT IRON CALIBRATION void FindMagSphereCenter() { int16_t running_min[3] = {32767, 32767, 32767}, running_max[3] = {-32768, -32768, -32768}, running_center[3] = {0, 0, 0}, last_running_center[3] = {0, 0, 0}; int lastChangeTime = millis(); //Look for new min and max magnetic values. If more than 4 sec since last new min and max, end collection while ((millis() - lastChangeTime) < 4000) { caveatron.IMU_Read(); running_min[0] = min(running_min[0], caveatron.IMU_m_x); running_min[1] = min(running_min[1], caveatron.IMU_m_y); running_min[2] = min(running_min[2], caveatron.IMU_m_z); running_max[0] = max(running_max[0], caveatron.IMU_m_x); running_max[1] = max(running_max[1], caveatron.IMU_m_y); running_max[2] = max(running_max[2], caveatron.IMU_m_z); //Update x,y,z center estimate from min and max for (int i=0; i<3; i++) { last_running_center[i] = running_center[i]; running_center[i] = running_max[i] - ((running_max[i]-running_min[i])/2); ctGUI.printNumI(running_center[i], 100+75*i, 380, caveatron.FONT_19, 2, LEFT_J, WHITE_STD, BLACK_STD); } //Check for change in center values since last reading and if so, reset time counter if ((running_center[0] != last_running_center[0]) || (running_center[1] != last_running_center[1]) || (running_center[2] != last_running_center[2])) { lastChangeTime = millis(); } ctGUI.updateProgressBar(pbar2, 4000-(millis()-lastChangeTime)); } for (int i=0; i<3; i++) sphereCenter[i] = running_center[i]; } //HARD AND SOFT IRON CALIBRATION ROUTINE void EigenCalibration() { int calNumCount=0; int combo=-1, combo_sector=-1, XAxis, YAxis, ZAxis; int s=1000; float p; int sphereSectorCount[8]; for(int i=0;i<8;i++) sphereSectorCount[i]=8; /*int sphereSectorCount[8][4]; for(int i=0;i<8;i++) for(int j=0;j<4;j++) sphereSectorCount[i][j]=2;*/ //Initialize Matrices ArrayXf x(64,1); ArrayXf y(64,1); ArrayXf z(64,1); MatrixXf D(64,9); /*ArrayXf x(40,1); ArrayXf y(40,1); ArrayXf z(40,1); MatrixXf D(40,9);*/ MatrixXf VA(9,9); MatrixXf VB(9,1); MatrixXf V(9,1); MatrixXf A(4,4); MatrixXf CA(3,3); MatrixXf CB(3,1); MatrixXf C(3,1); MatrixXf T(4,4); MatrixXf R(4,4); MatrixXf E(3,3); MatrixXf EVEC(3,3); MatrixXf RADII(3,1); MatrixXf SCALE(3,3); MatrixXf SOFTIRON(3,3); // Find points around sphere and load array for calibration // The objective is to obtain a roughly equal distribution of points around the magnetic sphere while (calNumCount<64) { //while (calNumCount<40) { delay(200); caveatron.IMU_Read(); XAxis = caveatron.IMU_m_x; YAxis = caveatron.IMU_m_y; ZAxis = caveatron.IMU_m_z; //Subdivide sphere into 8 quadrants and detemine which quadrant new point falls within if ((XAxis > sphereCenter[0]) && (YAxis > sphereCenter[1]) && (ZAxis > sphereCenter[2])) combo = 0; if ((XAxis > sphereCenter[0]) && (YAxis > sphereCenter[1]) && (ZAxis < sphereCenter[2])) combo = 1; if ((XAxis > sphereCenter[0]) && (YAxis < sphereCenter[1]) && (ZAxis > sphereCenter[2])) combo = 2; if ((XAxis > sphereCenter[0]) && (YAxis < sphereCenter[1]) && (ZAxis < sphereCenter[2])) combo = 3; if ((XAxis < sphereCenter[0]) && (YAxis > sphereCenter[1]) && (ZAxis > sphereCenter[2])) combo = 4; if ((XAxis < sphereCenter[0]) && (YAxis > sphereCenter[1]) && (ZAxis < sphereCenter[2])) combo = 5; if ((XAxis < sphereCenter[0]) && (YAxis < sphereCenter[1]) && (ZAxis > sphereCenter[2])) combo = 6; if ((XAxis < sphereCenter[0]) && (YAxis < sphereCenter[1]) && (ZAxis < sphereCenter[2])) combo = 7; //Subdivide each quadrant into 4 sectors and determine which sector the point falls within if (XAxis > YAxis) { if (ZAxis > XAxis) combo_sector = 1; else combo_sector = 0; } else { if (ZAxis > YAxis) combo_sector = 3; else combo_sector = 2; } // Bad data filter - reject out of bounds (not used at this time) /*int Hyp = sqrt(ZAxis*ZAxis + YAxis*YAxis + XAxis*XAxis); if ( (Hyp > (caveatron.IMU_hypmax)) || (Hyp < (caveatron.IMU_hypmin)) ) combo =-1; if ( (abs(XAxis) > caveatron.IMU_hypUbound) || (abs(YAxis) > caveatron.IMU_hypUbound) || (abs(ZAxis) > caveatron.IMU_hypUbound)) combo =-1;*/ //We want to get 8 points within each quadrant for 64 total points //Optional approach for getting finer point distribution by subdividing each quandrant into 4 sector /*if ((combo>=0)&&(combo_sector>=0)) { if (sphereSectorCount[combo][combo_sector]>0) { x(calNumCount) = XAxis; y(calNumCount) = YAxis; z(calNumCount) = ZAxis; //theFile.print(XAxis);theFile.print(""\\t"");theFile.print(YAxis);theFile.print(""\\t"");theFile.println(ZAxis); sphereSectorCount[combo][combo_sector]--; calNumCount++; ctGUI.updateProgressBar(pbar1, calNumCount); } }*/ if (combo>=0) { if (sphereSectorCount[combo]>0) { x(calNumCount) = XAxis; y(calNumCount) = YAxis; z(calNumCount) = ZAxis; //theFile.print(XAxis);theFile.print(""\\t"");theFile.print(YAxis);theFile.print(""\\t"");theFile.println(ZAxis); sphereSectorCount[combo]--; calNumCount++; ctGUI.updateProgressBar(pbar1, calNumCount); } } } // Perform the eigenvector computation D << x * x, y * y, z * z, 2 * (x * y), 2 * (x * z), 2 * (y * z), 2 * x, 2 * y, 2 * z; D = D/s; VA = ( D.transpose() * D ); VB = ( D.transpose() * VectorXf::Ones(64)); V = VA.lu().solve(VB); A << V(0),V(3),V(4),V(6), V(3),V(1),V(5),V(7), V(4),V(5),V(2),V(8), V(6),V(7),V(8),-s; CA = -A.topLeftCorner(3,3); CB << V(6),V(7),V(8); C = CA.lu().solve(CB); //Hard Iron Result T << 1,0,0,0, 0,1,0,0, 0,0,1,0, C(0),C(1),C(2),1; R = T * A * T.transpose(); E = R.topLeftCorner(3,3)/R(3,3); EigenSolver eigensolver(E); MatrixXf EVE = eigensolver.pseudoEigenvectors(); MatrixXf EVA = eigensolver.pseudoEigenvalueMatrix(); RADII << sqrt(-1/EVA(2,2)), sqrt(-1/EVA(0,0)), sqrt(-1/EVA(1,1)); EVEC << -EVE.col(2), EVE.col(0), -EVE.col(1); float r_min = RADII.minCoeff(); SCALE << (1/RADII(0))*r_min,0,0, 0,(1/RADII(1))*r_min,0, 0,0,(1/RADII(2))*r_min; SOFTIRON = EVEC * SCALE * EVEC.transpose(); //Soft Iron Result for (int i=0; i<3; i++) { hardIronCal[i] = C(i); for (int j=0; j<3; j++) softIronCal[3*i+j] = SOFTIRON(i, j); } } // View Current Hard & Soft Iron User Calibration Parameters void ViewCalParameters() { ctGUI.makeObjectInvisible(btn1); ctGUI.makeObjectInvisible(btn2); ctGUI.makeObjectInvisible(btn3); ctGUI.makeObjectInvisible(btn4); myGLCD.setBackColor(BLACK_STD); myGLCD.setColor(YELLOW_STD); ctGUI.print(""Hard Iron Calibration"", 160, 40, caveatron.FONT_22, 2, CENTER_J); ctGUI.print(""Soft Iron Calibration"", 160, 150, caveatron.FONT_22, 2, CENTER_J); ctGUI.print(""X="", 80, 70, caveatron.FONT_19, 2, LEFT_J); ctGUI.print(""Y="", 80, 90, caveatron.FONT_19, 2, LEFT_J); ctGUI.print(""Z="", 80, 110, caveatron.FONT_19, 2, LEFT_J); myGLCD.setColor(WHITE_STD); ctGUI.printNumF(hardIronCal[0], 4, 240, 70, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(hardIronCal[1], 4, 240, 90, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(hardIronCal[2], 4, 240, 110, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(softIronCal[0], 6, 5, 180, caveatron.FONT_19, 2, LEFT_J); ctGUI.printNumF(softIronCal[1], 6, 160, 180, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumF(softIronCal[2], 6, 315, 180, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(softIronCal[3], 6, 5, 200, caveatron.FONT_19, 2, LEFT_J); ctGUI.printNumF(softIronCal[4], 6, 160, 200, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumF(softIronCal[5], 6, 315, 200, caveatron.FONT_19, 2, RIGHT_J); ctGUI.printNumF(softIronCal[6], 6, 5, 220, caveatron.FONT_19, 2, LEFT_J); ctGUI.printNumF(softIronCal[7], 6, 160, 220, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumF(softIronCal[8], 6, 315, 220, caveatron.FONT_19, 2, RIGHT_J); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // **** CHECK CURRENT AZIMUTH CALIBRATION TO SEE IF IT IS STILL GOOD **** // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // void CheckCalibrationSetup() { drawStatusBar(""Check Azi Calibration""); drawInfoBar(""""); btn1 = ctGUI.addButton(20,145,280,200,GREEN_DRK,""START"", ""CALIBRATION CHECK"", caveatron.FONT_28, optVisible, 1); pbar1 = ctGUI.addProgressBar(20,300,280,40,95,""Time Remaining:"", caveatron.FONT_22, WHITE_STD, optInvisible, 3); btn2 = ctGUI.addButton(20,364,130,84,RED_DRK,""CANCEL"",caveatron.FONT_22, optVisible, 5); btn3 = ctGUI.addButton(20,364,280,84,BLUE_STD,""DONE"",caveatron.FONT_22, optInvisible, 6); myGLCD.setColor(YELLOW_STD); myGLCD.setBackColor(BLACK_STD); ctGUI.print(""Rotate box, holding level,"", 160, 30, caveatron.FONT_22, 2, CENTER_J); ctGUI.print(""slowly in a full circle"", 160, 55, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""Time rotation to take"", 160, 75, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""about 8 seconds."", 160, 95, caveatron.FONT_19, 2, CENTER_J); } void CheckCalibrationHandler(int URN) { switch (URN) { case 1: //Record 1000 Raw Magnetometer and Accelerometer Readings ctGUI.makeObjectInvisible(btn1); ctGUI.makeObjectInvisible(btn5); ctGUI.print(""PERFORM ROTATION"", 160, 200, caveatron.FONT_28, 3, CENTER_J, YELLOW_STD, BLACK_STD); ctGUI.makeObjectVisible(pbar1); Timer4.stop(); delay(500); BuzzerBEEP(800, 200); delay(500); CheckCalibration(); ctGUI.makeObjectVisible(btn6); Timer4.start(); break; case 5: //Cancel case 6: //Done guiStep--; currentMode = modeNull; CreateScreen(screenCalibrate); break; } } void CheckCalibration() { float mgeo[96]; float sqDevSum = 0.0; float sumVals = 0; float deltaMax = 0; //Calibration Parameters for hard and soft iron float mcc11 = softIronCal[0]; float mcc12 = softIronCal[1]; float mcc13 = softIronCal[2]; float mcc21 = softIronCal[3]; float mcc22 = softIronCal[4]; float mcc23 = softIronCal[5]; float mcc31 = softIronCal[6]; float mcc32 = softIronCal[7]; float mcc33 = softIronCal[8]; float mb1 = hardIronCal[0]; float mb2 = hardIronCal[1]; float mb3 = hardIronCal[2]; for (int i=0; i<96; i++) { GetCompassReading(); float mroll = measureRoll(0); //Correct mag values for hard and soft iron effects and misalignment float mx = mcc11*(caveatron.IMU_m_x-mb1) + mcc12*(caveatron.IMU_m_y-mb2) + mcc13*(caveatron.IMU_m_z-mb3) + mmOff[0] + mmAmp[0]*cos(mroll); float my = mcc21*(caveatron.IMU_m_x-mb1) + mcc22*(caveatron.IMU_m_y-mb2) + mcc23*(caveatron.IMU_m_z-mb3) + mmOff[1] + mmAmp[1]*cos(mroll); float mz = mcc31*(caveatron.IMU_m_x-mb1) + mcc32*(caveatron.IMU_m_y-mb2) + mcc33*(caveatron.IMU_m_z-mb3) + mmOff[2] + mmAmp[2]*cos(mroll); mgeo[i] = sqrt(pow(mx,2) + pow(my,2) + pow(mz,2)); sumVals += mgeo[i]; ctGUI.updateProgressBar(pbar1, i); delay(83); } BuzzerBEEP(800, 1000); ctGUI.makeObjectInvisible(pbar1); ctGUI.makeObjectVisible(btn3); float avgVals = sumVals/96; for(int i=0; i<96; i++) { float dVal = avgVals - mgeo[i]; sqDevSum += pow(dVal, 2); if (abs(dVal) > deltaMax) deltaMax = abs(dVal); } float normStDev = caveatron.magCalStdevScale*sqrt(sqDevSum/96)/avgVals; float normdeltaMax = caveatron.magCalDeltaScale*deltaMax/avgVals; myGLCD.setColor(BLACK_STD); myGLCD.fillRect(10, 30, 310, 360); myGLCD.setColor(WHITE_STD); myGLCD.setBackColor(BLACK_STD); ctGUI.print(""AZIMUTH"", 160, 30, caveatron.FONT_28, 3, CENTER_J); ctGUI.print(""CALIBRATION"", 160, 64, caveatron.FONT_28, 3, CENTER_J); ctGUI.print(""QUALITY"", 160, 98, caveatron.FONT_28, 3, CENTER_J); ctGUI.print(""Deviation Factor:"", 15, 150, caveatron.FONT_28, 3, LEFT_J); ctGUI.print(""Maximum Error:"", 15, 210, caveatron.FONT_28, 3, LEFT_J); if (normStDev<1.0) myGLCD.setColor(GREEN_STD); //0.7 for SA004 else if (normStDev<2.0) myGLCD.setColor(YELLOW_STD); //1.4 for SA004 else myGLCD.setColor(RED_STD); ctGUI.printNumF(normStDev, 2, 240, 150, caveatron.FONT_28, 3, LEFT_J); if (normdeltaMax<1.0) myGLCD.setColor(GREEN_STD); //1.3 for SA004 else if (normdeltaMax<2.0) myGLCD.setColor(YELLOW_STD); //2.6 for SA004 else myGLCD.setColor(RED_STD); ctGUI.printNumF(normdeltaMax, 2, 240, 210, caveatron.FONT_28, 3, LEFT_J); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // **** ADVANCED CALIBRATION FUNCTIONS FOR SYSTEM SETUP AND VALIDATION **** // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // void AdvancedCalMenuSetup() { drawStatusBar(""Advanced Calibration""); drawInfoBar(""Data Recording Functions""); btn1 = ctGUI.addButton(5,30,310,80,BLACK_STD, ""1000 Raw Mag & Acc Points"", ""For Accelometer Calibration"",caveatron.FONT_19,optVisible,1); btn2 = ctGUI.addButton(5,120,310,80,BLACK_STD,""Continuous Raw Mag & Acc"", caveatron.FONT_19,optVisible,2); btn3 = ctGUI.addButton(5,210,310,80,BLACK_STD,""Uncorrected Compass Shots"", ""For Mag Alignment Calibration"", caveatron.FONT_19,optVisible,3); ctGUI.addButton(5,390,310,64,BLUE_STD,""RETURN TO SETTINGS"",caveatron.FONT_28,optVisible,5); SetupRawDisplay(); } void AdvancedCalMenuHandler(int URN) { switch (URN) { case 1: //Record 1000 Raw Magnetometer and Accelerometer Readings currentMode = modeCalRec1000; CreateScreen(screenFileNameEntry); break; case 2: //Record Continuous Raw Magnetometer and Accelerometer Readings currentMode = modeCalRecCont; CreateScreen(screenFileNameEntry); break; case 3: //Take Uncorrected & Raw Compass Shots currentMode = modeNull; CreateScreen(screenCalShots); break; case 5: //Exit guiStep--; currentMode = modeNull; CreateScreen(screenSettingsMenu); break; } } void SetupRawDisplay() { myGLCD.setColor(WHITE_STD); myGLCD.setBackColor(BLACK_STD); ctGUI.print(""X"", 140, 302, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""Y"", 200, 302, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""Z"", 270, 302, caveatron.FONT_19, 2, CENTER_J); ctGUI.print(""Raw ACC:"", 10, 328, caveatron.FONT_19, 2, LEFT_J); ctGUI.print(""Raw MAG:"", 10, 354, caveatron.FONT_19, 2, LEFT_J); } void UpdateRawDisplay() { caveatron.IMU_Read(); myGLCD.setColor(BLACK_STD); myGLCD.fillRect(120, 328, 300, 373); myGLCD.setBackColor(BLACK_STD); myGLCD.setColor(YELLOW_STD); ctGUI.printNumI(caveatron.IMU_a_x, 140, 328, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumI(caveatron.IMU_a_y, 200, 328, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumI(caveatron.IMU_a_z, 270, 328, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumI(caveatron.IMU_m_x, 140, 354, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumI(caveatron.IMU_m_y, 200, 354, caveatron.FONT_19, 2, CENTER_J); ctGUI.printNumI(caveatron.IMU_m_z, 270, 354, caveatron.FONT_19, 2, CENTER_J); delay(125); } // Acquire Raw Accelerometer and Magnetometer Readings Functions // Screen setup and handler void RawRecordSetup() { caveatron.LRF_PowerOn(); if (currentMode==modeCalRec1000) drawStatusBar(""Rec 1000 Raw Reads""); else drawStatusBar(""Rec Cont Raw Reads""); drawInfoBar(""Filename: ""+fileName); char _fileName[sizeof(fileName)]; fileName.toCharArray(_fileName, sizeof(_fileName)); if (!theFile.open(_fileName, O_RDWR | O_CREAT | O_AT_END)) { ctGUI.print(""File Open Failed"", 160, 230, caveatron.FONT_22, 2, CENTER_J, YELLOW_STD, BLACK_STD); while(true) {} } GetCurrentTime(); if (theFile.fileSize()==0) theFile.timestamp(T_CREATE, 2000+surveyYear, surveyMonth, surveyDay, surveyHour, surveyMinute, surveySecond); if (currentMode==modeCalRec1000) theFile.println(""1000 RAW ACCELEROMETER & MAGNETOMETER READINGS""); else theFile.println(""CONTINUOUS RAW ACCELEROMETER & MAGNETOMETER READINGS""); theFile.print(""Date: ""); theFile.print(dateYear); theFile.print(""-""); theFile.print(dateMonth); theFile.print(""-""); theFile.print(dateDay); theFile.print("" Time: ""); theFile.print(timeHour); theFile.print("":""); theFile.print(timeMinute); theFile.print("":""); theFile.println(timeSecond); theFile.println(); btn1 = ctGUI.addButton(11,28,300,265,GREEN_DRK,""START"",caveatron.FONT_34,optVisible,1); btn2 = ctGUI.addButton(11,28,300,265,RED_DRK,""STOP"",caveatron.FONT_34,optInvisible,2); btn3 = ctGUI.addButton(11,390,194,64,RED_STD,""Turn Laser Off"",caveatron.FONT_28,optVisible,3); btn4 = ctGUI.addButton(11,390,194,64,RED_DRK,""Turn Laser On"",caveatron.FONT_28,optInvisible,4); btn5 = ctGUI.addButton(215,390,94,64,BLUE_STD,""Done"",caveatron.FONT_28,optVisible,5); SetupRawDisplay(); delay(250); caveatron.LRF_LaserOn(); laserFlag = true; } void RawRecordHandler(int URN) { switch (URN) { case 1: //Start Recording ctGUI.makeObjectInvisible(btn1); if (laserFlag==true) ctGUI.makeObjectInvisible(btn3); else ctGUI.makeObjectInvisible(btn4); ctGUI.makeObjectInvisible(btn5); BuzzerBEEP(800, 200); if (currentMode==modeCalRecCont) ctGUI.makeObjectVisible(btn2); AcquireRawAccMag(); break; case 3: //Turn Laser Off ctGUI.makeObjectInvisible(btn3); ctGUI.makeObjectVisible(btn4); caveatron.LRF_LaserOff(); laserFlag = false; break; case 4: //Turn Laser On ctGUI.makeObjectInvisible(btn4); ctGUI.makeObjectVisible(btn3); caveatron.LRF_LaserOn(); laserFlag = true; break; case 5: //Done caveatron.LRF_LaserOff(); caveatron.LRF_PowerOff(); laserFlag=false; theFile.timestamp(T_WRITE, 2000+surveyYear, surveyMonth, surveyDay, surveyHour, surveyMinute, surveySecond); theFile.close(); currentMode = modeRawLive; CreateScreen(screenAdvancedCal); break; } } // Data Record Function void AcquireRawAccMag() { boolean done=false; //Record Raw Data if (currentMode==modeCalRec1000) { for (int i=0; i<1000; i++) { caveatron.IMU_Read(); theFile.print(caveatron.IMU_a_x);theFile.print(""\\t"");theFile.print(caveatron.IMU_a_y);theFile.print(""\\t"");theFile.print(caveatron.IMU_a_z);theFile.print(""\\t"");theFile.print(caveatron.IMU_m_x);theFile.print(""\\t"");theFile.print(caveatron.IMU_m_y);theFile.print(""\\t"");theFile.print(caveatron.IMU_m_z);theFile.print(""\\t""); theFile.println(); } } else { while (done==false) { caveatron.IMU_Read(); theFile.print(caveatron.IMU_a_x);theFile.print(""\\t"");theFile.print(caveatron.IMU_a_y);theFile.print(""\\t"");theFile.print(caveatron.IMU_a_z);theFile.print(""\\t"");theFile.print(caveatron.IMU_m_x);theFile.print(""\\t"");theFile.print(caveatron.IMU_m_y);theFile.print(""\\t"");theFile.print(caveatron.IMU_m_z);theFile.print(""\\t""); theFile.println(); // Check for button presses if ((myTouch.dataAvailable()==true) || (ctGUI.anyButtonPressed==true)) { btnFound=ctGUI.checkAllButtons(OnRelease); if (btnFound==2) { //Stop Recording done = true; ctGUI.makeObjectInvisible(btn2); } } } } //End Recording Process BuzzerBEEP(800, 1000); ctGUI.makeObjectVisible(btn1); if (laserFlag==true) ctGUI.makeObjectVisible(btn3); else ctGUI.makeObjectVisible(btn4); ctGUI.makeObjectVisible(btn5); Timer4.start(); } // Take Uncorrected & Raw Compass Shots Functions void CalShotsSetup() { drawStatusBar(""Calibration Shots""); drawInfoBar(""""); btn1 = ctGUI.addButton(11,393,86,60,GREEN_DRK,""BEGIN"",caveatron.FONT_28,optVisible,1); ctGUI.addButton(117,393,86,60,BUTTON_STD,""NEW"",caveatron.FONT_28,optVisible,2); btn3 = ctGUI.addHiddenButton(10, 30, 310, 343, optInvisible, 3); ctGUI.addButton(223,393,86,60,BLUE_STD,""QUIT"",caveatron.FONT_28,optVisible,5); if (!theFile.open(""CalShots.txt"", O_RDWR | O_CREAT)) { ctGUI.print(""File Open Failed"", 160, 230, caveatron.FONT_22, 2, CENTER_J, YELLOW_STD, BLACK_STD); sd.errorHalt(""File opening failed""); while(true) {} } if (theFile.fileSize()==0) theFile.timestamp(T_CREATE, 2000+surveyYear, surveyMonth, surveyDay, surveyHour, surveyMinute, surveySecond); currentMode = modeCalShots; LoadCalShots(); } void CalShotsHandler(int URN) { boolean waiting=true; String datetimeStr, outStr; switch (URN) { case 1: //Begin ctGUI.GUIobject_visible[btn1] = optInvisible; ctGUI.GUIobject_visible[btn3] = optVisible; caveatron.LRF_PowerOn(); LRFFlag = false; delay(250); caveatron.LRF_LaserOn(); laserFlag = true; break; case 2: //New theFile.println(""*L""+String(lidarModuleType)); theFile.timestamp(T_WRITE, 2000+surveyYear, surveyMonth, surveyDay, surveyHour, surveyMinute, surveySecond); LoadCalShots(); break; case 3: //Take Shot float singleInclin, singleRoll, singleAzimuth; int axSum, aySum, azSum, mxSum, mySum, mzSum, axAvg, ayAvg, azAvg, mxAvg, myAvg, mzAvg; axSum=0; aySum=0; azSum=0; mxSum=0; mySum=0; mzSum=0; azimuth=0; inclination=0; roll=0; ztilt = 0; BuzzerBEEP(800, 200); GetCurrentTime(); for (int i=0; i<300; i++) { GetCompassReading(); singleRoll = measureRoll(singleInclin); singleInclin = measureTilt(singleRoll); singleAzimuth = measureHeading(singleInclin, singleRoll); axSum += caveatron.IMU_a_x; aySum += caveatron.IMU_a_y; azSum += caveatron.IMU_a_z; mxSum += caveatron.IMU_m_x; mySum += caveatron.IMU_m_y; mzSum += caveatron.IMU_m_z; roll += singleRoll; inclination += -singleInclin; azimuth = SumAzimuth(azimuth, singleAzimuth); } AverageCompassData(300); datetimeStr = ""20""+dateYear+""-""+dateMonth+""-""+dateDay+""_""+timeHour+"":""+timeMinute+"":""+timeSecond; axAvg=axSum/300; ayAvg=aySum/300; azAvg=azSum/300; mxAvg=mxSum/300; myAvg=mySum/300; mzAvg=mzSum/300; outStr = String(azimuth)+"", ""+String(inclination)+"", ""+String(roll)+"",#,""+String(axAvg)+"",""+String(ayAvg)+"",""+String(azAvg)+"",""+String(mxAvg)+"",""+String(myAvg)+"",""+String(mzAvg)+"",""+datetimeStr; theFile.timestamp(T_WRITE, 2000+surveyYear, surveyMonth, surveyDay, surveyHour, surveyMinute, surveySecond); theFile.println(outStr); BuzzerBEEP(800, 1000); LoadCalShots(); break; case 5: //Done theFile.close(); laserFlag = false; caveatron.LRF_PowerOff(); currentMode = modeRawLive; CreateScreen(screenAdvancedCal); break; } } //Load list of cal shots stored on SD card void LoadCalShots() { int linelength = 1; int linecount = 0; int i=0; int numlines, endstr; char bufin[110]; String linestring; myGLCD.setColor(BLACK_STD); myGLCD.fillRect(160, 25, 300, 390); myGLCD.setBackColor(BLACK_STD); myGLCD.setColor(WHITE_STD); theFile.rewind(); while(linelength > 0) { linelength = theFile.fgets(bufin, 109); linecount++; } numlines = linecount; Serial.println(""Num lines""); Serial.println(numlines); linecount = 0; linelength = 1; theFile.rewind(); while (linelength > 0) { linelength = theFile.fgets(bufin, 109); linecount++; if ((numlines-linecount) <= 20) { Serial.println(""Line count""); Serial.println(linecount); linestring = String(bufin); endstr = linestring.indexOf(""#""); ctGUI.print(linestring.substring(0,endstr-2), 160, 25+(i*18), caveatron.FONT_15, 2); i++; } } theFile.seekEnd(0); } //Display list of cal shots void UpdateCalShotsDisplay() { ReadCompassData(1); myGLCD.setBackColor(BLACK_STD); myGLCD.setColor(BLACK_STD); myGLCD.fillRect(20, 50, 70, 178); myGLCD.setColor(YELLOW_STD); ctGUI.printNumI(azimuth, 20, 50, caveatron.FONT_28, 2); ctGUI.printNumI(inclination, 20, 100, caveatron.FONT_28, 2); ctGUI.printNumI(roll, 20, 150, caveatron.FONT_28, 2); delay(125); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // **** LOAD & SAVE CALIBRATION PARAMETERS FROM EEPROM **** // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // //Load calibration parameters from EEPROM void LoadCalibrationParameters() { String strArr; char cArr[9]; int addrMagAlignCal, addrMagHSCal, addrLidarOrientCal; float magAlignCal[8]; //Load Screen Calibration for (int i=0; i<3; i++) { strArr = caveatron.EEPROM_readCharArray(ADDR_SCREEN_CAL+(i*0x20), 10); strArr.toCharArray(cArr, 9); screenCal[i] = strtoul(cArr, NULL, 16); delay(5); } //Load Accelerometer Calibration for(int j=0;j<4;j++) { for(int i=0;i<3;i++) { accelCal[i+(3*j)] = caveatron.EEPROM_readFloat((ADDR_ACC_CAL+(4*i))+(0x20*j)); delay(5); } } if (LIDARModule) { switch (lidarModuleType) { case 1: addrMagAlignCal = ADDR_MAG_ALIGNCAL_LIDXV; addrMagHSCal = ADDR_MAG_HSCAL_LIDXV; addrLidarOrientCal = ADDR_LIDXV_ORIENTCAL; break; case 2: addrMagAlignCal = ADDR_MAG_ALIGNCAL_LIDSW; addrMagHSCal = ADDR_MAG_HSCAL_LIDSW; addrLidarOrientCal = ADDR_LIDSW_ORIENTCAL; break; case 3: addrMagAlignCal = ADDR_MAG_ALIGNCAL_LIDRP; addrMagHSCal = ADDR_MAG_HSCAL_LIDRP; addrLidarOrientCal = ADDR_LIDRP_ORIENTCAL; break; } } else { addrMagAlignCal = ADDR_MAG_ALIGNCAL_NOLID; addrMagHSCal = ADDR_MAG_HSCAL_NOLID; } //Load Magnetometer Alignment Calibration for(int i=0;i<4;i++) { magAlignCal[i] = caveatron.EEPROM_readFloat(addrMagAlignCal+(4*i)); magAlignCal[i+4] = caveatron.EEPROM_readFloat(addrMagAlignCal+0x20+(4*i)); delay(5); mmAmp[i] = (magAlignCal[i] - magAlignCal[i+4]) / 2; mmOff[i] = (magAlignCal[i] + magAlignCal[i+4]) / 2; } //Load Hard & Soft Magnetometer Alignment Calibration for(int i=0;i<3;i++) { hardIronCal[i] = caveatron.EEPROM_readFloat(addrMagHSCal+(4*i)); delay(5); } for(int j=0;j<3;j++) { for(int i=0;i<3;i++) { softIronCal[i+(3*j)] = caveatron.EEPROM_readFloat(addrMagHSCal+(4*i)+(0x20*(j+1))); delay(5); } } //Load LIDAR Rotation Orientation Calibration LIDAROrientCal = int(caveatron.EEPROM_readFloat(addrLidarOrientCal)); delay(5); //Load LRF Range Calibration LRFRangeCal = int(caveatron.EEPROM_readFloat(ADDR_LRF_RANGECAL)); delay(5); } //Save new Hard and Soft Iron calibration parameters to EEPROM void SaveCalibration() { float calBuffer1[3], calBuffer2[3], calBuffer3[3]; int addrMagHSCal; if (LIDARModule) { switch (lidarModuleType) { case 1: addrMagHSCal = ADDR_MAG_HSCAL_LIDXV; break; case 2: addrMagHSCal = ADDR_MAG_HSCAL_LIDSW; break; case 3: addrMagHSCal = ADDR_MAG_HSCAL_LIDRP; break; } } else addrMagHSCal = ADDR_MAG_HSCAL_NOLID; caveatron.EEPROM_writeFloatArray(addrMagHSCal, hardIronCal, 3); for(int i=0;i<3;i++) calBuffer1[i] = softIronCal[i]; for(int i=0;i<3;i++) calBuffer2[i] = softIronCal[3+i]; for(int i=0;i<3;i++) calBuffer3[i] = softIronCal[6+i]; caveatron.EEPROM_writeFloatArray(addrMagHSCal+0x20, calBuffer1, 3); caveatron.EEPROM_writeFloatArray(addrMagHSCal+0x40, calBuffer2, 3); caveatron.EEPROM_writeFloatArray(addrMagHSCal+0x60, calBuffer3, 3); } //Test calibration parameters - for initial setup only - will not yield useable data! void LoadTestCalibrationParameters() { char cArr[9]; float magAlignCal[8]; //You can enter your own calibration test parameters here caveatron.serialNumber = ""0A000""; String screenCalTest[3] = {""038DC286UL"",""00868F58UL"",""0013F1DFUL""}; float accCalTest[4][3] = { {-2.0E-02,7.0E-03,-3.0E-02}, {6.0E-05,2.0E-08,4.0E-07}, {1.0E-08,6.0E-05,-3.0E-07}, {-3.0E-08,3.0E-07,6.0E-05} }; float magAlignCalTest[8] = {0,0,0,0,0,0,0,0}; float magCalTest[4][3] = { {100.0,-500.0,-800.0}, {0.8,-0.1,0.03}, {-0.1,1.0,0.01}, {0.03,0.01,1.0} }; LIDAROrientCal = 0; LRFRangeCal = 0; for (int i=0; i<3; i++) { screenCalTest[i].toCharArray(cArr, 9); screenCal[i] = strtoul(cArr, NULL, 16); } for(int j=0;j<4;j++) { for(int i=0;i<3;i++) accelCal[i+(3*j)] = accCalTest[j][i]; } for(int i=0;i<4;i++) { mmAmp[i] = (magAlignCalTest[i] - magAlignCalTest[i+4]) / 2; mmOff[i] = (magAlignCalTest[i] + magAlignCalTest[i+4]) / 2; } for(int i=0;i<3;i++) hardIronCal[i] = magCalTest[0][i]; for(int j=0;j<3;j++) { for(int i=0;i<3;i++) softIronCal[i+(3*j)] = magCalTest[j+1][i]; } } ",12521,False,2177.8202203144538,median "*&---------------------------------------------------------------------* *& Local class definition - Actual Events Fillers *&---------------------------------------------------------------------* ********************************************************************** *** Purchase Order Item Confirmation Event *************************** ********************************************************************** CLASS lcl_ae_filler_po_item_conf DEFINITION. PUBLIC SECTION. INTERFACES lif_ae_filler. METHODS constructor IMPORTING io_ae_parameters TYPE REF TO lif_ae_parameters. PRIVATE SECTION. DATA: mo_ae_parameters TYPE REF TO lif_ae_parameters. METHODS get_confirmation_quantity IMPORTING ir_ekpo TYPE REF TO data ir_ekes TYPE REF TO data RETURNING VALUE(rv_menge) TYPE menge_d RAISING cx_udm_message. METHODS get_confirmation_quantity_diff IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_difference) TYPE menge_d RAISING cx_udm_message. METHODS is_appropriate_conf_type IMPORTING iv_ebtyp TYPE clike RETURNING VALUE(rv_result) TYPE abap_bool. METHODS is_appropriate_conf_control IMPORTING iv_bstae TYPE clike RETURNING VALUE(rv_result) TYPE abap_bool. METHODS has_changes IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_result) TYPE lif_ef_types=>tv_condition RAISING cx_udm_message. ENDCLASS. CLASS lcl_ae_filler_po_item_conf IMPLEMENTATION. METHOD constructor. mo_ae_parameters = io_ae_parameters. ENDMETHOD. METHOD has_changes. DATA(lv_difference) = get_confirmation_quantity_diff( is_events = is_events ). rv_result = COND #( WHEN lv_difference <> 0 THEN lif_ef_constants=>cs_condition-true ELSE lif_ef_constants=>cs_condition-false ). ENDMETHOD. METHOD lif_ae_filler~check_relevance. DATA: lv_difference TYPE menge_d. rv_result = lif_ef_constants=>cs_condition-false. IF is_events-maintabdef = lif_app_constants=>cs_tabledef-po_item_new AND lcl_po_tools=>is_appropriate_po_type( ir_ekko = is_events-mastertabref ) = abap_true AND lcl_po_tools=>is_appropriate_po_item( ir_ekpo = is_events-maintabref ) = abap_true. CASE is_events-update_indicator. WHEN lif_ef_constants=>cs_change_mode-insert. lv_difference = get_confirmation_quantity_diff( is_events = is_events ). rv_result = COND #( WHEN lv_difference <> 0 THEN lif_ef_constants=>cs_condition-true ELSE lif_ef_constants=>cs_condition-false ). WHEN lif_ef_constants=>cs_change_mode-update OR lif_ef_constants=>cs_change_mode-undefined. rv_result = has_changes( is_events = is_events ). ENDCASE. ENDIF. ENDMETHOD. METHOD lif_ae_filler~get_event_data. DATA(lv_difference) = get_confirmation_quantity_diff( is_events = is_events ). ct_trackingheader = VALUE #( BASE ct_trackingheader ( language = sy-langu trxid = lcl_po_tools=>get_tracking_id_po_item( ir_ekpo = is_events-maintabref ) trxcod = lif_app_constants=>cs_trxcod-po_position evtcnt = is_events-eventid evtid = lif_app_constants=>cs_milestone-po_confirmation evtdat = sy-datum evttim = sy-uzeit evtzon = lcl_tools=>get_system_time_zone( ) ) ). ct_eventid_map = VALUE #( BASE ct_eventid_map ( eventid = is_events-eventid evtcnt = is_events-eventid ) ). ct_tracklocation = VALUE #( BASE ct_tracklocation ( evtcnt = is_events-eventid loccod = lif_ef_constants=>cs_loc_types-plant locid1 = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'WERKS' ) ) ). "" QUANTITY ct_trackparameters = VALUE #( BASE ct_trackparameters ( evtcnt = is_events-eventid param_name = lif_app_constants=>cs_event_param-quantity param_value = lcl_tools=>get_pretty_value( iv_value = lv_difference ) ) ). "" CONFIRMATION TYPE ct_trackparameters = VALUE #( BASE ct_trackparameters ( evtcnt = is_events-eventid param_name = lif_app_constants=>cs_event_param-confirm_type param_value = lif_app_constants=>cs_relevance-ebtyp ) ). ENDMETHOD. METHOD get_confirmation_quantity. DATA: lv_has_conf TYPE abap_bool, lv_dummy TYPE char100. TYPES: tt_ekes TYPE STANDARD TABLE OF uekes. FIELD-SYMBOLS: TYPE uekpo, TYPE tt_ekes, TYPE uekes. CLEAR rv_menge. ASSIGN ir_ekpo->* TO . ASSIGN ir_ekes->* TO . IF IS ASSIGNED AND IS ASSIGNED. IF is_appropriate_conf_control( iv_bstae = -bstae ) = abap_true. LOOP AT ASSIGNING WHERE ebeln = -ebeln AND ebelp = -ebelp. IF is_appropriate_conf_type( iv_ebtyp = -ebtyp ) = abap_true. ADD -menge TO rv_menge. ENDIF. ENDLOOP. rv_menge = COND #( WHEN sy-subrc <> 0 THEN -menge ELSE rv_menge ). ENDIF. ELSEIF IS NOT ASSIGNED. MESSAGE e002(zpof_gtt) WITH 'EKPO' INTO lv_dummy. lcl_tools=>throw_exception( ). ELSE. MESSAGE e002(zpof_gtt) WITH 'EKET' INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD get_confirmation_quantity_diff. DATA: lv_mng_old TYPE menge_d VALUE 0, lv_mng_new TYPE menge_d. IF is_events-update_indicator <> lif_ef_constants=>cs_change_mode-insert. lv_mng_old = get_confirmation_quantity( ir_ekpo = is_events-mainoldtabref ir_ekes = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-po_vend_conf_old ) ). ENDIF. lv_mng_new = get_confirmation_quantity( ir_ekpo = is_events-maintabref ir_ekes = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-po_vend_conf_new ) ). rv_difference = lv_mng_new - lv_mng_old. ENDMETHOD. METHOD is_appropriate_conf_control. rv_result = boolc( iv_bstae = lif_app_constants=>cs_bstae-confirm OR iv_bstae = lif_app_constants=>cs_bstae-delivery ). ENDMETHOD. METHOD is_appropriate_conf_type. rv_result = boolc( iv_ebtyp = lif_app_constants=>cs_relevance-ebtyp ). ENDMETHOD. ENDCLASS. ********************************************************************** *** Purchase Order Item Goods Receipt Event ************************** ********************************************************************** CLASS lcl_ae_filler_po_item_gr DEFINITION. PUBLIC SECTION. INTERFACES lif_ae_filler. METHODS constructor IMPORTING io_ae_parameters TYPE REF TO lif_ae_parameters. PRIVATE SECTION. DATA: mo_ae_parameters TYPE REF TO lif_ae_parameters. METHODS get_goods_receipt_quantity IMPORTING ir_goods_receipt TYPE REF TO data RETURNING VALUE(rv_menge) TYPE menge_d RAISING cx_udm_message. METHODS get_goods_receipt_quantity_dif IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_difference) TYPE menge_d RAISING cx_udm_message. METHODS is_appropriate_definition IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_appropriate_md_type IMPORTING ir_md_head TYPE REF TO data RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_appropriate_po_item IMPORTING ir_md_pos TYPE REF TO data RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_appropriate_po_type IMPORTING ir_md_pos TYPE REF TO data RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_creation_for_po_item IMPORTING ir_md_pos TYPE REF TO data RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_creation_mode IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. ENDCLASS. CLASS lcl_ae_filler_po_item_gr IMPLEMENTATION. METHOD constructor. mo_ae_parameters = io_ae_parameters. ENDMETHOD. METHOD get_goods_receipt_quantity. DATA: lv_dummy TYPE char100. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE any. ASSIGN ir_goods_receipt->* TO . IF IS ASSIGNED. ASSIGN COMPONENT 'ERFMG' OF STRUCTURE TO . ASSIGN COMPONENT 'SHKZG' OF STRUCTURE TO . IF IS ASSIGNED. rv_menge = COND #( WHEN = 'H' THEN - ELSE ). ELSE. MESSAGE e001(zpof_gtt) WITH 'ERFMG' 'Goods Receipt' INTO lv_dummy ##NO_TEXT. lcl_tools=>throw_exception( ). ENDIF. ELSE. MESSAGE e002(zpof_gtt) WITH 'Goods Receipt' INTO lv_dummy ##NO_TEXT. lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD get_goods_receipt_quantity_dif. rv_difference = get_goods_receipt_quantity( ir_goods_receipt = is_events-maintabref ). ENDMETHOD. METHOD lif_ae_filler~check_relevance. DATA: lv_mng_new TYPE menge_d. rv_result = lif_ef_constants=>cs_condition-false. "" mkpf-blart = 'WE' "" ekko-bsart = 'NB' "" ekpo-wepos = 'X' "" update_indicator = insert IF is_appropriate_definition( is_events = is_events ) = abap_true AND is_appropriate_md_type( ir_md_head = is_events-mastertabref ) = abap_true AND * is_creation_for_po_item( ir_md_pos = is_events-maintabref ) = abap_true AND is_appropriate_po_type( ir_md_pos = is_events-maintabref ) = abap_true AND is_appropriate_po_item( ir_md_pos = is_events-maintabref ) = abap_true AND is_creation_mode( is_events = is_events ) = abap_true. lv_mng_new = get_goods_receipt_quantity( ir_goods_receipt = is_events-maintabref ). rv_result = COND #( WHEN lv_mng_new <> 0 THEN lif_ef_constants=>cs_condition-true ELSE lif_ef_constants=>cs_condition-false ). ENDIF. ENDMETHOD. METHOD is_appropriate_definition. rv_result = boolc( is_events-maintabdef = lif_app_constants=>cs_tabledef-md_material_segment ). ENDMETHOD. METHOD is_appropriate_md_type. DATA: lv_md_type TYPE mkpf-blart. lv_md_type = lcl_tools=>get_field_of_structure( ir_struct_data = ir_md_head iv_field_name = 'BLART' ). rv_result = boolc( lv_md_type = lif_app_constants=>cs_md_type-goods_receipt ). ENDMETHOD. METHOD is_appropriate_po_item. DATA: ls_ekpo TYPE ekpo. DATA(lv_ebeln) = CONV ebeln( lcl_tools=>get_field_of_structure( ir_struct_data = ir_md_pos iv_field_name = 'EBELN' ) ). DATA(lv_ebelp) = CONV ebelp( lcl_tools=>get_field_of_structure( ir_struct_data = ir_md_pos iv_field_name = 'EBELP' ) ). CALL FUNCTION 'ME_EKPO_SINGLE_READ' EXPORTING pi_ebeln = lv_ebeln pi_ebelp = lv_ebelp IMPORTING po_ekpo = ls_ekpo EXCEPTIONS no_records_found = 1 OTHERS = 2. rv_result = boolc( sy-subrc = 0 AND lcl_po_tools=>is_appropriate_po_item( ir_ekpo = REF #( ls_ekpo ) ) = abap_true ). ENDMETHOD. METHOD is_appropriate_po_type. DATA: lv_ebeln TYPE ekko-ebeln, ls_ekko TYPE ekko. lv_ebeln = lcl_tools=>get_field_of_structure( ir_struct_data = ir_md_pos iv_field_name = 'EBELN' ). CALL FUNCTION 'ME_EKKO_SINGLE_READ' EXPORTING pi_ebeln = lv_ebeln IMPORTING po_ekko = ls_ekko EXCEPTIONS no_records_found = 1 OTHERS = 2. rv_result = boolc( sy-subrc = 0 AND lcl_po_tools=>is_appropriate_po_type( ir_ekko = REF #( ls_ekko ) ) = abap_true ). ENDMETHOD. METHOD is_creation_for_po_item. DATA: lv_ebeln TYPE ekko-ebeln, lv_vbeln TYPE mseg-vbeln_im. lv_ebeln = lcl_tools=>get_field_of_structure( ir_struct_data = ir_md_pos iv_field_name = 'EBELN' ). lv_vbeln = lcl_tools=>get_field_of_structure( ir_struct_data = ir_md_pos iv_field_name = 'VBELN_IM' ). rv_result = boolc( lv_ebeln IS NOT INITIAL AND lv_vbeln IS INITIAL ). ENDMETHOD. METHOD is_creation_mode. DATA: lv_mblnr TYPE mkpf-mblnr, lv_mjahr TYPE mkpf-mjahr. * ls_mkpf TYPE mkpf. IF is_events-update_indicator = lif_ef_constants=>cs_change_mode-insert. rv_result = abap_true. ELSEIF is_events-update_indicator = lif_ef_constants=>cs_change_mode-undefined. lv_mblnr = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'MBLNR' ). lv_mjahr = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'MJAHR' ). SELECT SINGLE mblnr INTO lv_mblnr FROM mkpf WHERE mblnr = lv_mblnr AND mjahr = lv_mjahr. rv_result = boolc( sy-subrc <> 0 ). ELSE. rv_result = abap_false. ENDIF. ENDMETHOD. METHOD lif_ae_filler~get_event_data. DATA(lv_difference) = get_goods_receipt_quantity_dif( is_events = is_events ). ct_trackingheader = VALUE #( BASE ct_trackingheader ( language = sy-langu trxid = lcl_po_tools=>get_tracking_id_po_item( ir_ekpo = is_events-maintabref ) ""MSEG contains EBELN/EBELP trxcod = lif_app_constants=>cs_trxcod-po_position evtcnt = is_events-eventid evtid = lif_app_constants=>cs_milestone-po_goods_receipt evtdat = sy-datum evttim = sy-uzeit evtzon = lcl_tools=>get_system_time_zone( ) ) ). ct_eventid_map = VALUE #( BASE ct_eventid_map ( eventid = is_events-eventid evtcnt = is_events-eventid ) ). ct_tracklocation = VALUE #( BASE ct_tracklocation ( evtcnt = is_events-eventid loccod = lif_ef_constants=>cs_loc_types-plant locid1 = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'WERKS' ) ) ). ct_trackparameters = VALUE #( BASE ct_trackparameters ( evtcnt = is_events-eventid param_name = lif_app_constants=>cs_event_param-quantity param_value = lcl_tools=>get_pretty_value( iv_value = lv_difference ) ) ). ENDMETHOD. ENDCLASS. ********************************************************************** *** Purchase Order Item Deletion Event ******************************* ********************************************************************** CLASS lcl_ae_filler_po_item_del DEFINITION. PUBLIC SECTION. INTERFACES lif_ae_filler. METHODS constructor IMPORTING io_ae_parameters TYPE REF TO lif_ae_parameters. PRIVATE SECTION. DATA: mo_ae_parameters TYPE REF TO lif_ae_parameters. METHODS is_appropriate_mode IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_result) TYPE abap_bool. ENDCLASS. CLASS lcl_ae_filler_po_item_del IMPLEMENTATION. METHOD constructor. mo_ae_parameters = io_ae_parameters. ENDMETHOD. METHOD lif_ae_filler~check_relevance. DATA: lv_loekz_old TYPE ekpo-loekz, lv_loekz_new TYPE ekpo-loekz. rv_result = lif_ef_constants=>cs_condition-false. IF is_events-maintabdef = lif_app_constants=>cs_tabledef-po_item_new AND lcl_po_tools=>is_appropriate_po_type( ir_ekko = is_events-mastertabref ) = abap_true AND lcl_po_tools=>is_appropriate_po_item( ir_ekpo = is_events-maintabref ) = abap_true AND is_appropriate_mode( is_events = is_events ) = abap_true. lv_loekz_old = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-mainoldtabref iv_field_name = 'LOEKZ' ). lv_loekz_new = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'LOEKZ' ). rv_result = COND #( WHEN lv_loekz_new <> lv_loekz_old AND ( lv_loekz_old = lif_app_constants=>cs_loekz-deleted OR lv_loekz_new = lif_app_constants=>cs_loekz-deleted ) THEN lif_ef_constants=>cs_condition-true ELSE lif_ef_constants=>cs_condition-false ). ENDIF. ENDMETHOD. METHOD lif_ae_filler~get_event_data. DATA(lv_loekz) = CONV eloek( lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'LOEKZ' ) ). ct_trackingheader = VALUE #( BASE ct_trackingheader ( language = sy-langu trxid = lcl_po_tools=>get_tracking_id_po_item( ir_ekpo = is_events-maintabref ) trxcod = lif_app_constants=>cs_trxcod-po_position evtcnt = is_events-eventid evtid = COND #( WHEN lv_loekz = lif_app_constants=>cs_loekz-deleted THEN lif_app_constants=>cs_milestone-po_deletion ELSE lif_app_constants=>cs_milestone-po_undeletion ) evtdat = sy-datum evttim = sy-uzeit evtzon = lcl_tools=>get_system_time_zone( ) ) ). ct_eventid_map = VALUE #( BASE ct_eventid_map ( eventid = is_events-eventid evtcnt = is_events-eventid ) ). ENDMETHOD. METHOD is_appropriate_mode. rv_result = boolc( is_events-update_indicator = lif_ef_constants=>cs_change_mode-insert OR is_events-update_indicator = lif_ef_constants=>cs_change_mode-update OR is_events-update_indicator = lif_ef_constants=>cs_change_mode-undefined ). ENDMETHOD. ENDCLASS. ********************************************************************** *** Inbound Delivery Header Goods Receipt Event ********************** ********************************************************************** CLASS lcl_ae_filler_dl_header_gr DEFINITION. PUBLIC SECTION. INTERFACES lif_ae_filler. METHODS constructor IMPORTING io_ae_parameters TYPE REF TO lif_ae_parameters. PRIVATE SECTION. TYPES: BEGIN OF ts_dl_item_id, vbeln TYPE vbeln_vl, posnr TYPE posnr_vl, END OF ts_dl_item_id. TYPES: tt_vbeln TYPE STANDARD TABLE OF vbeln_vl. DATA: mo_ae_parameters TYPE REF TO lif_ae_parameters. METHODS get_delivery_ids IMPORTING ir_md_pos TYPE REF TO data EXPORTING et_vbeln TYPE tt_vbeln RAISING cx_udm_message. METHODS is_appropriate_definition IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_appropriate_md_type IMPORTING ir_md_head TYPE REF TO data RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_appropriate_dl_item IMPORTING ir_md_pos TYPE REF TO data RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_appropriate_dl_type IMPORTING ir_md_pos TYPE REF TO data RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_creation_mode IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. METHODS is_reveral_document IMPORTING ir_md_pos TYPE REF TO data RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. ENDCLASS. CLASS lcl_ae_filler_dl_header_gr IMPLEMENTATION. METHOD constructor. mo_ae_parameters = io_ae_parameters. ENDMETHOD. METHOD get_delivery_ids. DATA: lv_vbeln TYPE vbeln_vl. FIELD-SYMBOLS: TYPE lif_app_types=>tt_mseg. CLEAR: et_vbeln[]. ASSIGN ir_md_pos->* TO . IF IS ASSIGNED. LOOP AT ASSIGNING FIELD-SYMBOL() WHERE vbeln_im IS NOT INITIAL. IF NOT line_exists( et_vbeln[ table_line = -vbeln_im ] ). APPEND -vbeln_im TO et_vbeln. ENDIF. ENDLOOP. ELSE. MESSAGE e002(zpof_gtt) WITH 'MSEG' INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD is_appropriate_definition. rv_result = boolc( is_events-maintabdef = lif_app_constants=>cs_tabledef-md_material_header ). ENDMETHOD. METHOD is_appropriate_md_type. DATA: lv_md_type TYPE mkpf-blart. lv_md_type = lcl_tools=>get_field_of_structure( ir_struct_data = ir_md_head iv_field_name = 'BLART' ). rv_result = boolc( lv_md_type = lif_app_constants=>cs_md_type-goods_receipt ). ENDMETHOD. METHOD is_appropriate_dl_item. DATA: lt_vbeln TYPE tt_vbeln, lt_lips TYPE STANDARD TABLE OF lips. rv_result = abap_false. get_delivery_ids( EXPORTING ir_md_pos = ir_md_pos IMPORTING et_vbeln = lt_vbeln ). IF lt_vbeln[] IS NOT INITIAL. SELECT * INTO TABLE lt_lips FROM lips FOR ALL ENTRIES IN lt_vbeln WHERE vbeln = lt_vbeln-table_line. LOOP AT lt_lips ASSIGNING FIELD-SYMBOL(). rv_result = boolc( sy-subrc = 0 AND lcl_dl_tools=>is_appropriate_dl_item( ir_struct = REF #( ) ) = abap_true ). IF rv_result = abap_true. EXIT. ENDIF. ENDLOOP. ENDIF. ENDMETHOD. METHOD is_appropriate_dl_type. DATA: lt_vbeln TYPE tt_vbeln, lt_likp TYPE STANDARD TABLE OF likp. rv_result = abap_false. get_delivery_ids( EXPORTING ir_md_pos = ir_md_pos IMPORTING et_vbeln = lt_vbeln ). IF lt_vbeln[] IS NOT INITIAL. SELECT * INTO TABLE lt_likp FROM likp FOR ALL ENTRIES IN lt_vbeln WHERE vbeln = lt_vbeln-table_line. LOOP AT lt_likp ASSIGNING FIELD-SYMBOL(). rv_result = boolc( sy-subrc = 0 AND lcl_dl_tools=>is_appropriate_dl_type( ir_struct = REF #( ) ) = abap_true ). IF rv_result = abap_true. EXIT. ENDIF. ENDLOOP. ENDIF. ENDMETHOD. METHOD is_creation_mode. DATA: lv_mblnr TYPE mkpf-mblnr, lv_mjahr TYPE mkpf-mjahr. IF is_events-update_indicator = lif_ef_constants=>cs_change_mode-insert. rv_result = abap_true. ELSEIF is_events-update_indicator = lif_ef_constants=>cs_change_mode-undefined. lv_mblnr = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'MBLNR' ). lv_mjahr = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'MJAHR' ). SELECT SINGLE mblnr INTO lv_mblnr FROM mkpf WHERE mblnr = lv_mblnr AND mjahr = lv_mjahr. rv_result = boolc( sy-subrc <> 0 ). ELSE. rv_result = abap_false. ENDIF. ENDMETHOD. METHOD is_reveral_document. DATA: lv_vbeln TYPE vbeln_vl. FIELD-SYMBOLS: TYPE lif_app_types=>tt_mseg. ASSIGN ir_md_pos->* TO . IF IS ASSIGNED. READ TABLE ASSIGNING FIELD-SYMBOL() INDEX 1. rv_result = boolc( sy-subrc = 0 AND -smbln IS NOT INITIAL ). ELSE. MESSAGE e002(zpof_gtt) WITH 'MSEG' INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD lif_ae_filler~check_relevance. DATA: lv_mng_new TYPE menge_d. DATA(lr_md_pos) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-md_material_segment ). rv_result = lif_ef_constants=>cs_condition-false. "" mkpf-blart = 'WE' "" update_indicator = insert IF is_appropriate_definition( is_events = is_events ) = abap_true AND is_appropriate_md_type( ir_md_head = is_events-maintabref ) = abap_true AND is_appropriate_dl_type( ir_md_pos = lr_md_pos ) = abap_true AND is_appropriate_dl_item( ir_md_pos = lr_md_pos ) = abap_true AND is_creation_mode( is_events = is_events ) = abap_true. rv_result = lif_ef_constants=>cs_condition-true. ENDIF. ENDMETHOD. METHOD lif_ae_filler~get_event_data. DATA: lt_vbeln TYPE tt_vbeln. DATA(lr_md_pos) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-md_material_segment ). DATA(lv_reversal) = is_reveral_document( ir_md_pos = lr_md_pos ). get_delivery_ids( EXPORTING ir_md_pos = lr_md_pos IMPORTING et_vbeln = lt_vbeln ). LOOP AT lt_vbeln ASSIGNING FIELD-SYMBOL(). DATA(lv_evtcnt) = lcl_sh_tools=>get_next_event_counter( ). ct_trackingheader = VALUE #( BASE ct_trackingheader ( language = sy-langu trxid = trxcod = lif_app_constants=>cs_trxcod-dl_number evtcnt = lv_evtcnt evtid = lif_app_constants=>cs_milestone-dl_goods_receipt evtdat = sy-datum evttim = sy-uzeit evtzon = lcl_tools=>get_system_time_zone( ) ) ). ct_eventid_map = VALUE #( BASE ct_eventid_map ( eventid = is_events-eventid evtcnt = lv_evtcnt ) ). ct_trackparameters = VALUE #( BASE ct_trackparameters ( evtcnt = lv_evtcnt param_name = lif_app_constants=>cs_event_param-reversal param_value = lv_reversal ) ). ENDLOOP. ENDMETHOD. ENDCLASS. ********************************************************************** *** Inbound Delivery Item Put Away Event ***************************** ********************************************************************** CLASS lcl_ae_filler_dl_item_pa DEFINITION. PUBLIC SECTION. INTERFACES lif_ae_filler. METHODS constructor IMPORTING io_ae_parameters TYPE REF TO lif_ae_parameters. PRIVATE SECTION. DATA: mo_ae_parameters TYPE REF TO lif_ae_parameters. METHODS get_put_away_quantity IMPORTING ir_data TYPE REF TO data RETURNING VALUE(rv_menge) TYPE menge_d RAISING cx_udm_message. METHODS get_put_away_quantity_diff IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_difference) TYPE menge_d RAISING cx_udm_message. ENDCLASS. CLASS lcl_ae_filler_dl_item_pa IMPLEMENTATION. METHOD constructor. mo_ae_parameters = io_ae_parameters. ENDMETHOD. METHOD get_put_away_quantity. rv_menge = lcl_tools=>get_field_of_structure( ir_struct_data = ir_data iv_field_name = 'PIKMG' ). ENDMETHOD. METHOD get_put_away_quantity_diff. DATA: lv_mng_old TYPE menge_d VALUE 0, lv_mng_new TYPE menge_d. IF is_events-update_indicator <> lif_ef_constants=>cs_change_mode-insert. lv_mng_old = get_put_away_quantity( ir_data = is_events-mainoldtabref ). ENDIF. lv_mng_new = get_put_away_quantity( ir_data = is_events-maintabref ). rv_difference = lv_mng_new - lv_mng_old. ENDMETHOD. METHOD lif_ae_filler~check_relevance. DATA: lv_difference TYPE menge_d. rv_result = lif_ef_constants=>cs_condition-false. IF is_events-maintabdef = lif_app_constants=>cs_tabledef-dl_item_new AND lcl_dl_tools=>is_appropriate_dl_type( ir_struct = is_events-mastertabref ) = abap_true AND lcl_dl_tools=>is_appropriate_dl_item( ir_struct = is_events-maintabref ) = abap_true. CASE is_events-update_indicator. WHEN lif_ef_constants=>cs_change_mode-insert OR lif_ef_constants=>cs_change_mode-update OR lif_ef_constants=>cs_change_mode-undefined. lv_difference = get_put_away_quantity_diff( is_events = is_events ). rv_result = COND #( WHEN lv_difference <> 0 THEN lif_ef_constants=>cs_condition-true ELSE lif_ef_constants=>cs_condition-false ). ENDCASE. ENDIF. ENDMETHOD. METHOD lif_ae_filler~get_event_data. DATA(lv_difference) = get_put_away_quantity_diff( is_events = is_events ). ct_trackingheader = VALUE #( BASE ct_trackingheader ( language = sy-langu trxid = lcl_dl_tools=>get_tracking_id_dl_item( ir_lips = is_events-maintabref ) trxcod = lif_app_constants=>cs_trxcod-dl_position evtcnt = is_events-eventid evtid = lif_app_constants=>cs_milestone-dl_put_away evtdat = sy-datum evttim = sy-uzeit evtzon = lcl_tools=>get_system_time_zone( ) ) ). ct_eventid_map = VALUE #( BASE ct_eventid_map ( eventid = is_events-eventid evtcnt = is_events-eventid ) ). ct_tracklocation = VALUE #( BASE ct_tracklocation ( evtcnt = is_events-eventid loccod = lif_ef_constants=>cs_loc_types-plant locid1 = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'WERKS' ) ) ). ct_trackparameters = VALUE #( BASE ct_trackparameters ( evtcnt = is_events-eventid param_name = lif_app_constants=>cs_event_param-quantity param_value = lcl_tools=>get_pretty_value( iv_value = lv_difference ) ) ). ENDMETHOD. ENDCLASS. ********************************************************************** *** Inbound Delivery Item Packing Event ****************************** ********************************************************************** CLASS lcl_ae_filler_dl_item_pkng DEFINITION. PUBLIC SECTION. INTERFACES lif_ae_filler. METHODS constructor IMPORTING io_ae_parameters TYPE REF TO lif_ae_parameters. PRIVATE SECTION. TYPES: tt_vepo TYPE STANDARD TABLE OF vepovb. DATA: mo_ae_parameters TYPE REF TO lif_ae_parameters. METHODS get_packing_quantity IMPORTING ir_lips TYPE REF TO data ir_vepo TYPE REF TO data RETURNING VALUE(rv_menge) TYPE menge_d RAISING cx_udm_message. METHODS get_packing_quantity_changed IMPORTING is_events TYPE trxas_evt_ctab_wa RETURNING VALUE(rv_changed) TYPE lif_ef_types=>tv_condition RAISING cx_udm_message. ENDCLASS. CLASS lcl_ae_filler_dl_item_pkng IMPLEMENTATION. METHOD constructor. mo_ae_parameters = io_ae_parameters. ENDMETHOD. METHOD get_packing_quantity. DATA: lv_vemng_flo TYPE vepo-vemng_flo VALUE 0. FIELD-SYMBOLS: TYPE tt_vepo. DATA(lv_vbeln) = CONV vbeln_vl( lcl_tools=>get_field_of_structure( ir_struct_data = ir_lips iv_field_name = 'VBELN' ) ). DATA(lv_posnr) = CONV posnr_vl( lcl_tools=>get_field_of_structure( ir_struct_data = ir_lips iv_field_name = 'POSNR' ) ). ASSIGN ir_vepo->* TO . CLEAR: rv_menge. IF IS ASSIGNED. LOOP AT ASSIGNING FIELD-SYMBOL() WHERE vbeln = lv_vbeln AND posnr = lv_posnr. ADD -vemng_flo TO lv_vemng_flo. ENDLOOP. rv_menge = lcl_dl_tools=>convert_quantity_into_pounits( iv_quantity_uom = lv_vemng_flo ir_lips = ir_lips ). ELSE. MESSAGE e002(zpof_gtt) WITH 'VEPO' INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD get_packing_quantity_changed. FIELD-SYMBOLS: TYPE tt_vepo, TYPE tt_vepo. IF is_events-update_indicator = lif_ef_constants=>cs_change_mode-insert. DATA(lv_quantity) = get_packing_quantity( ir_lips = is_events-maintabref ir_vepo = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-dl_hu_item_new ) ). rv_changed = COND #( WHEN lv_quantity > 0 THEN lif_ef_constants=>cs_condition-true ELSE lif_ef_constants=>cs_condition-false ). ELSE. rv_changed = lif_ef_constants=>cs_condition-false. DATA(lv_vbeln) = CONV vbeln_vl( lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'VBELN' ) ). DATA(lv_posnr) = CONV posnr_vl( lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'POSNR' ) ). DATA(lr_vepo_old) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-dl_hu_item_old ). DATA(lr_vepo_new) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-dl_hu_item_new ). ASSIGN lr_vepo_old->* TO . ASSIGN lr_vepo_new->* TO . IF IS ASSIGNED AND IS ASSIGNED. LOOP AT ASSIGNING FIELD-SYMBOL() WHERE vbeln = lv_vbeln AND posnr = lv_posnr AND updkz IS NOT INITIAL. "" HU item inserted ? IF -updkz = lif_ef_constants=>cs_change_mode-insert. rv_changed = lif_ef_constants=>cs_condition-true. RETURN. "" HU item updated ? ELSEIF -updkz = lif_ef_constants=>cs_change_mode-update OR -updkz = lif_ef_constants=>cs_change_mode-undefined. READ TABLE ASSIGNING FIELD-SYMBOL() WITH KEY venum = -venum vepos = -vepos. IF sy-subrc = 0 AND -vemng_flo <> -vemng_flo . rv_changed = lif_ef_constants=>cs_condition-true. RETURN. ENDIF. ENDIF. ENDLOOP. "" HU item deleted ? READ TABLE TRANSPORTING NO FIELDS WITH KEY vbeln = lv_vbeln posnr = lv_posnr updkz = lif_ef_constants=>cs_change_mode-delete. rv_changed = COND #( WHEN sy-subrc = 0 THEN lif_ef_constants=>cs_condition-true ELSE lif_ef_constants=>cs_condition-false ). ELSE. MESSAGE e002(zpof_gtt) WITH 'VEPO' INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. ENDIF. ENDMETHOD. METHOD lif_ae_filler~check_relevance. DATA: lv_difference TYPE menge_d. rv_result = lif_ef_constants=>cs_condition-false. IF is_events-maintabdef = lif_app_constants=>cs_tabledef-dl_item_new AND lcl_dl_tools=>is_appropriate_dl_type( ir_struct = is_events-mastertabref ) = abap_true AND lcl_dl_tools=>is_appropriate_dl_item( ir_struct = is_events-maintabref ) = abap_true. CASE is_events-update_indicator. WHEN lif_ef_constants=>cs_change_mode-insert OR lif_ef_constants=>cs_change_mode-update OR lif_ef_constants=>cs_change_mode-undefined. rv_result = get_packing_quantity_changed( is_events = is_events ). ENDCASE. ENDIF. ENDMETHOD. METHOD lif_ae_filler~get_event_data. DATA(lv_quantity) = get_packing_quantity( ir_lips = is_events-maintabref ir_vepo = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-dl_hu_item_new ) ). ct_trackingheader = VALUE #( BASE ct_trackingheader ( language = sy-langu trxid = lcl_dl_tools=>get_tracking_id_dl_item( ir_lips = is_events-maintabref ) trxcod = lif_app_constants=>cs_trxcod-dl_position evtcnt = is_events-eventid evtid = lif_app_constants=>cs_milestone-dl_packing evtdat = sy-datum evttim = sy-uzeit evtzon = lcl_tools=>get_system_time_zone( ) ) ). ct_eventid_map = VALUE #( BASE ct_eventid_map ( eventid = is_events-eventid evtcnt = is_events-eventid ) ). ct_tracklocation = VALUE #( BASE ct_tracklocation ( evtcnt = is_events-eventid loccod = lif_ef_constants=>cs_loc_types-plant locid1 = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'WERKS' ) ) ). "" the WHOLE QUANTITY is sent (delta approach might have calculation mistakes "" because of quantity conversion ct_trackparameters = VALUE #( BASE ct_trackparameters ( evtcnt = is_events-eventid param_name = lif_app_constants=>cs_event_param-quantity param_value = lcl_tools=>get_pretty_value( iv_value = lv_quantity ) ) ). ENDMETHOD. ENDCLASS. ********************************************************************** *** Shipment Header - Header Based Events **************************** ********************************************************************** CLASS lcl_ae_filler_sh_header_bh DEFINITION ABSTRACT. PUBLIC SECTION. INTERFACES lif_ae_filler. METHODS constructor IMPORTING io_ae_parameters TYPE REF TO lif_ae_parameters. PROTECTED SECTION. METHODS get_eventid ABSTRACT RETURNING VALUE(rv_eventid) TYPE /saptrx/ev_evtid. METHODS get_date_field ABSTRACT RETURNING VALUE(rv_field) TYPE lif_ef_types=>tv_field_name. METHODS get_time_field ABSTRACT RETURNING VALUE(rv_field) TYPE lif_ef_types=>tv_field_name. PRIVATE SECTION. TYPES: BEGIN OF ts_dl_item_id, vbeln TYPE vbeln_vl, posnr TYPE posnr_vl, END OF ts_dl_item_id. DATA: mo_ae_parameters TYPE REF TO lif_ae_parameters. ENDCLASS. CLASS lcl_ae_filler_sh_header_bh IMPLEMENTATION. METHOD constructor. mo_ae_parameters = io_ae_parameters. ENDMETHOD. METHOD lif_ae_filler~check_relevance. DATA: lr_vttk_old TYPE REF TO data, lv_date TYPE d. DATA(lr_vttp) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-sh_item_new ). lv_date = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = get_date_field( ) ). rv_result = lif_ef_constants=>cs_condition-false. IF is_events-maintabdef = lif_app_constants=>cs_tabledef-sh_header_new AND lcl_sh_tools=>is_appropriate_type( ir_vttk = is_events-maintabref ) = abap_true AND lcl_sh_tools=>is_delivery_assigned( ir_vttp = lr_vttp ) = abap_true AND lv_date IS NOT INITIAL. lr_vttk_old = COND #( WHEN is_events-update_indicator = lif_ef_constants=>cs_change_mode-insert THEN NEW vttkvb( ) ELSE is_events-mainoldtabref ). rv_result = lcl_tools=>are_fields_different( ir_data1 = is_events-maintabref ir_data2 = lr_vttk_old it_fields = VALUE #( ( get_date_field( ) ) ( get_time_field( ) ) ) ). ENDIF. ENDMETHOD. METHOD lif_ae_filler~get_event_data. DATA(lv_evtcnt) = lcl_sh_tools=>get_next_event_counter( ). ct_trackingheader = VALUE #( BASE ct_trackingheader ( language = sy-langu trxid = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'TKNUM' ) trxcod = lif_app_constants=>cs_trxcod-sh_number evtcnt = lv_evtcnt evtid = get_eventid( ) evtdat = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = get_date_field( ) ) evttim = lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = get_time_field( ) ) evtzon = lcl_tools=>get_system_time_zone( ) ) ). ct_eventid_map = VALUE #( BASE ct_eventid_map ( eventid = is_events-eventid evtcnt = lv_evtcnt ) ). ENDMETHOD. ENDCLASS. ********************************************************************** *** Shipment Header Check In Event *********************************** ********************************************************************** CLASS lcl_ae_filler_sh_header_ci DEFINITION INHERITING FROM lcl_ae_filler_sh_header_bh. PROTECTED SECTION. METHODS get_eventid REDEFINITION. METHODS get_date_field REDEFINITION. METHODS get_time_field REDEFINITION. ENDCLASS. CLASS lcl_ae_filler_sh_header_ci IMPLEMENTATION. METHOD get_eventid. rv_eventid = lif_app_constants=>cs_milestone-sh_check_in. ENDMETHOD. METHOD get_date_field. rv_field = 'DAREG'. ENDMETHOD. METHOD get_time_field. rv_field = 'UAREG'. ENDMETHOD. ENDCLASS. ********************************************************************** *** Shipment Header Load Start Event ********************************* ********************************************************************** CLASS lcl_ae_filler_sh_header_ls DEFINITION INHERITING FROM lcl_ae_filler_sh_header_bh. PROTECTED SECTION. METHODS get_eventid REDEFINITION. METHODS get_date_field REDEFINITION. METHODS get_time_field REDEFINITION. ENDCLASS. CLASS lcl_ae_filler_sh_header_ls IMPLEMENTATION. METHOD get_eventid. rv_eventid = lif_app_constants=>cs_milestone-sh_load_start. ENDMETHOD. METHOD get_date_field. rv_field = 'DALBG'. ENDMETHOD. METHOD get_time_field. rv_field = 'UALBG'. ENDMETHOD. ENDCLASS. ********************************************************************** *** Shipment Header Load End Event *********************************** ********************************************************************** CLASS lcl_ae_filler_sh_header_le DEFINITION INHERITING FROM lcl_ae_filler_sh_header_bh. PROTECTED SECTION. METHODS get_eventid REDEFINITION. METHODS get_date_field REDEFINITION. METHODS get_time_field REDEFINITION. ENDCLASS. CLASS lcl_ae_filler_sh_header_le IMPLEMENTATION. METHOD get_eventid. rv_eventid = lif_app_constants=>cs_milestone-sh_load_end. ENDMETHOD. METHOD get_date_field. rv_field = 'DALEN'. ENDMETHOD. METHOD get_time_field. rv_field = 'UALEN'. ENDMETHOD. ENDCLASS. ********************************************************************** *** Shipment Header - Stops Based Events **************************** ********************************************************************** CLASS lcl_ae_filler_sh_header_bs DEFINITION ABSTRACT. PUBLIC SECTION. INTERFACES lif_ae_filler. METHODS constructor IMPORTING io_ae_parameters TYPE REF TO lif_ae_parameters RAISING cx_udm_message. PROTECTED SECTION. METHODS get_date_field ABSTRACT RETURNING VALUE(rv_field) TYPE lif_ef_types=>tv_field_name. METHODS get_eventid ABSTRACT RETURNING VALUE(rv_eventid) TYPE /saptrx/ev_evtid. METHODS get_location_category ABSTRACT RETURNING VALUE(rv_loccat) TYPE lif_app_types=>tv_loccat. METHODS get_time_field ABSTRACT RETURNING VALUE(rv_field) TYPE lif_ef_types=>tv_field_name. METHODS is_location_required ABSTRACT RETURNING VALUE(rv_result) TYPE abap_bool. PRIVATE SECTION. TYPES: tt_vttsvb TYPE vttsvb_tab. TYPES: BEGIN OF ts_dl_item_id, vbeln TYPE vbeln_vl, posnr TYPE posnr_vl, END OF ts_dl_item_id. DATA: mo_ae_parameters TYPE REF TO lif_ae_parameters, mt_vtts_new TYPE tt_vttsvb, mt_vtts_old TYPE tt_vttsvb. METHODS get_copy_of_vtts_table IMPORTING ir_vtts TYPE REF TO data EXPORTING et_vtts TYPE tt_vttsvb. METHODS get_stops_from_shipment IMPORTING is_events TYPE trxas_evt_ctab_wa EXPORTING et_stops TYPE lif_app_types=>tt_stops RAISING cx_udm_message. METHODS is_stop_changed IMPORTING iv_tknum TYPE tknum iv_tsnum TYPE tsnum RETURNING VALUE(rv_result) TYPE abap_bool RAISING cx_udm_message. ENDCLASS. CLASS lcl_ae_filler_sh_header_bs IMPLEMENTATION. METHOD constructor. mo_ae_parameters = io_ae_parameters. get_copy_of_vtts_table( EXPORTING ir_vtts = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-sh_stage_new ) IMPORTING et_vtts = mt_vtts_new ). get_copy_of_vtts_table( EXPORTING ir_vtts = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-sh_stage_old ) IMPORTING et_vtts = mt_vtts_old ). ENDMETHOD. METHOD get_copy_of_vtts_table. FIELD-SYMBOLS: TYPE tt_vttsvb. ASSIGN ir_vtts->* TO . IF IS ASSIGNED. et_vtts[] = []. SORT et_vtts BY tknum tsnum. ELSE. CLEAR et_vtts[]. ENDIF. ENDMETHOD. METHOD get_stops_from_shipment. DATA: lt_vtts TYPE vttsvb_tab. DATA(lv_tknum) = CONV tknum( lcl_tools=>get_field_of_structure( ir_struct_data = is_events-maintabref iv_field_name = 'TKNUM' ) ). DATA(lr_vttp) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-sh_item_new ). DATA(lr_vtts) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-sh_stage_new ). DATA(lr_vtsp) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-sh_item_stage_new ). FIELD-SYMBOLS: TYPE vttpvb_tab, TYPE vttsvb_tab, TYPE vtspvb_tab. ASSIGN lr_vtts->* TO . ASSIGN lr_vttp->* TO . ASSIGN lr_vtsp->* TO . IF IS ASSIGNED AND IS ASSIGNED AND IS ASSIGNED. lt_vtts[] = []. SORT lt_vtts BY tsrfo. lcl_sh_tools=>get_stops_from_shipment( EXPORTING iv_tknum = lv_tknum it_vtts = lt_vtts it_vtsp = it_vttp = IMPORTING et_stops = et_stops ). ELSE. MESSAGE e002(zpof_gtt) WITH 'VTTS' INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD is_stop_changed. FIELD-SYMBOLS: TYPE d. rv_result = lif_ef_constants=>cs_condition-false. READ TABLE mt_vtts_new ASSIGNING FIELD-SYMBOL() WITH KEY tknum = iv_tknum tsnum = iv_tsnum BINARY SEARCH. IF sy-subrc = 0. CASE -updkz. WHEN lif_ef_constants=>cs_change_mode-insert. ASSIGN COMPONENT get_date_field( ) OF STRUCTURE TO . IF IS ASSIGNED. rv_result = COND #( WHEN IS NOT INITIAL THEN lif_ef_constants=>cs_condition-true ELSE lif_ef_constants=>cs_condition-false ). ELSE. MESSAGE e001(zpof_gtt) WITH get_date_field( ) 'VTTS' INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. WHEN lif_ef_constants=>cs_change_mode-update OR lif_ef_constants=>cs_change_mode-undefined. ASSIGN COMPONENT get_date_field( ) OF STRUCTURE TO . IF IS ASSIGNED AND IS NOT INITIAL. READ TABLE mt_vtts_old ASSIGNING FIELD-SYMBOL() WITH KEY tknum = -tknum tsnum = -tsnum BINARY SEARCH. IF sy-subrc = 0. rv_result = lcl_tools=>are_fields_different( ir_data1 = REF #( ) ir_data2 = REF #( ) it_fields = VALUE #( ( get_date_field( ) ) ( get_time_field( ) ) ) ). ENDIF. ENDIF. ENDCASE. ELSE. MESSAGE e005(zpof_gtt) WITH |{ iv_tknum }{ iv_tsnum }| 'VTTS' INTO lv_dummy. lcl_tools=>throw_exception( ). ENDIF. ENDMETHOD. METHOD lif_ae_filler~check_relevance. DATA: lv_date TYPE d. FIELD-SYMBOLS: TYPE lif_app_types=>tt_vttsvb, TYPE lif_app_types=>tt_vttsvb. DATA(lt_fields) = VALUE lif_ef_types=>tt_field_name( ( get_date_field( ) ) ( get_time_field( ) ) ). DATA(lr_vttp) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-sh_item_new ). DATA(lr_vtts_new) = mo_ae_parameters->get_appl_table( iv_tabledef = lif_app_constants=>cs_tabledef-sh_stage_new ). rv_result = lif_ef_constants=>cs_condition-false. IF is_events-maintabdef = lif_app_constants=>cs_tabledef-sh_header_new AND lcl_sh_tools=>is_appropriate_type( ir_vttk = is_events-maintabref ) = abap_true AND lcl_sh_tools=>is_delivery_assigned( ir_vttp = lr_vttp ) = abap_true. ASSIGN lr_vtts_new->* TO . IF IS ASSIGNED. LOOP AT ASSIGNING FIELD-SYMBOL() WHERE updkz IS NOT INITIAL. rv_result = is_stop_changed( iv_tknum = -tknum iv_tsnum = -tsnum ). IF rv_result = lif_ef_constants=>cs_condition-true. EXIT. ENDIF. ENDLOOP. ELSE. MESSAGE e002(zpof_gtt) WITH 'VTTS' INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. ENDIF. ENDMETHOD. METHOD lif_ae_filler~get_event_data. DATA: lt_stops TYPE lif_app_types=>tt_stops. get_stops_from_shipment( EXPORTING is_events = is_events IMPORTING et_stops = lt_stops ). LOOP AT lt_stops ASSIGNING FIELD-SYMBOL() WHERE loccat = get_location_category( ). IF is_stop_changed( iv_tknum = -tknum iv_tsnum = -tsnum ) = lif_ef_constants=>cs_condition-true. DATA(lv_evtcnt) = lcl_sh_tools=>get_next_event_counter( ). READ TABLE mt_vtts_new ASSIGNING FIELD-SYMBOL() WITH KEY tknum = -tknum tsnum = -tsnum BINARY SEARCH. IF sy-subrc = 0. ct_trackingheader = VALUE #( BASE ct_trackingheader ( language = sy-langu trxcod = lif_app_constants=>cs_trxcod-sh_number trxid = -tknum evtcnt = lv_evtcnt evtid = get_eventid( ) evtdat = lcl_tools=>get_field_of_structure( ir_struct_data = REF #( ) iv_field_name = get_date_field( ) ) evttim = lcl_tools=>get_field_of_structure( ir_struct_data = REF #( ) iv_field_name = get_time_field( ) ) evtzon = lcl_tools=>get_system_time_zone( ) ) ). ct_eventid_map = VALUE #( BASE ct_eventid_map ( eventid = is_events-eventid evtcnt = lv_evtcnt ) ). ct_tracklocation = VALUE #( BASE ct_tracklocation ( evtcnt = lv_evtcnt loccod = -loctype locid1 = -locid locid2 = -stopid ) ). IF is_location_required( ) = abap_true. ct_trackparameters = VALUE #( BASE ct_trackparameters ( evtcnt = lv_evtcnt param_name = lif_app_constants=>cs_event_param-location_id param_value = -locid ) ( evtcnt = lv_evtcnt param_name = lif_app_constants=>cs_event_param-location_type param_value = -loctype ) ). ENDIF. ELSE. MESSAGE e005(zpof_gtt) WITH |{ -tknum }{ -tsnum }| 'VTTK' INTO DATA(lv_dummy). lcl_tools=>throw_exception( ). ENDIF. ENDIF. ENDLOOP. ENDMETHOD. ENDCLASS. ********************************************************************** *** Shipment Header Departure Event ********************************** ********************************************************************** CLASS lcl_ae_filler_sh_header_dep DEFINITION INHERITING FROM lcl_ae_filler_sh_header_bs. PROTECTED SECTION. METHODS get_date_field REDEFINITION. METHODS get_eventid REDEFINITION. METHODS get_location_category REDEFINITION. METHODS get_time_field REDEFINITION. METHODS is_location_required REDEFINITION. ENDCLASS. CLASS lcl_ae_filler_sh_header_dep IMPLEMENTATION. METHOD get_date_field. rv_field = 'DATBG'. ENDMETHOD. METHOD get_eventid. rv_eventid = lif_app_constants=>cs_milestone-sh_departure. ENDMETHOD. METHOD get_location_category. rv_loccat = lif_app_constants=>cs_loccat-departure. ENDMETHOD. METHOD get_time_field. rv_field = 'UATBG'. ENDMETHOD. METHOD is_location_required. rv_result = abap_false. ENDMETHOD. ENDCLASS. ********************************************************************** *** Shipment Header Arrival Event ************************************ ********************************************************************** CLASS lcl_ae_filler_sh_header_arr DEFINITION INHERITING FROM lcl_ae_filler_sh_header_bs. PROTECTED SECTION. METHODS get_date_field REDEFINITION. METHODS get_eventid REDEFINITION. METHODS get_location_category REDEFINITION. METHODS get_time_field REDEFINITION. METHODS is_location_required REDEFINITION. ENDCLASS. CLASS lcl_ae_filler_sh_header_arr IMPLEMENTATION. METHOD get_date_field. rv_field = 'DATEN'. ENDMETHOD. METHOD get_eventid. rv_eventid = lif_app_constants=>cs_milestone-sh_arrival. ENDMETHOD. METHOD get_location_category. rv_loccat = lif_app_constants=>cs_loccat-arrival. ENDMETHOD. METHOD get_time_field. rv_field = 'UATEN'. ENDMETHOD. METHOD is_location_required. rv_result = abap_true. ENDMETHOD. ENDCLASS. ",14597,True,3463.0133126989454,median "#include #define CATCH_CONFIG_RUNNER bool write_expected = false; int main(int argc, char* argv[]) { Catch::Session session; auto cli = session.cli() | Catch::clara::Opt(write_expected)[""--write""](""Write .expected files""); session.cli(cli); auto ret = session.applyCommandLine(argc, argv); if (ret) return ret; return session.run(); } struct CompareFile { std::string expected_path; std::string actual_path; std::ofstream file; CompareFile(const std::string& name) : expected_path(""eden-test-data/"" + name + "".expected""), actual_path(""eden-test-data/"" + name + "".actual""), file{actual_path} { eosio::check(file.is_open(), ""failed to open "" + actual_path); } void compare() { file.close(); if (write_expected) eosio::execute(""cp "" + actual_path + "" "" + expected_path); else eosio::check(!eosio::execute(""diff "" + expected_path + "" "" + actual_path), ""file mismatch between "" + expected_path + "", "" + actual_path); } auto& write_events(eosio::test_chain& chain) { uint32_t last_block = 1; while (auto history = chain.get_history(last_block + 1)) { for (auto& ttrace : history->traces) { std::visit( [&](auto& ttrace) { for (auto& atrace : ttrace.action_traces) { std::visit( [&](auto& atrace) { if (atrace.receiver == ""eosio.null""_n && atrace.act.name == ""eden.events""_n) { std::vector events; from_bin(events, atrace.act.data); for (auto& event : events) { std::string str; eosio::pretty_stream< eosio::time_point_include_z_stream> stream{str}; to_json(event, stream); file << str << ""\\n""; } } }, atrace); } }, ttrace); } ++last_block; } return *this; } // write_events }; // CompareFile TEST_CASE(""genesis NFT pre-setup"") { eden_tester t; t.eden_gm.act( ""eden.gm""_n, ""eden.gm""_n, true, std::vector{""eden.gm""_n}, std::vector{""eden.gm""_n}, 0.05, atomicassets::attribute_map{}); std::vector schema{{""account"", ""string""}, {""name"", ""string""}, {""img"", ""ipfs""}, {""bio"", ""string""}, {""social"", ""string""}, {""video"", ""ipfs""}}; t.eden_gm.act(""eden.gm""_n, ""eden.gm""_n, eden::schema_name, schema); t.eden_gm.act( ""Eden"", eosio::symbol(""EOS"", 4), s2a(""10.0000 EOS""), std::vector{""alice""_n, ""pip""_n, ""egeon""_n}, ""QmTYqoPYf7DiVebTnvwwFdTgsYXg2RnuPrt8uddjfW2kHS"", attribute_map{}, s2a(""1.0000 EOS""), 7 * 24 * 60 * 60, """", 6, ""15:30""); } TEST_CASE(""genesis NFT pre-setup with incorrect schema"") { eden_tester t; t.eden_gm.act( ""eden.gm""_n, ""eden.gm""_n, true, std::vector{""eden.gm""_n}, std::vector{""eden.gm""_n}, 0.05, atomicassets::attribute_map{}); std::vector schema{{""account"", ""uint64""}, {""name"", ""string""}}; t.eden_gm.act(""eden.gm""_n, ""eden.gm""_n, eden::schema_name, schema); auto trace = t.eden_gm.trace( ""Eden"", eosio::symbol(""EOS"", 4), s2a(""10.0000 EOS""), std::vector{""alice""_n, ""pip""_n, ""egeon""_n}, ""QmTYqoPYf7DiVebTnvwwFdTgsYXg2RnuPrt8uddjfW2kHS"", attribute_map{}, s2a(""1.0000 EOS""), 7 * 24 * 60 * 60, """", 6, ""15:30""); expect(trace, ""there already is an attribute with the same name""); } TEST_CASE(""genesis NFT pre-setup with compatible schema"") { eden_tester t; t.eden_gm.act( ""eden.gm""_n, ""eden.gm""_n, true, std::vector{""eden.gm""_n}, std::vector{""eden.gm""_n}, 0.05, atomicassets::attribute_map{}); std::vector schema{{""social"", ""string""}, {""pi"", ""float""}, {""video"", ""ipfs""}, {""account"", ""string""}, {""name"", ""string""}}; t.eden_gm.act(""eden.gm""_n, ""eden.gm""_n, eden::schema_name, schema); t.eden_gm.act( ""Eden"", eosio::symbol(""EOS"", 4), s2a(""10.0000 EOS""), std::vector{""alice""_n, ""pip""_n, ""egeon""_n}, ""QmTYqoPYf7DiVebTnvwwFdTgsYXg2RnuPrt8uddjfW2kHS"", attribute_map{}, s2a(""1.0000 EOS""), 7 * 24 * 60 * 60, """", 6, ""15:30""); } TEST_CASE(""genesis"") { eden_tester t; t.eden_gm.act( ""Eden"", eosio::symbol(""EOS"", 4), s2a(""10.0000 EOS""), std::vector{""alice""_n, ""pip""_n, ""egeon""_n}, ""QmTYqoPYf7DiVebTnvwwFdTgsYXg2RnuPrt8uddjfW2kHS"", attribute_map{}, s2a(""1.0000 EOS""), 7 * 24 * 60 * 60, """", 6, ""15:30""); CHECK(get_eden_membership(""alice""_n).status() == eden::member_status::pending_membership); CHECK(get_eden_membership(""pip""_n).status() == eden::member_status::pending_membership); CHECK(get_eden_membership(""egeon""_n).status() == eden::member_status::pending_membership); t.alice.act(1, alice_profile); t.pip.act(2, pip_profile); t.egeon.act(3, egeon_profile); CHECK(get_eden_account(""alice""_n) == std::nullopt); CHECK(get_token_balance(""alice""_n) == s2a(""1000.0000 EOS"")); t.alice.act(""alice""_n, ""eden.gm""_n, s2a(""100.0000 EOS""), ""memo""); t.pip.act(""pip""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); t.egeon.act(""egeon""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); CHECK(get_eden_account(""alice""_n) != std::nullopt); CHECK(get_eden_account(""alice""_n)->balance() == s2a(""100.0000 EOS"")); CHECK(get_token_balance(""alice""_n) == s2a(""900.0000 EOS"")); t.alice.act(""alice""_n, 1, s2a(""10.0000 EOS"")); t.pip.act(""pip""_n, 2, s2a(""10.0000 EOS"")); t.eden_gm.act( ""bertie""_n, t.chain.get_head_block_info().timestamp.to_time_point() + eosio::days(1)); t.egeon.act(""egeon""_n, 3, s2a(""10.0000 EOS"")); CHECK(get_globals().stage == eden::contract_stage::genesis); t.bertie.act(4, bertie_profile); t.bertie.act(""bertie""_n, ""eden.gm""_n, s2a(""100.0000 EOS""), ""memo""); t.bertie.act(""bertie""_n, 4, s2a(""10.0000 EOS"")); CHECK(get_eden_account(""alice""_n) != std::nullopt); CHECK(get_eden_account(""alice""_n)->balance() == s2a(""90.0000 EOS"")); CHECK(get_token_balance(""alice""_n) == s2a(""900.0000 EOS"")); CHECK(get_eden_membership(""alice""_n).status() == eden::member_status::active_member); CHECK(get_eden_membership(""pip""_n).status() == eden::member_status::active_member); CHECK(get_eden_membership(""egeon""_n).status() == eden::member_status::active_member); CHECK(get_eden_membership(""bertie""_n).status() == eden::member_status::active_member); CHECK(get_globals().stage == eden::contract_stage::active); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 4); { auto template_id = get_eden_membership(""alice""_n).nft_template_id(); expect(t.eden_gm.trace( ""eden.gm""_n, ""eden.gm""_n, eden::schema_name, template_id, ""alice""_n, eden::atomicassets::attribute_map(), eden::atomicassets::attribute_map{}, std::vector()), ""maxsupply has already been reached""); } // Verify that all members have the same set of NFTs std::vector expected_assets; for (auto member : {""alice""_n, ""pip""_n, ""egeon""_n, ""bertie""_n}) { expected_assets.push_back(get_eden_membership(member).nft_template_id()); } std::sort(expected_assets.begin(), expected_assets.end()); for (auto member : {""alice""_n, ""pip""_n, ""egeon""_n, ""bertie""_n, ""atomicmarket""_n}) { INFO(member.to_string() << ""'s assets""); auto assets = eden::atomicassets::assets_by_owner(eden::atomic_assets_account, member); std::sort(assets.begin(), assets.end()); CHECK(assets == expected_assets); } } TEST_CASE(""genesis expiration"") { eden_tester t; t.eden_gm.act(""Eden"", eosio::symbol(""EOS"", 4), s2a(""10.0000 EOS""), std::vector{""alice""_n, ""pip""_n, ""egeon""_n, ""bertie""_n}, ""QmTYqoPYf7DiVebTnvwwFdTgsYXg2RnuPrt8uddjfW2kHS"", attribute_map{}, s2a(""1.0000 EOS""), 14 * 24 * 60 * 60, """", 6, ""15:30""); CHECK(get_eden_membership(""alice""_n).status() == eden::member_status::pending_membership); CHECK(get_eden_membership(""pip""_n).status() == eden::member_status::pending_membership); CHECK(get_eden_membership(""egeon""_n).status() == eden::member_status::pending_membership); CHECK(get_eden_membership(""bertie""_n).status() == eden::member_status::pending_membership); t.alice.act(1, alice_profile); t.pip.act(2, pip_profile); t.egeon.act(3, egeon_profile); t.alice.act(""alice""_n, ""eden.gm""_n, s2a(""100.0000 EOS""), ""memo""); t.pip.act(""pip""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); t.egeon.act(""egeon""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); t.alice.act(""alice""_n, 1, s2a(""10.0000 EOS"")); t.pip.act(""pip""_n, 2, s2a(""10.0000 EOS"")); t.egeon.act(""egeon""_n, 3, s2a(""10.0000 EOS"")); CHECK(get_eden_membership(""alice""_n).status() == eden::member_status::active_member); CHECK(get_eden_membership(""pip""_n).status() == eden::member_status::active_member); CHECK(get_eden_membership(""egeon""_n).status() == eden::member_status::active_member); CHECK(get_globals().stage == eden::contract_stage::genesis); // Wait for Bertie's genesis invitation to expire t.chain.start_block(7 * 24 * 60 * 60 * 1000); expect(t.alice.trace(42), ""Nothing to do""); // Extend Bertie's invitation expect(t.eden_gm.trace( 4, t.chain.get_head_block_info().timestamp.to_time_point() + eosio::days(8)), ""too far in the future""); expect(t.eden_gm.trace( 4, t.chain.get_head_block_info().timestamp.to_time_point() - eosio::days(8)), ""in the past""); t.chain.start_block(10 * 1000); expect(t.eden_gm.trace( 4, t.chain.get_head_block_info().timestamp.to_time_point()), ""in the past""); t.eden_gm.trace( 4, t.chain.get_head_block_info().timestamp.to_time_point() + eosio::milliseconds(10500)); expect(t.alice.trace(42), ""Nothing to do""); t.chain.start_block(10 * 1000); expect(t.alice.trace(42), ""Nothing to do""); t.chain.start_block(); t.alice.act(42); CHECK(get_globals().stage == eden::contract_stage::active); CHECK(members(""eden.gm""_n).stats().active_members == 3); CHECK(members(""eden.gm""_n).stats().pending_members == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 3); } TEST_CASE(""genesis replacement"") { eden_tester t; t.eden_gm.act( ""Eden"", eosio::symbol(""EOS"", 4), s2a(""10.0000 EOS""), std::vector{""alice""_n, ""pip""_n, ""egeon""_n}, ""QmTYqoPYf7DiVebTnvwwFdTgsYXg2RnuPrt8uddjfW2kHS"", attribute_map{}, s2a(""1.0000 EOS""), 7 * 24 * 60 * 60, """", 6, ""15:30""); CHECK(get_eden_membership(""alice""_n).status() == eden::member_status::pending_membership); CHECK(get_eden_membership(""pip""_n).status() == eden::member_status::pending_membership); CHECK(get_eden_membership(""egeon""_n).status() == eden::member_status::pending_membership); t.alice.act(1, alice_profile); t.alice.act(""alice""_n, ""eden.gm""_n, s2a(""100.0000 EOS""), ""memo""); t.alice.act(""alice""_n, 1, s2a(""10.0000 EOS"")); t.eden_gm.act(""eden.gm""_n, 2); t.eden_gm.act( ""bertie""_n, t.chain.get_head_block_info().timestamp.to_time_point() + eosio::days(1)); CHECK(get_eden_membership(""alice""_n).status() == eden::member_status::active_member); CHECK(get_eden_membership(""egeon""_n).status() == eden::member_status::pending_membership); CHECK(get_eden_membership(""bertie""_n).status() == eden::member_status::pending_membership); CHECK(members(""eden.gm""_n).stats().active_members == 1); CHECK(members(""eden.gm""_n).stats().pending_members == 2); CHECK(get_table_size() == 2); CHECK(get_table_size() == 4); t.egeon.act(3, egeon_profile); t.bertie.act(4, bertie_profile); t.egeon.act(""egeon""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); t.bertie.act(""bertie""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); t.egeon.act(""egeon""_n, 3, s2a(""10.0000 EOS"")); t.bertie.act(""bertie""_n, 4, s2a(""10.0000 EOS"")); CHECK(get_eden_membership(""egeon""_n).status() == eden::member_status::active_member); CHECK(get_eden_membership(""bertie""_n).status() == eden::member_status::active_member); CHECK(get_globals().stage == eden::contract_stage::active); CHECK(members(""eden.gm""_n).stats().active_members == 3); CHECK(members(""eden.gm""_n).stats().pending_members == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 3); // Verify that all members have the same set of NFTs std::vector expected_assets; for (auto member : {""alice""_n, ""egeon""_n, ""bertie""_n}) { expected_assets.push_back(get_eden_membership(member).nft_template_id()); } std::sort(expected_assets.begin(), expected_assets.end()); for (auto member : {""alice""_n, ""egeon""_n, ""bertie""_n, ""atomicmarket""_n}) { INFO(member.to_string() << ""'s assets""); auto assets = eden::atomicassets::assets_by_owner(eden::atomic_assets_account, member); std::sort(assets.begin(), assets.end()); CHECK(assets == expected_assets); } // The removed member should only have NFTs issued before his removal CHECK(eden::atomicassets::assets_by_owner(eden::atomic_assets_account, ""pip""_n) == std::vector{ static_cast(get_eden_membership(""alice""_n).nft_template_id())}); } TEST_CASE(""induction"") { eden_tester t; t.genesis(); for (auto member : {""alice""_n, ""pip""_n, ""egeon""_n}) { t.chain.as(member).act(member, eosio::public_key{}); } t.alice.act(4, ""alice""_n, ""bertie""_n, std::vector{""pip""_n, ""egeon""_n}); t.bertie.act(""bertie""_n, eosio::public_key{}); t.alice.act(""alice""_n, 4, std::vector(4), eosio::bytes{}, std::nullopt); CHECK(get_table_size(""induction""_n) == 1); t.bertie.act(""bertie""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); CHECK(get_eden_membership(""bertie""_n).status() == eden::member_status::pending_membership); // cannot endorse before video and profile are set auto blank_hash_data = eosio::convert_to_bin(std::tuple(std::string{}, eden::new_member_profile{})); expect(t.alice.trace( ""alice""_n, 4, eosio::sha256(blank_hash_data.data(), blank_hash_data.size())), ""not set""); expect(t.bertie.trace(5, ""bertie""_n, ""ahab""_n, std::vector{""pip""_n, ""egeon""_n}), ""inactive member bertie""); expect(t.alice.trace(6, ""alice""_n, ""bertie""_n, std::vector{""pip""_n, ""egeon""_n}), ""already in progress""); expect(t.alice.trace(7, ""alice""_n, ""ahab""_n, std::vector{""alice""_n, ""egeon""_n}), ""inviter cannot be in the witnesses list""); expect(t.alice.trace(8, ""alice""_n, ""ahab""_n, std::vector{""pip""_n, ""pip""_n}), ""duplicated entry""); expect( t.alice.trace(9, ""alice""_n, ""ahab""_n, std::vector{""pip""_n, ""bertie""_n}), ""inactive member bertie""); expect( t.alice.trace(10, ""alice""_n, ""void""_n, std::vector{""pip""_n, ""egeon""_n}), ""Account void does not exist""); std::string bertie_video = ""QmTYqoPYf7DiVebTnvwwFdTgsYXg2RnuPrt8uddjfW2kHS""; t.bertie.act(4, bertie_profile); t.alice.act(""alice""_n, 4, bertie_video); // Can be inviter or witness expect(t.bertie.trace(""bertie""_n, 4, s2a(""10.0000 EOS"")), ""induction is not fully endorsed""); auto hash_data = eosio::convert_to_bin(std::tuple(bertie_video, bertie_profile)); auto induction_hash = eosio::sha256(hash_data.data(), hash_data.size()); expect(t.bertie.trace(""alice""_n, 4, induction_hash), ""missing authority of alice""); expect(t.bertie.trace(""bertie""_n, 4, induction_hash), ""Induction can only be endorsed by inviter or a witness""); expect(t.alice.trace( ""alice""_n, 4, eosio::sha256(hash_data.data(), hash_data.size() - 1)), ""Outdated endorsement""); auto endorse_all = [&] { t.alice.act(""alice""_n, 4, induction_hash); t.pip.act(""pip""_n, 4, induction_hash); t.egeon.act(""egeon""_n, 4, induction_hash); }; endorse_all(); t.chain.start_block(); expect(t.alice.trace(""alice""_n, 4, induction_hash), ""Already endorsed""); // changing the profile resets endorsements t.bertie.act(4, bertie_profile); expect(t.bertie.trace(""bertie""_n, 4, s2a(""10.0000 EOS"")), ""induction is not fully endorsed""); t.chain.start_block(); endorse_all(); // changing the video resets endorsements t.pip.act(""pip""_n, 4, bertie_video); expect(t.bertie.trace(""bertie""_n, 4, s2a(""10.0000 EOS"")), ""induction is not fully endorsed""); t.chain.start_block(); endorse_all(); t.bertie.act(""bertie""_n, 4, s2a(""10.0000 EOS"")); CHECK(get_eden_membership(""bertie""_n).status() == eden::member_status::active_member); CHECK(get_table_size(""induction""_n) == 0); } TEST_CASE(""resignation"") { eden_tester t; t.genesis(); t.alice.act(""alice""_n); CHECK(members{""eden.gm""_n}.is_new_member(""alice""_n)); } TEST_CASE(""board resignation"") { eden_tester t; t.genesis(); t.run_election(); t.induct_n(4); t.alice.act(""alice""_n); t.egeon.act(""egeon""_n); t.pip.act(""pip""_n); } TEST_CASE(""auction"") { eden_tester t; t.genesis(); t.ahab.act(""ahab""_n, eden::atomic_market_account, s2a(""10.0000 EOS""), ""deposit""); t.ahab.act(""ahab""_n, 1, s2a(""10.0000 EOS""), eosio::name{}); t.chain.start_block(7 * 24 * 60 * 60 * 1000); t.chain.start_block(); t.ahab.act(1); t.eden_gm.act(1); } TEST_CASE(""auction batch claim"") { eden_tester t; t.genesis(); t.ahab.act(""ahab""_n, eden::atomic_market_account, s2a(""10.0000 EOS""), ""deposit""); t.ahab.act(""ahab""_n, 1, s2a(""10.0000 EOS""), eosio::name{}); t.chain.start_block(7 * 24 * 60 * 60 * 1000); t.chain.start_block(); t.ahab.act(1); auto old_balance = get_token_balance(""eden.gm""_n); t.eden_gm.act(42); auto new_balance = get_token_balance(""eden.gm""_n); // 0.5 EOS left deposited in atomicmarket // 0.1 EOS to each of the maker and taker marketplaces CHECK(new_balance - old_balance == s2a(""9.3000 EOS"")); } TEST_CASE(""auction migration"") { eden_tester t; t.genesis(); t.eden_gm.act(); t.ahab.act(""ahab""_n, eden::atomic_market_account, s2a(""10.0000 EOS""), ""deposit""); t.ahab.act(""ahab""_n, 1, s2a(""10.0000 EOS""), eosio::name{}); t.chain.start_block(7 * 24 * 60 * 60 * 1000); t.chain.start_block(); t.ahab.act(1); auto old_balance = get_token_balance(""eden.gm""_n); expect(t.eden_gm.trace(42), ""Nothing to do""); while (true) { t.chain.start_block(); auto trace = t.eden_gm.trace(1); if (trace.except) { expect(trace, ""Nothing to do""); break; } } t.eden_gm.act(42); auto new_balance = get_token_balance(""eden.gm""_n); // 0.5 EOS left deposited in atomicmarket // 0.1 EOS to each of the maker and taker marketplaces CHECK(new_balance - old_balance == s2a(""9.3000 EOS"")); } TEST_CASE(""induction gc"") { eden_tester t; t.genesis(); auto test_accounts = make_names(38); t.create_accounts(test_accounts); // induct some members for (std::size_t i = 0; i < 34; ++i) { t.chain.start_block(); // don't run out of cpu auto account = test_accounts.at(i); auto induction_id = i + 4; t.alice.act(induction_id, ""alice""_n, account, std::vector{""pip""_n, ""egeon""_n}); t.finish_induction(induction_id, ""alice""_n, account, {""pip""_n, ""egeon""_n}); } CHECK(members(""eden.gm""_n).stats().active_members == 37); CHECK(members(""eden.gm""_n).stats().pending_members == 0); // clear the auctions t.chain.start_block(8 * 24 * 60 * 60 * 1000); t.alice.act(64); for (std::size_t i = 0; i <= 2; ++i) { // many inductions for the same invitee t.chain.start_block(); auto member_idx = i + 34; auto invitee = test_accounts.at(34 + i); uint64_t base_induction_id = 34 + 4 + i * 64; for (std::size_t j = 0; j < 32 + i; ++j) { auto inviter = test_accounts.at(j); auto induction_id = base_induction_id + j; t.chain.as(inviter).act(induction_id, inviter, invitee, std::vector{""pip""_n, ""egeon""_n}); } } expect(t.alice.trace(32), ""Nothing to do""); // lots of invites; none are available for gc // Complete some invites for (std::size_t i = 0; i <= 2; ++i) { t.chain.start_block(); auto member_idx = i + 34; auto invitee = test_accounts.at(34 + i); uint64_t base_induction_id = 34 + 4 + i * 64; t.finish_induction(base_induction_id, test_accounts.at(0), invitee, {""pip""_n, ""egeon""_n}); CHECK(members(""eden.gm""_n).stats().active_members == 37 + i + 1); CHECK(members(""eden.gm""_n).stats().pending_members == 2 - i); } CHECK(get_table_size() == 1); CHECK(get_table_size() == 3); CHECK(get_table_size() == 0); CHECK(get_table_size() > 0); t.ahab.act(32); // ahab is not a member, but gc needs no permissions // clear the auctions t.chain.start_block(8 * 24 * 60 * 60 * 1000); t.alice.act(64); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); // An expired invitation t.alice.act(42, ""alice""_n, test_accounts.at(37), std::vector{""pip""_n, ""egeon""_n}); t.chain.start_block(1000 * 60 * 60 * 24 * 7); expect(t.alice.trace(32), ""Nothing to do""); t.chain.start_block(); t.alice.act(32); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); CHECK(get_table_size() == 0); CHECK(members(""eden.gm""_n).stats().active_members == 40); CHECK(members(""eden.gm""_n).stats().pending_members == 0); } TEST_CASE(""induction cancelling"") { eden_tester t; t.genesis(); // inviter can cancel t.alice.act(101, ""alice""_n, ""bertie""_n, std::vector{""pip""_n, ""egeon""_n}); t.alice.act(""alice""_n, 101); CHECK(get_table_size() == 0); // invitee can cancel t.alice.act(102, ""alice""_n, ""bertie""_n, std::vector{""pip""_n, ""egeon""_n}); t.bertie.act(""bertie""_n, 102); CHECK(get_table_size() == 0); // endorser can cancel t.alice.act(103, ""alice""_n, ""bertie""_n, std::vector{""pip""_n, ""egeon""_n}); t.pip.act(""pip""_n, 103); CHECK(get_table_size() == 0); t.alice.act(104, ""alice""_n, ""bertie""_n, std::vector{""pip""_n, ""egeon""_n}); expect(t.ahab.trace(""ahab""_n, 104), ""Induction can only be canceled by an endorser or the invitee itself""); CHECK(get_table_size() == 1); CHECK(get_eden_membership(""bertie""_n).status() == eden::member_status::pending_membership); } TEST_CASE(""deposit and spend"") { eden_tester t; t.eden_gm.act( ""Eden"", eosio::symbol(""EOS"", 4), s2a(""10.0000 EOS""), std::vector{""alice""_n, ""pip""_n, ""egeon""_n}, ""QmTYqoPYf7DiVebTnvwwFdTgsYXg2RnuPrt8uddjfW2kHS"", attribute_map{}, s2a(""1.0000 EOS""), 7 * 24 * 60 * 60, """", 6, ""15:30""); expect(t.alice.trace(""alice""_n, ""eden.gm""_n, s2a(""10.0000 OTHER""), ""memo""), ""token must be a valid 4,EOS""); expect( t.alice.trace(""alice""_n, ""eden.gm""_n, s2a(""9.9999 EOS""), ""memo""), ""insufficient deposit to open an account""); CHECK(get_eden_account(""alice""_n) == std::nullopt); t.alice.act(""alice""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); CHECK(get_eden_account(""alice""_n) != std::nullopt); CHECK(get_eden_account(""alice""_n)->balance() == s2a(""10.0000 EOS"")); CHECK(get_token_balance(""alice""_n) == s2a(""990.0000 EOS"")); expect(t.pip.trace(""pip""_n, s2a(""10.0000 EOS"")), ""insufficient balance""); expect(t.pip.trace(""alice""_n, s2a(""10.0000 EOS"")), ""missing authority of alice""); expect(t.alice.trace(""alice""_n, s2a(""10.0001 EOS"")), ""insufficient balance""); CHECK(get_eden_account(""alice""_n)->balance() == s2a(""10.0000 EOS"")); CHECK(get_token_balance(""alice""_n) == s2a(""990.0000 EOS"")); t.alice.act(""alice""_n, s2a(""4.0000 EOS"")); CHECK(get_eden_account(""alice""_n)->balance() == s2a(""6.0000 EOS"")); CHECK(get_token_balance(""alice""_n) == s2a(""994.0000 EOS"")); t.alice.act(""alice""_n, s2a(""6.0000 EOS"")); CHECK(get_eden_account(""alice""_n) == std::nullopt); CHECK(get_token_balance(""alice""_n) == s2a(""1000.0000 EOS"")); t.alice.act(""alice""_n, ""eden.gm""_n, s2a(""100.0000 EOS""), ""donate""); CHECK(get_eden_account(""alice""_n) == std::nullopt); CHECK(get_token_balance(""alice""_n) == s2a(""900.0000 EOS"")); } TEST_CASE(""election config"") { auto verify_cfg = [](const auto& config, uint16_t num_participants) { INFO(""participants: "" << num_participants) if (num_participants < 1) { CHECK(config.empty()); } else { CHECK(config.back().num_groups == 1); CHECK(config.front().num_participants == num_participants); for (std::size_t i = 0; i < config.size() - 1; ++i) { CHECK(config[i].num_groups == config[i + 1].num_participants); } // There are at most two group sizes, except for the last round std::set group_sizes; auto early_rounds = config; early_rounds.pop_back(); for (const auto& round_config : early_rounds) { group_sizes.insert(round_config.group_max_size()); if (round_config.num_short_groups()) { group_sizes.insert(round_config.group_max_size() - 1); } } CHECK(group_sizes.size() <= 2); if (group_sizes.size() == 2) { CHECK(*group_sizes.begin() + 1 == *(--group_sizes.end())); } } }; for (uint16_t i = 0; i <= 10000; ++i) { verify_cfg(eden::make_election_config(i), i); } } TEST_CASE(""election"") { eden_tester t; t.genesis(); t.electdonate_all(); { eden::current_election_state_singleton state(""eden.gm""_n, eden::default_scope); auto current = std::get(state.get()); CHECK(eosio::convert_to_json(current.start_time) == ""\\""2020-07-04T15:30:00.000\\""""); } t.skip_to(""2020-07-03T15:29:59.500""); t.electseed(eosio::time_point_sec(0x5f009260u), ""Cannot start seeding yet""); t.chain.start_block(); t.electseed(eosio::time_point_sec(0x5f009260u)); t.skip_to(""2020-07-04T15:29:59.500""); expect(t.alice.trace(1), ""Seeding window is still open""); t.chain.start_block(); t.setup_election(); CHECK(get_table_size() == 0); eden::election_state_singleton results(""eden.gm""_n, eden::default_scope); auto result = std::get(results.get()); // This is likely to change as it depends on the exact random number algorithm and seed CHECK(result.lead_representative == ""egeon""_n); std::sort(result.board.begin(), result.board.end()); CHECK(result.board == std::vector{""alice""_n, ""egeon""_n, ""pip""_n}); } TEST_CASE(""mid-election induction"") { eden_tester t; bool has_bertie = false; t.genesis(); t.electdonate_all(); SECTION(""pre-registration"") { t.skip_to(""2020-06-04T15:29:59.500""); has_bertie = true; t.induct(""bertie""_n); } SECTION(""registration"") { t.skip_to(""2020-06-04T15:30:00.000""); has_bertie = true; t.induct(""bertie""_n); } t.skip_to(""2020-07-03T15:30:00.000""); SECTION(""pre-seed"") { has_bertie = true; t.induct(""bertie""_n); } t.electseed(s2t(""2020-07-03T15:30:00.000"")); SECTION(""post-seed"") { has_bertie = true; t.induct(""bertie""_n); } t.skip_to(""2020-07-04T15:30:00.000""); for (int i = 0;; ++i) { DYNAMIC_SECTION(""electprocess"" << i) { has_bertie = true; t.induct(""bertie""_n); } auto trace = t.eden_gm.trace(1); if (trace.except) { expect(trace, ""Nothing to do""); break; } t.chain.start_block(); } eden::election_state_singleton results(""eden.gm""_n, eden::default_scope); auto result = std::get(results.get()); std::sort(result.board.begin(), result.board.end()); CHECK(result.board == std::vector{""alice""_n, ""egeon""_n, ""pip""_n}); if (has_bertie) { CHECK(get_table_size() == 4); CHECK(get_eden_membership(""bertie""_n).election_participation_status() == eden::not_in_election); } else { CHECK(get_table_size() == 3); } CHECK(eden::members{""eden.gm""_n}.stats().ranks == std::vector{2, 1}); } TEST_CASE(""election with multiple rounds"") { constexpr std::size_t num_accounts = 200; // 10000 takes too long eden_tester t; t.genesis(); t.eden_gm.act(s2t(""2020-07-04T15:30:00.000"")); auto test_accounts = make_names(num_accounts - 3); t.create_accounts(test_accounts); for (auto account : test_accounts) { t.chain.start_block(); t.alice.act(42, ""alice""_n, account, std::vector{""pip""_n, ""egeon""_n}); t.finish_induction(42, ""alice""_n, account, {""pip""_n, ""egeon""_n}); } t.electdonate_all(); t.alice.act(""alice""_n, eosio::public_key{}); t.pip.act(""pip""_n, eosio::public_key{}); t.egeon.act(""egeon""_n, eosio::public_key{}); for (auto account : test_accounts) { t.chain.start_block(); t.chain.as(account).act(account, eosio::public_key{}); } t.skip_to(""2020-07-03T15:30:00.000""); t.electseed(eosio::time_point_sec(0x5f009260)); t.skip_to(""2020-07-04T15:30:00.000""); t.setup_election(); uint8_t round = 0; // With 200 members, there should be three rounds CHECK(get_table_size() == 200); t.alice.act(""alice""_n, 0, std::vector{{}, {}, {}, {}}, eosio::bytes{}, std::nullopt); t.generic_group_vote(t.get_current_groups(), round++); CHECK(get_table_size() == 48); t.alice.act(0, ""alice""_n, ""Qmb7WmZiSDXss5HfuKfoSf6jxTDrHzr8AoAUDeDMLNDuws""); t.alice.act(""alice""_n, 1, std::vector{{}, {}, {}, {}}, eosio::bytes{}, std::nullopt); t.generic_group_vote(t.get_current_groups(), round++); CHECK(get_table_size() == 12); t.alice.act(""alice""_n, 2, std::vector{{}, {}, {}, {}}, eosio::bytes{}, std::nullopt); t.generic_group_vote(t.get_current_groups(), round++); CHECK(get_table_size() == 3); t.electseed(s2t(""2020-07-04T19:30:00.000"")); t.chain.start_block((15 * 60 + 30) * 60 * 1000); t.chain.start_block(2 * 60 * 60 * 1000); t.alice.act(256); CHECK(get_table_size() == 0); CHECK(get_table_size(""election""_n) == 0); eden::election_state_singleton results(""eden.gm""_n, eden::default_scope); auto result = std::get(results.get()); // alice wins at every level but the last, because everyone votes for the member with the lowest name CHECK(std::find(result.board.begin(), result.board.end(), ""alice""_n) != result.board.end()); t.alice.act(1, ""alice""_n, ""Qmb7WmZiSDXss5HfuKfoSf6jxTDrHzr8AoAUDeDMLNDuws""); t.alice.act(2, ""alice""_n, ""Qmb7WmZiSDXss5HfuKfoSf6jxTDrHzr8AoAUDeDMLNDuws""); CHECK(members(""eden.gm""_n).stats().ranks == std::vector{200 - 48, 48 - 12, 12 - 3, 3 - 1, 1}); } TEST_CASE(""budget distribution"") { eden_tester t; t.genesis(); t.set_balance(s2a(""36.0000 EOS"")); t.run_election(); t.alice.act(250); CHECK(t.get_total_budget() == s2a(""1.8000 EOS"")); // Skip forward to the next distribution t.skip_to(""2020-08-03T15:29:59.500""); expect(t.alice.trace(250), ""Nothing to do""); t.chain.start_block(); t.alice.act(250); CHECK(t.get_total_budget() == s2a(""3.5100 EOS"")); // Skip into the next election t.skip_to(""2021-01-02T15:30:00.000""); t.alice.act(1); t.alice.act(5000); CHECK(t.get_total_budget() == s2a(""10.9435 EOS"")); expect(t.alice.trace(""alice""_n, s2t(""2020-07-04T15:30:00.000""), 1, ""egeon""_n, s2a(""1.8001 EOS""), ""memo""), ""insufficient balance""); expect(t.alice.trace(""alice""_n, s2t(""2020-07-04T15:30:00.000""), 1, ""egeon""_n, s2a(""-1.0000 EOS""), ""memo""), ""amount must be positive""); expect(t.alice.trace(""alice""_n, s2t(""2020-07-04T15:30:00.000""), 1, ""ahab""_n, s2a(""1.0000 EOS""), ""memo""), ""member ahab not found""); t.alice.act(""alice""_n, s2t(""2020-07-04T15:30:00.000""), 1, ""egeon""_n, s2a(""1.8000 EOS""), ""memo""); CHECK(get_eden_account(""egeon""_n)->balance() == s2a(""1.8000 EOS"")); expect(t.alice.trace(""alice""_n, ""ahab""_n, s2a(""10.0000 EOS""), ""memo""), ""member ahab not found""); t.ahab.act(""ahab""_n, ""eden.gm""_n, s2a(""10.0000 EOS""), ""memo""); expect(t.ahab.trace(""ahab""_n, ""egeon""_n, s2a(""10.0000 EOS""), ""memo""), ""member ahab not found""); expect(t.alice.trace(""alice""_n, ""egeon""_n, s2a(""-1.0000 EOS""), ""memo""), ""amount must be positive""); t.alice.act(""alice""_n, ""egeon""_n, s2a(""10.0000 EOS""), ""memo""); CHECK(get_eden_account(""egeon""_n)->balance() == s2a(""11.8000 EOS"")); CHECK(get_eden_account(""alice""_n)->balance() == s2a(""80.0000 EOS"")); CHECK(get_eden_account(""ahab""_n)->balance() == s2a(""10.0000 EOS"")); } TEST_CASE(""budget distribution triggered by donation"") { eden_tester t; t.genesis(); t.electdonate_all(); t.set_balance(s2a(""100.0000 EOS"")); t.run_election(); t.distribute(1); CHECK(t.get_total_budget() == s2a(""5.0000 EOS"")); t.skip_to(""2020-08-03T15:29:59.500""); t.set_balance(s2a(""100.0000 EOS"")); t.chain.start_block(); CHECK(t.get_total_budget() == s2a(""5.0000 EOS"")); t.eosio_token.act(""eosio.token""_n, ""eden.gm""_n, s2a(""5.0000 EOS""), ""memo""); CHECK(t.get_total_budget() == s2a(""10.0000 EOS"")); t.skip_to(""2020-09-02T15:30:00.0000""); t.eosio_token.act(""eosio.token""_n, ""eden.gm""_n, s2a(""5.0000 EOS""), ""memo""); CHECK(t.get_total_budget() == s2a(""15.0000 EOS"")); t.skip_to(""2020-10-02T15:30:00.0000""); t.eosio_token.act(""eosio.token""_n, ""eden.gm""_n, s2a(""5.0000 EOS""), ""memo""); CHECK(t.get_total_budget() == s2a(""20.0000 EOS"")); } TEST_CASE(""budget distribution minimum period"") { eden_tester t; t.genesis(); t.set_balance(s2a(""36.0000 EOS"")); t.run_election(); t.electdonate_all(); t.set_balance(s2a(""100000.0000 EOS"")); t.eden_gm.act(s2t(""2020-09-02T15:30:01.000"")); t.run_election(); std::map expected{ {s2t(""2020-07-04T15:30:00.000""), s2a(""1.8000 EOS"")}, {s2t(""2020-08-03T15:30:00.000""), s2a(""5000.0000 EOS"")}, {s2t(""2020-09-02T15:30:00.000""), s2a(""0.0018 EOS"")}, {s2t(""2020-09-02T15:30:01.000""), s2a(""4749.9999 EOS"")}}; CHECK(t.get_budgets_by_period() == expected); } TEST_CASE(""budget distribution exact"") { eden_tester t; t.genesis(); t.set_balance(s2a(""36.0000 EOS"")); t.run_election(); t.electdonate_all(); t.set_balance(s2a(""1000.0000 EOS"")); t.eden_gm.act(s2t(""2020-09-02T15:30:00.000"")); t.run_election(); std::map expected{ {s2t(""2020-07-04T15:30:00.000""), s2a(""1.8000 EOS"")}, {s2t(""2020-08-03T15:30:00.000""), s2a(""50.0000 EOS"")}, {s2t(""2020-09-02T15:30:00.000""), s2a(""47.5000 EOS"")}}; CHECK(t.get_budgets_by_period() == expected); } TEST_CASE(""budget distribution underflow"") { eden_tester t; t.genesis(); t.set_balance(s2a(""36.0000 EOS"")); t.run_election(); t.electdonate_all(); t.set_balance(s2a(""1000.0000 EOS"")); t.eden_gm.act(s2t(""2020-09-02T15:30:01.000"")); t.run_election(); std::map expected{ {s2t(""2020-07-04T15:30:00.000""), s2a(""1.8000 EOS"")}, {s2t(""2020-08-03T15:30:00.000""), s2a(""50.0000 EOS"")}, {s2t(""2020-09-02T15:30:01.000""), s2a(""47.5000 EOS"")}}; CHECK(t.get_budgets_by_period() == expected); } #ifdef ENABLE_SET_TABLE_ROWS TEST_CASE(""budget distribution min"") { eden_tester t; t.genesis(); auto members = make_names(100); t.create_accounts(members); for (auto a : members) { t.chain.start_block(); t.induct(a); } t.set_balance(s2a(""1236.0000 EOS"")); t.run_election(); t.set_balance(s2a(""0.0020 EOS"")); t.skip_to(""2020-08-03T15:30:00.000""); t.distribute(); std::map expected{ {s2t(""2020-07-04T15:30:00.000""), s2a(""61.8000 EOS"")}, {s2t(""2020-08-03T15:30:00.000""), s2a(""0.0001 EOS"")}}; CHECK(t.get_budgets_by_period() == expected); } #endif TEST_CASE(""budget adjustment on resignation"") { eden_tester t; t.genesis(); t.set_balance(s2a(""36.0000 EOS"")); t.run_election(); t.set_balance(s2a(""1000.0000 EOS"")); t.skip_to(""2020-09-02T15:30:00.000""); // alice is satoshi, and receives the whole budget t.alice.act(""alice""_n); std::map expected{}; CHECK(t.get_budgets_by_period() == expected); t.skip_to(""2020-10-02T15:30:00.000""); t.distribute(); CHECK(t.get_budgets_by_period() == expected); CHECK(accounts{""eden.gm""_n, ""owned""_n}.get_account(""master""_n)->balance() == s2a(""1001.8000 EOS"")); } TEST_CASE(""multi budget adjustment on resignation"") { eden_tester t; t.genesis(); auto members = make_names(100); t.create_accounts(members); for (auto a : members) { t.chain.start_block(); t.induct(a); } t.set_balance(s2a(""1236.0000 EOS"")); t.run_election(); t.set_balance(s2a(""10000.0000 EOS"")); t.skip_to(""2020-09-02T15:30:00.000""); auto lead_representative = std::get( eden::election_state_singleton{""eden.gm""_n, eden::default_scope}.get()) .lead_representative; t.chain.as(lead_representative).act(lead_representative); std::map expected{ {s2t(""2020-07-04T15:30:00.000""), s2a(""36.2560 EOS"")}, {s2t(""2020-08-03T15:30:00.000""), s2a(""293.3316 EOS"")}, {s2t(""2020-09-02T15:30:00.000""), s2a(""278.6656 EOS"")}}; CHECK(t.get_budgets_by_period() == expected); t.skip_to(""2020-10-02T15:30:00.000""); t.distribute(); expected.insert({s2t(""2020-10-02T15:30:00.000""), s2a(""10.5028 EOS"")}); CHECK(t.get_budgets_by_period() == expected); } TEST_CASE(""bylaws"") { eden_tester t; t.genesis(); t.induct_n(3); t.run_election(); auto state = std::get( eden::election_state_singleton{""eden.gm""_n, eden::default_scope}.get()); std::string bylaws = ""xxx""; auto bylaws_hash = eosio::sha256(bylaws.data(), bylaws.size()); t.chain.as(state.lead_representative) .act(state.lead_representative, bylaws); int i = 0; SECTION(""basic"") { for (auto board_member : state.board) { if (i++ == 5) break; t.chain.as(board_member).act(board_member, bylaws_hash); } } // Make sure that resigned members are not counted towards the limit SECTION(""resign"") { for (auto board_member : state.board) { if (board_member != state.lead_representative) { if (i++ >= 2) { t.chain.as(board_member).act(board_member, bylaws_hash); } else { t.chain.as(board_member).act(board_member, bylaws_hash); t.chain.as(board_member).act(board_member); } } } } } TEST_CASE(""accounting"") { eden_tester t; t.genesis(); // should now have 30.0000 EOS, with a 90.0000 EOS deposit from alice CHECK(get_token_balance(""eden.gm""_n) == s2a(""120.0000 EOS"")); } TEST_CASE(""pre-genesis balance"") { eden_tester t{[&] { t.eosio_token.act(""eosio.token""_n, ""eden.gm""_n, s2a(""3.1415 EOS""), """"); }}; t.genesis(); CHECK(get_token_balance(""eden.gm""_n) == t.get_total_balance()); } TEST_CASE(""clearall"") { eden_tester t; t.genesis(); t.eden_gm.act(); t.chain.start_block(); t.genesis(); } TEST_CASE(""account migration"") { eden_tester t; t.genesis(); auto sum_accounts = [](eden::account_table_type& table) { auto total = s2a(""0.0000 EOS""); for (auto iter = table.begin(), end = table.end(); iter != end; ++iter) { CHECK(iter->balance().amount > 0); total += iter->balance(); } return total; }; { eden::account_table_type user_table{""eden.gm""_n, eden::default_scope}; eden::account_table_type system_table{""eden.gm""_n, ""owned""_n.value}; CHECK(sum_accounts(user_table) + sum_accounts(system_table) == get_token_balance(""eden.gm""_n)); } t.eden_gm.act(); { eden::account_table_type user_table{""eden.gm""_n, eden::default_scope}; eden::account_table_type system_table{""eden.gm""_n, ""owned""_n.value}; CHECK(sum_accounts(system_table) == s2a(""0.0000 EOS"")); } expect(t.alice.trace(""alice""_n, s2a(""0.4200 EOS"")), ""must be migrated""); while (true) { t.chain.start_block(); t.alice.act(""alice""_n, ""eden.gm""_n, s2a(""15.0000 EOS""), """"); t.alice.act(""alice""_n, s2a(""14.0000 EOS"")); auto trace = t.eden_gm.trace(1); if (trace.except) { expect(trace, ""Nothing to do""); break; } } { eden::account_table_type user_table{""eden.gm""_n, eden::default_scope}; eden::account_table_type system_table{""eden.gm""_n, ""owned""_n.value}; CHECK(sum_accounts(user_table) + sum_accounts(system_table) == get_token_balance(""eden.gm""_n)); } #ifdef ENABLE_SET_TABLE_ROWS t.set_balance(s2a(""0.0000 EOS"")); t.alice.act(""alice""_n, get_eden_account(""alice""_n)->balance()); t.eden_gm.act(""eden.gm""_n, eosio::symbol(""EOS"", 4)); t.eden_gm.act(); t.eden_gm.act(100); #endif } #ifdef ENABLE_SET_TABLE_ROWS TEST_CASE(""settablerows"") { eden_tester t; t.genesis(); t.eden_gm.act( eosio::name(eden::default_scope), std::vector{ eden::current_election_state_registration{s2t(""2020-01-02T00:00:00.0000"")}}); eden::current_election_state_singleton state{""eden.gm""_n, eden::default_scope}; auto value = std::get(state.get()); CHECK(value.start_time.to_time_point() == s2t(""2020-01-02T00:00:00.0000"")); } #endif TEST_CASE(""election-events"") { eden_tester t; t.genesis(); t.run_election(true, 10000, true); t.induct_n(100); t.run_election(true, 10000, true); t.skip_to(""2021-02-01T15:30:00.000""); t.alice.act(250); t.write_dfuse_history(""dfuse-test-election.json""); CompareFile{""test-election""}.write_events(t.chain).compare(); } ",16353,True,3069.6393349167333,median "CLASS /dmo/cx_rap_generator DEFINITION PUBLIC INHERITING FROM cx_xco_runtime_exception FINAL CREATE PUBLIC . PUBLIC SECTION. * INTERFACES if_t100_dyn_msg . * INTERFACES if_t100_message . CONSTANTS: gc_msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', BEGIN OF is_no_child_nor_grandchild, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '001', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE 'MV_ROOT_ENTITY', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF is_no_child_nor_grandchild, BEGIN OF non_alpha_numeric_characters, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '002', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF non_alpha_numeric_characters, BEGIN OF contains_spaces, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '003', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF contains_spaces, BEGIN OF is_too_long, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '004', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_MAX_LENGTH', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF is_too_long, BEGIN OF node_is_not_consistent, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '005', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF node_is_not_consistent, BEGIN OF entity_name_is_not_unique, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '005', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF entity_name_is_not_unique, BEGIN OF implementation_type_not_valid, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '006', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF implementation_type_not_valid, BEGIN OF no_namespace_set, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '007', attr1 TYPE scx_attrname VALUE '', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF no_namespace_set, BEGIN OF node_is_not_finalized, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '008', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF node_is_not_finalized, BEGIN OF is_not_a_root_node, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '009', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF is_not_a_root_node, BEGIN OF sematic_key_is_not_in_table, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '010', attr1 TYPE scx_attrname VALUE 'MV_SEMANTIC_KEY_FIELD', attr2 TYPE scx_attrname VALUE 'MV_TABLE_NAME', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF sematic_key_is_not_in_table, BEGIN OF repository_already_exists, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '011', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_VALUE_2', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF repository_already_exists, BEGIN OF cannot_check_object_type, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '012', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF cannot_check_object_type, BEGIN OF parameter_is_initial, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '013', attr1 TYPE scx_attrname VALUE 'MV_PARAMETER_NAME', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF parameter_is_initial, BEGIN OF package_does_not_exist, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '014', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF package_does_not_exist, BEGIN OF table_does_not_exist, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '015', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF table_does_not_exist, BEGIN OF root_cause_exception, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '016', attr1 TYPE scx_attrname VALUE '', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF root_cause_exception, BEGIN OF field_uuid_missing, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '017', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF field_uuid_missing, BEGIN OF field_parent_uuid_missing, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '018', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF FIELD_parent_UUID_MISSING, BEGIN OF field_root_uuid_missing, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '019', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF FIELD_root_UUID_MISSING, BEGIN OF no_table_set, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '020', attr1 TYPE scx_attrname VALUE '', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF NO_table_SET, BEGIN OF no_semantic_key_set, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '021', attr1 TYPE scx_attrname VALUE '', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF no_semantic_key_set, BEGIN OF object_name_is_not_unique, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '022', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF object_name_is_not_unique, BEGIN OF software_comp_do_not_match, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '023', attr1 TYPE scx_attrname VALUE 'MV_TABLE_NAME', attr2 TYPE scx_attrname VALUE 'MV_PACKAGE_NAME', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF software_comp_do_not_match, BEGIN OF cds_view_does_not_exist, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '024', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF cds_view_does_not_exist, BEGIN OF starts_not_with_underscore, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '025', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF starts_not_with_underscore, BEGIN OF assocation_is_not_supported, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '026', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF assocation_is_not_supported, BEGIN OF not_a_field_in_cds_view, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '027', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_ENTITY', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF not_a_field_in_cds_view, BEGIN OF usage_is_not_supported, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '028', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF usage_is_not_supported, BEGIN OF invalid_json_array_name, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '029', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF invalid_json_array_name, BEGIN OF invalid_json_object_name, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '030', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF invalid_json_object_name, BEGIN OF invalid_json_property_name, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '031', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF invalid_json_property_name, BEGIN OF field_is_not_in_datasource, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '032', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_TABLE_NAME', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF field_is_not_in_datasource, BEGIN OF field_is_not_in_cds_view, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '033', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_ENTITY', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF field_is_not_in_cds_view, BEGIN OF no_object_id_set, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '034', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF no_object_id_set, BEGIN OF invalid_data_source_type, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '035', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF invalid_data_source_type, BEGIN OF no_data_source_set, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '036', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF no_data_source_set, BEGIN OF invalid_namespace, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '037', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF invalid_namespace, BEGIN OF uuid_is_not_key_field, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '038', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_ENTITY', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF uuid_is_not_key_field, BEGIN OF uuid_has_invalid_data_type, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '039', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF uuid_has_invalid_data_type, BEGIN OF more_than_one_key_field, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '040', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE 'MV_VALUE', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF more_than_one_key_field, BEGIN OF has_no_key_field, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '041', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF has_no_KEY_FIELD, BEGIN OF invalid_binding_type, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '042', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_VALUE_2', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF invalid_binding_type, BEGIN OF invalid_transport_request, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '043', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_VALUE2', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF invalid_transport_request, BEGIN OF no_draft_table_specified, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '044', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE 'MV_ROOT_ENTITY', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF no_draft_table_specified, BEGIN OF table_is_inactive, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '045', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF table_is_inactive, BEGIN OF cannot_add_additional_fields, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '046', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF cannot_add_additional_fields, BEGIN OF not_implemented, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '047', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_VALUE_2', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF not_implemented, BEGIN OF not_draft_enabled, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '048', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF not_draft_enabled, BEGIN OF no_ui_v4_service_binding, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '049', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF no_ui_v4_service_binding, BEGIN OF admin_field_missing, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '050', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_VALUE_2', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF admin_field_missing, BEGIN OF transport_does_not_exist, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '051', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF transport_does_not_exist, BEGIN OF underscore_not_at_pos_2_3, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '052', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF underscore_not_at_pos_2_3, BEGIN OF publish_needs_active_srvd, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '053', attr1 TYPE scx_attrname VALUE '', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF publish_needs_active_srvd, BEGIN OF grand_child_not_supported, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '054', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE 'MV_VALUE', attr3 TYPE scx_attrname VALUE 'MV_VALUE_2', attr4 TYPE scx_attrname VALUE '', END OF grand_child_not_supported, BEGIN OF field_total_etag_missing, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '055', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_ENTITY', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF field_total_etag_missing, BEGIN OF field_etag_master_missing, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '056', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_ENTITY', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF field_etag_master_missing, BEGIN OF invalid_abap_type_name, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '057', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_ENTITY', attr3 TYPE scx_attrname VALUE 'MV_VALUE_2', attr4 TYPE scx_attrname VALUE '', END OF invalid_abap_type_name, BEGIN OF CLNT_is_not_key_field, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '038', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_ENTITY', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF clnt_is_not_key_field, BEGIN OF mult_edit_not_supported, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '058', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE '', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF mult_edit_not_supported, BEGIN OF delivery_class_c_required, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '060', attr1 TYPE scx_attrname VALUE 'MV_VALUE', attr2 TYPE scx_attrname VALUE 'MV_VALUE_2', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF delivery_class_c_required, BEGIN OF view_type_not_supported, msgid TYPE symsgid VALUE '/DMO/CM_RAP_GEN_MSG', msgno TYPE symsgno VALUE '061', attr1 TYPE scx_attrname VALUE 'MV_ENTITY', attr2 TYPE scx_attrname VALUE 'MV_VALUE', attr3 TYPE scx_attrname VALUE '', attr4 TYPE scx_attrname VALUE '', END OF VIEW_TYPE_NOT_SUPPORTED . DATA mv_entity TYPE sxco_ddef_alias_name. DATA mv_root_entity TYPE sxco_ddef_alias_name. DATA mv_value TYPE string. DATA mv_value_2 TYPE string. DATA mv_max_length TYPE i. DATA mv_parameter_name TYPE string. DATA mv_semantic_key_field TYPE string. DATA mv_table_name TYPE string. DATA mv_package_name TYPE string. CLASS-METHODS class_constructor . METHODS constructor IMPORTING !textid LIKE if_t100_message=>t100key OPTIONAL !previous LIKE previous OPTIONAL !mv_entity TYPE sxco_ddef_alias_name OPTIONAL !mv_root_entity TYPE sxco_ddef_alias_name OPTIONAL !mv_value TYPE string OPTIONAL !mv_value_2 TYPE string OPTIONAL !mv_max_length TYPE i OPTIONAL !mv_parameter_name TYPE string OPTIONAL !mv_semantic_key_field TYPE string OPTIONAL !mv_table_name TYPE string OPTIONAL !mv_package_name TYPE string OPTIONAL . PROTECTED SECTION. PRIVATE SECTION. ENDCLASS. CLASS /dmo/cx_rap_generator IMPLEMENTATION. METHOD class_constructor. ENDMETHOD. METHOD constructor ##ADT_SUPPRESS_GENERATION. CALL METHOD super->constructor EXPORTING previous = previous. me->mv_entity = mv_entity. me->mv_root_entity = mv_root_entity. me->mv_value = mv_value. me->mv_value_2 = mv_value_2. me->mv_max_length = mv_max_length. me->mv_parameter_name = mv_parameter_name. me->mv_semantic_key_field = mv_semantic_key_field. me->mv_table_name = mv_table_name. me->mv_package_name = mv_package_name. CLEAR me->textid. IF textid IS INITIAL. if_t100_message~t100key = if_t100_message=>default_textid. ELSE. if_t100_message~t100key = textid. ENDIF. ENDMETHOD. ENDCLASS. ",6206,False,1954.0913587037899,median "CLASS zcl_abapgit_gui_asset_manager DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. METHODS get_asset IMPORTING iv_asset_name TYPE string RETURNING VALUE(rv_data) TYPE xstring RAISING zcx_abapgit_exception. METHODS get_images RETURNING VALUE(rt_images) TYPE zif_abapgit_definitions=>tt_web_assets. CLASS-METHODS get_webfont_link RETURNING VALUE(rv_link) TYPE string. PRIVATE SECTION. METHODS get_inline_asset IMPORTING iv_asset_name TYPE string RETURNING VALUE(rv_data) TYPE xstring RAISING zcx_abapgit_exception. METHODS get_mime_asset IMPORTING iv_asset_name TYPE c RETURNING VALUE(rv_data) TYPE xstring RAISING zcx_abapgit_exception. METHODS get_inline_images RETURNING VALUE(rt_images) TYPE zif_abapgit_definitions=>tt_web_assets. ENDCLASS. CLASS ZCL_ABAPGIT_GUI_ASSET_MANAGER IMPLEMENTATION. METHOD get_asset. DATA: lv_asset_name TYPE string, lv_mime_name TYPE wwwdatatab-objid. lv_asset_name = to_upper( iv_asset_name ). CASE lv_asset_name. WHEN 'CSS_COMMON'. lv_mime_name = 'ZABAPGIT_CSS_COMMON'. WHEN 'JS_COMMON'. lv_mime_name = 'ZABAPGIT_JS_COMMON'. WHEN OTHERS. zcx_abapgit_exception=>raise( |Improper resource name: { iv_asset_name }| ). ENDCASE. "" Inline is default (for older AG snapshots to work) rv_data = get_inline_asset( lv_asset_name ). IF rv_data IS INITIAL. rv_data = get_mime_asset( lv_mime_name ). "" Get MIME object ENDIF. IF rv_data IS INITIAL. zcx_abapgit_exception=>raise( |Failed to get GUI resource: { iv_asset_name }| ). ENDIF. ENDMETHOD. "" get_asset. METHOD get_images. FIELD-SYMBOLS LIKE LINE OF rt_images. rt_images = get_inline_images( ). "" Convert to xstring LOOP AT rt_images ASSIGNING . CALL FUNCTION 'SSFC_BASE64_DECODE' EXPORTING b64data = -base64 IMPORTING bindata = -content EXCEPTIONS OTHERS = 1. ASSERT sy-subrc = 0. "" Image data error ENDLOOP. ENDMETHOD. "" get_images. METHOD get_inline_asset. * used by abapmerge DEFINE _inline. APPEND &1 TO lt_data. END-OF-DEFINITION. DATA: lt_data TYPE zif_abapgit_definitions=>ty_string_tt, lv_str TYPE string. CASE iv_asset_name. WHEN 'CSS_COMMON'. "" @@abapmerge include zabapgit_css_common.w3mi.data.css > _inline '$$'. WHEN 'JS_COMMON'. "" @@abapmerge include zabapgit_js_common.w3mi.data.js > _inline '$$'. WHEN OTHERS. zcx_abapgit_exception=>raise( |No inline resource: { iv_asset_name }| ). ENDCASE. CONCATENATE LINES OF lt_data INTO lv_str SEPARATED BY zif_abapgit_definitions=>gc_newline. CALL FUNCTION 'SCMS_STRING_TO_XSTRING' EXPORTING text = lv_str IMPORTING buffer = rv_data EXCEPTIONS OTHERS = 1. ASSERT sy-subrc = 0. ENDMETHOD. "" get_inline_asset. METHOD get_inline_images. DATA ls_image TYPE zif_abapgit_definitions=>ty_web_asset. * see https://github.com/larshp/abapGit/issues/201 for source SVG ls_image-url = 'img/logo' ##NO_TEXT. ls_image-base64 = 'iVBORw0KGgoAAAANSUhEUgAAAKMAAAAoCAYAAACSG0qbAAAABHNCSVQICAgIfAhkiAAA' && 'AAlwSFlzAAAEJQAABCUBprHeCQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9y' && 'Z5vuPBoAAA8VSURBVHic7Zx7cJzVeYef31nJAtvYko1JjM3FYHlXimwZkLWyLEMcwIGQ' && 'cEkDJWmTltLStGkoDCkzwBAuCemUlksDNCkhJTTTljJpZhIuBQxxAWPvyuYiW7UkG8Il' && 'UByIsS1sLEu75+0fu5JXu9/etAJz0TOzM/rOec85765+37m+3yczY8w0NU3qrwv9npfa' && 'Hfx02pPPd469sgk+7misYnyjpWXy5IOG7kd8ZjjNjEtr13TdOm7eTfCxwo2lUJAQASRu' && '2dnRfMn4uDbBx42yxZhPiMNMCHKCsVK2GGuqqqoQUwrZTAhygrFQshjfaGmZ/M7yxQtm' && 'xGL9/qDqzwLxQvYTgpygXEoS4/DQ7LE1O05atLBu1YZdE4KcYLwpupoOmCO+5Z2dXPfE' && 'xk07Tm2ZroGhBwX1wAygKqiOiVX2Rw9Jam/gyH0wuGGzvTEudRYSY4HFyogghxN2n7Sw' && 'IendvcCioLoOtCCXNeqohOf0oDwPq9f3Wt/77dOHlWhYzUj/BRybTnrGEnZO5wv2m0rq' && 'DezJoOiqeZbzegzpk6TVPPWJTT39y5svMogF1ZcesjlQgkwYp4F+EJQXwv4E+MiLUZJa' && 'F7AIcRq4hWZ2mMRhQD/oZcErXv7FScaja3rt/wpU9E/sFyLACQq57wB/XIl/gWIstn2T' && 'xpHVre7ZW71p8sFDeQscSEHKu3pTBadNH2Lq61VT57iwNazLgaNSqYaUaWXLDZCJIbBo' && 'g3tK2A2xHns0oMrm3CRrqdTPnAVMiUIEmLlz2XGLMxNmH7YrifFcoUIHalHj8f8p6UfA' && 'O+932weStno1zghps6Q7GBFiUYRxopkeaZ2vIwLyfxtQ4vV8lbWHNScacf+T/vwqn90o' && 'MZYhRADJ+bv725vmj6Q8tHWffPKUD6IgO/tsfawneRHYd97Pdg8kSyJaZiGtBY4pYPYO' && 'kH84C0Cyv8tKSiK7OZ99EpYAJ2V8AhkRY5lCHGaxhaq+BLCzY/EXd5y0aOG0td1vf1AF' && 'CWCw7/1u80DQEtahQvcB03MyjQfM7Hwnmxfv9dPivX5SssqOwuzPSqk71mN3ymw5ZtdK' && 'dmVIdly8xx7JZ29yy0qptwrGLMRRCA6T1w93nLTo5Lq13Zv625tOMRd6DLF4v0lWmQO8' && 'qPko45y7TWaHZyUnwa6M99mN2fYbuu1V4K5oxF1B4Z4UgFifrQHWFLNbvkh1QheV5DNN' && 'TZMqFWIGs5zX48M95PTqGa3TZ4erzbvj8/WUErf0L2++uNyGJLn2Js1oDeuYlkbNbmlR' && 'deXup2hq0qS2es2VlHMDFaOlRdXL5uuwlnodG23QTEljCkbJV3d7WHOK+dXWqHqZnZeb' && 'Y1fGe3OFOArRU5GTGbSHNWdwUL8Epo1qIQ9V/bXu3HES4jCznNfjb7e1zZ8Ri/UD1MLz' && 'u05s/huMx4IKGNy4+8Tj/2Pqk8++Vaji86TQqxEuNNM5rWGtSCaokSDkgd0QjbidoPvN' && '+5s7t9jz5TgdbdBMvLsG2cop6FgLUdUaZk804jYKuyrWa6vzlT2+XrOqQnxd6KwQOj5R' && 'hULpL9Yaxkcj7g3QT6zK397ZbdtGtbtAZ+B0U3adkt0c67E7OyI6fFDuSpktC6HGpJjU' && 'GmZ3NOI2mdnVnX32eHZZ7903hGXfBG8mp3J7sd/B0DPCTgUmBf9O7lmMybk56or3Jn8f' && 'oLVB7Q5dZ9Iy4OBsw2jYbUUk96fwQrzHf955iBZzsDA+aL9k1owZ20fNzaY/tfFXwK48' && 'ldQkSZ5YqJXmZk15JaJfmOmfgdOAmgCzWrCvyum5aIO+Uor3AIbOx7QV2TeBMPu3vKYA' && 'Sw091hbWt4PKRhu0oDqkmND1wAnk3vkOmAN2lRLa2hrWMVm5Tek2R3286YzWiK4eQltk' && '9g1gMfsFMhVYKunR1obQddk+SXZqwLe8acMGe7fYb9HZk7wm3utrBmpsqiXsyClHMHK6' && '0hLWoRjHBfmLbP9K3bPYjFPIFWLaQeZnlZ8H4JyFflrMwcK4wG63v3/ycZnXOzqalxE0' && 'mU7x9rvvVv93oVZqBtzNGGeU7Jbp9pZGzS7ReiVQVyDfmXRda4PaA9p5mBLmWGmmSron' && 'M0FytUGGgjPTAi8UIeVk9u1og5YOJ0QbNBOjIac+Y22JPgLQ1WV7Ol+w36xebYnhtGpj' && 'FjBYTj3l4KY9/dx6My4d74pN/Ki/Y9HpSG5HR/Nyh/1DHtO9OM6dvWFDwbtWslOykt6U' && 's5VWZbOFnQtsyMqvc56Ty3T7NeBhLGAfDZDpe5nX6V5uXpbZ43K2NGQ2V9glwLas/I62' && 'hfrE8EWsJ3mFsGYs+OQqze+A1cBLgbmma4f/9AmOJGBe5vKVLYN1W6wnOWSHmdkVhexM' && 'PG6yC0x2AbmjoQ3njdh4uwrSw1Htmq5bd3Y0I3FLpQ5n0GTSQ7s6Fva70RPYTPbi+Pz0' && 'J7ryboRC+m5PnRfsJjVEAfp5bLNflTb52dKIBj36RWY5ZyX2WCLukvbX67ZYHFLHZtGw' && '+1fD/jDL8qQljWpav9m6Uw3wKYzXgUNJTxsk+0Fssw0L6x+j4dCx6eF/BEtwDBkbx7Fe' && '29gWCa0yrC2rvXXO26WZfrWG3V2kji8zWbm0QUev67GX5ZgZ8A0H121hXIIZNrxou9oW' && '6m4b4m/z2aTP+fsAohF3PaNHROvssZ8ElRs5DnyPBAkovxDFF4oJESDeY9tJD4Ur5umg' && 'PSFm1Uy23Zk2SaM7e43p5Y4uxUMzu2f4H56+tuZmff2gfTqHrGEy5DkW6Abo7LH7gfsB' && '2uo1LQGzBmoYFSwg57vNcjqqo4F1JXh2S7Zfx83TZZNqdD6MXkQkU369jONgcmfxe83M' && 'B7XQEdEhg1B0HzDk2ZHpy3vBqLPpMQhyi/f2AIA3WyPZG6KkeVpKiE925awEi7H6JRsA' && 'cqJDfIi9oayfW8ZB5dY/TFeX7YlGQg+RmgJkcnSQfWyr9QP92enmGcgeNCvx67mXbGdb' && 'xD1hjI5AklJ+ydgTUGz6iiZNXd09+gYGGIRlQgXn6wDesZYSRFsJOYES5QjSw7fqnu7q' && 'Bqh7uqu7f3nzdw3uKFJszEIcpqVRs12SRuAYiTrJ1YXMzSGgS6iQnHmWyQWe70pySz/F' && 'MZagMWnMlaiTuTqTTih7s7IIHm1T1ncVI37l3BAAA4McAYF7iAvG17uxExi1U6Igd9XN' && 'Dj+UmZA8qPrf3MDQbeSPIN8Ldub0JzeWLcT2I3Swn8JFhr4VQnMze5uKnv0ugOHfUXa3' && 'ZhySedkR0eGDuMtbw/rTZCI1pA9PF0yWf4e3MnJ7YKXm0pOr6H03QRIIZeYnUj1njhid' && '8aaRscKX/VGWSRLsCjnK2rcdC3njGUsQ5PSdv92yqJaMk5WBoRMpJsSnNgZufBdCkmsN' && '60FgRbllK8PNzOlttT/qpz2sOUnpeWGHvq9ewcyc28/7XQCru213NOL+l6wgZ0kXAjnD' && 'cazP7gXuTdu41rCyxbgr3mt/P16+F6LgUVXtmq5bC237yNsNu5YtPBZgx4kLFznZ1XlM' && 'BzB/1liECBAN801yhfiq0HflbKXz1ojZ4qCylSBsbm6q/93wX0n0Q1Ir6UzWYXaZyZaF' && 'qqxeZn813n4ZlhPWJWXMo00P5OTDF5c0qmm8fRlPip6bFhHk6Ti3ddfy5i3OXBemJQE2' && 'A5g/c/qaTasC8krC0KdzE+3qWG/y6thmW7Vui/UkQ7w51vqDaGnRZFInPdlshNQ2C8oJ' && 'h0oqaefF++zmzh5bu7bbXrBxjp88bp5qgZzNdyfWD/9t+B+TO4GW8/p+R0SHcGBxLWEF' && 'jiQlHeIXEaRIPZAVRMVCTDcQCUh8LfOyaqjgCcr+YpY7NRFa2VY/egsqtNtdw8ie5gjJ' && 'oUTqicjofOYA2f/YgcR03s5MMBF4wlIa7rMr5mnUyru6xl0LZAeFvDG3l83DF5199muk' && 'oJO1FUMoviSi8Nh9Kg+Ru7qvUvCqPO+cMZsxbPsM4HXW9KcrEyKApTa7s9BVSyLaF3Ik' && 'SbLSQros18RyInkkV2u5q+6zLaS+aCT0oJl/QVI78IWcsvDos1vtLYCE551QKNuCKW63' && '+157g36cMOYI9yWhC3K+j4KDEHKxC9+t0altDaFHwL/kvVZIBJw761/uM5/MTJlU7S/Z' && 'N6hTBNlhZA0OPReNuGdM6nL4jR4G5ZnRusAtKmVHwg1Slcxe11nODZJKh1fJ6kwM3dQa' && 'VgOw3omjkGuL9/o/L/vFTzs7mi8pQZBpIT4f9PxE2bRFQncY9pdjKDoExDH7ebzPbgFo' && 'bQjdng48KBfvzZau77ORN61FI66PsW2N7ARiZnZTZ589BtAWCV1v5J1zF+JNVdui2CbL' && 'OcJsq1ejD2lVgCDL4e14r58J0N6k+cmEu0HYIssdrbxgnaGeeG9yJEg32hC6GbOix81y' && 'trTsWLtiixpgQNLZ4yVEgCT++xSP0H7C0N1ZadVAh6SR3kRm2WfJO0H/XqTuQcn+IlOI' && 'AFjRVaZhus3g2az0WuA0wcIi5QP3DDNIIPtakBABYltts7AO4OEi9eTFYGCksSRzwM4L' && 'ECKAM1gG9tVR5UP+RkqZN5s7a0yBnwUEOSDp7GlPPp83BH0srO+1PmQrDIIen9wOdnln' && 'n31G5n9ZtDLL6ck2x3uTf6DUee8rASX6vNnyWI/dmZ0R77O7LNXLBkWy9CE7Pd6XvNih' && 'QkEQeZHZl9PBFtsDstebtyWFwv0B4r32UrzXn+6xDtBdwIslNL0N+JnMvravxiraFO/s' && 'tm0y+xzQlcfkddCNCe/vGfP7GQH6lzdfbHAjqSCBHZK+PN5CzESSlixgnhMLzXAeXp+3' && 'hWfuM0sWL10abQv1CdtHixzvmtiYPhcvSFOTJk1NEPEQkWdPUry4oc96y2o3YJiWs5Wx' && 'zbYq83THHHu9Y1N2kG45tDRqdsgzxxuznKPOGbsTsN2M7d6zfXhePJ5Ici1h6mUcAcw0' && '8Zo5fp35NoqKxAjwTrRhZmLSpPY9ySmPzV27dm+lTn9cKSTGA+XT+03Jq+l8HBLv2Q7c' && 'X9K+ygQTFGDcHhaaoGJyouDNV7JH+eGj4mF6gspoC+tzJt1ObsT4MDsF2zxs886+Ml5v' && '/PogUvEwPUGFiE+SX4gAtQa1gkhV7onQR4oJMR5oxC6stDeghd7Dh6E+CPw/HL4vVO2f' && 'cpUAAAAASUVORK5CYII='. APPEND ls_image TO rt_images. ENDMETHOD. "" get_inline_images. METHOD get_mime_asset. DATA: ls_key TYPE wwwdatatab, lv_size_c TYPE wwwparams-value, lv_size TYPE i, lt_w3mime TYPE STANDARD TABLE OF w3mime. ls_key-relid = 'MI'. ls_key-objid = iv_asset_name. "" Get exact file size CALL FUNCTION 'WWWPARAMS_READ' EXPORTING relid = ls_key-relid objid = ls_key-objid name = 'filesize' IMPORTING value = lv_size_c EXCEPTIONS entry_not_exists = 1. IF sy-subrc IS NOT INITIAL. RETURN. ENDIF. lv_size = lv_size_c. "" Get binary data CALL FUNCTION 'WWWDATA_IMPORT' EXPORTING key = ls_key TABLES mime = lt_w3mime EXCEPTIONS wrong_object_type = 1 import_error = 2. IF sy-subrc IS NOT INITIAL. RETURN. ENDIF. CALL FUNCTION 'SCMS_BINARY_TO_XSTRING' EXPORTING input_length = lv_size IMPORTING buffer = rv_data TABLES binary_tab = lt_w3mime EXCEPTIONS failed = 1 ##FM_SUBRC_OK. ENDMETHOD. "" get_mime_asset. METHOD get_webfont_link. rv_link = ''. ""#EC NOTEXT ENDMETHOD. "" get_webfont_link ENDCLASS. ",5570,False,1843.8729390350043,median "/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ 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. */ #include ""btCollisionWorld.h"" #include ""btCollisionDispatcher.h"" #include ""BulletCollision/CollisionDispatch/btCollisionObject.h"" #include ""BulletCollision/CollisionShapes/btCollisionShape.h"" #include ""BulletCollision/CollisionShapes/btConvexShape.h"" #include ""BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"" #include ""BulletCollision/CollisionShapes/btSphereShape.h"" //for raycasting #include ""BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h"" //for raycasting #include ""BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h"" //for raycasting #include ""BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"" //for raycasting #include ""BulletCollision/NarrowPhaseCollision/btRaycastCallback.h"" #include ""BulletCollision/CollisionShapes/btCompoundShape.h"" #include ""BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"" #include ""BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"" #include ""BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"" #include ""BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"" #include ""BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"" #include ""BulletCollision/BroadphaseCollision/btDbvt.h"" #include ""LinearMath/btAabbUtil2.h"" #include ""LinearMath/btQuickprof.h"" #include ""LinearMath/btSerializer.h"" #include ""BulletCollision/CollisionShapes/btConvexPolyhedron.h"" #include ""BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"" //#define DISABLE_DBVT_COMPOUNDSHAPE_RAYCAST_ACCELERATION //#define USE_BRUTEFORCE_RAYBROADPHASE 1 //RECALCULATE_AABB is slower, but benefit is that you don't need to call 'stepSimulation' or 'updateAabbs' before using a rayTest //#define RECALCULATE_AABB_RAYCAST 1 //When the user doesn't provide dispatcher or broadphase, create basic versions (and delete them in destructor) #include ""BulletCollision/CollisionDispatch/btCollisionDispatcher.h"" #include ""BulletCollision/BroadphaseCollision/btSimpleBroadphase.h"" #include ""BulletCollision/CollisionDispatch/btCollisionConfiguration.h"" ///for debug drawing //for debug rendering #include ""BulletCollision/CollisionShapes/btBoxShape.h"" #include ""BulletCollision/CollisionShapes/btCapsuleShape.h"" #include ""BulletCollision/CollisionShapes/btCompoundShape.h"" #include ""BulletCollision/CollisionShapes/btConeShape.h"" #include ""BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h"" #include ""BulletCollision/CollisionShapes/btCylinderShape.h"" #include ""BulletCollision/CollisionShapes/btMultiSphereShape.h"" #include ""BulletCollision/CollisionShapes/btPolyhedralConvexShape.h"" #include ""BulletCollision/CollisionShapes/btSphereShape.h"" #include ""BulletCollision/CollisionShapes/btTriangleCallback.h"" #include ""BulletCollision/CollisionShapes/btTriangleMeshShape.h"" #include ""BulletCollision/CollisionShapes/btStaticPlaneShape.h"" btCollisionWorld::btCollisionWorld(btDispatcher* dispatcher, btBroadphaseInterface* pairCache, btCollisionConfiguration* collisionConfiguration) : m_dispatcher1(dispatcher), m_broadphasePairCache(pairCache), m_debugDrawer(0), m_forceUpdateAllAabbs(true) { } btCollisionWorld::~btCollisionWorld() { //clean up remaining objects int i; for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* collisionObject = m_collisionObjects[i]; btBroadphaseProxy* bp = collisionObject->getBroadphaseHandle(); if (bp) { // // only clear the cached algorithms // getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bp, m_dispatcher1); getBroadphase()->destroyProxy(bp, m_dispatcher1); collisionObject->setBroadphaseHandle(0); } } } void btCollisionWorld::refreshBroadphaseProxy(btCollisionObject* collisionObject) { if (collisionObject->getBroadphaseHandle()) { int collisionFilterGroup = collisionObject->getBroadphaseHandle()->m_collisionFilterGroup; int collisionFilterMask = collisionObject->getBroadphaseHandle()->m_collisionFilterMask; getBroadphase()->destroyProxy(collisionObject->getBroadphaseHandle(), getDispatcher()); //calculate new AABB btTransform trans = collisionObject->getWorldTransform(); btVector3 minAabb; btVector3 maxAabb; collisionObject->getCollisionShape()->getAabb(trans, minAabb, maxAabb); int type = collisionObject->getCollisionShape()->getShapeType(); collisionObject->setBroadphaseHandle(getBroadphase()->createProxy( minAabb, maxAabb, type, collisionObject, collisionFilterGroup, collisionFilterMask, m_dispatcher1)); } } void btCollisionWorld::addCollisionObject(btCollisionObject* collisionObject, int collisionFilterGroup, int collisionFilterMask) { btAssert(collisionObject); //check that the object isn't already added btAssert(m_collisionObjects.findLinearSearch(collisionObject) == m_collisionObjects.size()); btAssert(collisionObject->getWorldArrayIndex() == -1); // do not add the same object to more than one collision world collisionObject->setWorldArrayIndex(m_collisionObjects.size()); m_collisionObjects.push_back(collisionObject); //calculate new AABB btTransform trans = collisionObject->getWorldTransform(); btVector3 minAabb; btVector3 maxAabb; collisionObject->getCollisionShape()->getAabb(trans, minAabb, maxAabb); int type = collisionObject->getCollisionShape()->getShapeType(); collisionObject->setBroadphaseHandle(getBroadphase()->createProxy( minAabb, maxAabb, type, collisionObject, collisionFilterGroup, collisionFilterMask, m_dispatcher1)); } void btCollisionWorld::updateSingleAabb(btCollisionObject* colObj) { btVector3 minAabb, maxAabb; colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb, maxAabb); //need to increase the aabb for contact thresholds btVector3 contactThreshold(gContactBreakingThreshold, gContactBreakingThreshold, gContactBreakingThreshold); minAabb -= contactThreshold; maxAabb += contactThreshold; if (getDispatchInfo().m_useContinuous && colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY && !colObj->isStaticOrKinematicObject()) { btVector3 minAabb2, maxAabb2; colObj->getCollisionShape()->getAabb(colObj->getInterpolationWorldTransform(), minAabb2, maxAabb2); minAabb2 -= contactThreshold; maxAabb2 += contactThreshold; minAabb.setMin(minAabb2); maxAabb.setMax(maxAabb2); } btBroadphaseInterface* bp = (btBroadphaseInterface*)m_broadphasePairCache; //moving objects should be moderately sized, probably something wrong if not if (colObj->isStaticObject() || ((maxAabb - minAabb).length2() < btScalar(1e12))) { bp->setAabb(colObj->getBroadphaseHandle(), minAabb, maxAabb, m_dispatcher1); } else { //something went wrong, investigate //this assert is unwanted in 3D modelers (danger of loosing work) colObj->setActivationState(DISABLE_SIMULATION); static bool reportMe = true; if (reportMe && m_debugDrawer) { reportMe = false; m_debugDrawer->reportErrorWarning(""Overflow in AABB, object removed from simulation""); m_debugDrawer->reportErrorWarning(""If you can reproduce this, please email bugs@continuousphysics.com\\n""); m_debugDrawer->reportErrorWarning(""Please include above information, your Platform, version of OS.\\n""); m_debugDrawer->reportErrorWarning(""Thanks.\\n""); } } } void btCollisionWorld::updateAabbs() { BT_PROFILE(""updateAabbs""); btTransform predictedTrans; for (int i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* colObj = m_collisionObjects[i]; btAssert(colObj->getWorldArrayIndex() == i); //only update aabb of active objects if (m_forceUpdateAllAabbs || colObj->isActive()) { updateSingleAabb(colObj); } } } void btCollisionWorld::computeOverlappingPairs() { BT_PROFILE(""calculateOverlappingPairs""); m_broadphasePairCache->calculateOverlappingPairs(m_dispatcher1); } void btCollisionWorld::performDiscreteCollisionDetection() { BT_PROFILE(""performDiscreteCollisionDetection""); btDispatcherInfo& dispatchInfo = getDispatchInfo(); updateAabbs(); computeOverlappingPairs(); btDispatcher* dispatcher = getDispatcher(); { BT_PROFILE(""dispatchAllCollisionPairs""); if (dispatcher) dispatcher->dispatchAllCollisionPairs(m_broadphasePairCache->getOverlappingPairCache(), dispatchInfo, m_dispatcher1); } } void btCollisionWorld::removeCollisionObject(btCollisionObject* collisionObject) { //bool removeFromBroadphase = false; { btBroadphaseProxy* bp = collisionObject->getBroadphaseHandle(); if (bp) { // // only clear the cached algorithms // getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bp, m_dispatcher1); getBroadphase()->destroyProxy(bp, m_dispatcher1); collisionObject->setBroadphaseHandle(0); } } int iObj = collisionObject->getWorldArrayIndex(); // btAssert(iObj >= 0 && iObj < m_collisionObjects.size()); // trying to remove an object that was never added or already removed previously? if (iObj >= 0 && iObj < m_collisionObjects.size()) { btAssert(collisionObject == m_collisionObjects[iObj]); m_collisionObjects.swap(iObj, m_collisionObjects.size() - 1); m_collisionObjects.pop_back(); if (iObj < m_collisionObjects.size()) { m_collisionObjects[iObj]->setWorldArrayIndex(iObj); } } else { // slow linear search //swapremove m_collisionObjects.remove(collisionObject); } collisionObject->setWorldArrayIndex(-1); } void btCollisionWorld::rayTestSingle(const btTransform& rayFromTrans, const btTransform& rayToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, RayResultCallback& resultCallback) { btCollisionObjectWrapper colObWrap(0, collisionShape, collisionObject, colObjWorldTransform, -1, -1); btCollisionWorld::rayTestSingleInternal(rayFromTrans, rayToTrans, &colObWrap, resultCallback); } void btCollisionWorld::rayTestSingleInternal(const btTransform& rayFromTrans, const btTransform& rayToTrans, const btCollisionObjectWrapper* collisionObjectWrap, RayResultCallback& resultCallback) { btSphereShape pointShape(btScalar(0.0)); pointShape.setMargin(0.f); const btConvexShape* castShape = &pointShape; const btCollisionShape* collisionShape = collisionObjectWrap->getCollisionShape(); const btTransform& colObjWorldTransform = collisionObjectWrap->getWorldTransform(); if (collisionShape->isConvex()) { // BT_PROFILE(""rayTestConvex""); btConvexCast::CastResult castResult; castResult.m_fraction = resultCallback.m_closestHitFraction; btConvexShape* convexShape = (btConvexShape*)collisionShape; btVoronoiSimplexSolver simplexSolver; btSubsimplexConvexCast subSimplexConvexCaster(castShape, convexShape, &simplexSolver); btGjkConvexCast gjkConvexCaster(castShape, convexShape, &simplexSolver); //btContinuousConvexCollision convexCaster(castShape,convexShape,&simplexSolver,0); btConvexCast* convexCasterPtr = 0; //use kF_UseSubSimplexConvexCastRaytest by default if (resultCallback.m_flags & btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest) convexCasterPtr = &gjkConvexCaster; else convexCasterPtr = &subSimplexConvexCaster; btConvexCast& convexCaster = *convexCasterPtr; if (convexCaster.calcTimeOfImpact(rayFromTrans, rayToTrans, colObjWorldTransform, colObjWorldTransform, castResult)) { //add hit if (castResult.m_normal.length2() > btScalar(0.0001)) { if (castResult.m_fraction < resultCallback.m_closestHitFraction) { //todo: figure out what this is about. When is rayFromTest.getBasis() not identity? #ifdef USE_SUBSIMPLEX_CONVEX_CAST //rotate normal into worldspace castResult.m_normal = rayFromTrans.getBasis() * castResult.m_normal; #endif //USE_SUBSIMPLEX_CONVEX_CAST castResult.m_normal.normalize(); btCollisionWorld::LocalRayResult localRayResult( collisionObjectWrap->getCollisionObject(), 0, castResult.m_normal, castResult.m_fraction); bool normalInWorldSpace = true; resultCallback.addSingleResult(localRayResult, normalInWorldSpace); } } } } else { if (collisionShape->isConcave()) { //ConvexCast::CastResult struct BridgeTriangleRaycastCallback : public btTriangleRaycastCallback { btCollisionWorld::RayResultCallback* m_resultCallback; const btCollisionObject* m_collisionObject; const btConcaveShape* m_triangleMesh; btTransform m_colObjWorldTransform; BridgeTriangleRaycastCallback(const btVector3& from, const btVector3& to, btCollisionWorld::RayResultCallback* resultCallback, const btCollisionObject* collisionObject, const btConcaveShape* triangleMesh, const btTransform& colObjWorldTransform) : //@BP Mod btTriangleRaycastCallback(from, to, resultCallback->m_flags), m_resultCallback(resultCallback), m_collisionObject(collisionObject), m_triangleMesh(triangleMesh), m_colObjWorldTransform(colObjWorldTransform) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = partId; shapeInfo.m_triangleIndex = triangleIndex; btVector3 hitNormalWorld = m_colObjWorldTransform.getBasis() * hitNormalLocal; btCollisionWorld::LocalRayResult rayResult(m_collisionObject, &shapeInfo, hitNormalWorld, hitFraction); bool normalInWorldSpace = true; return m_resultCallback->addSingleResult(rayResult, normalInWorldSpace); } }; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); // BT_PROFILE(""rayTestConcave""); if (collisionShape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE) { ///optimized version for btBvhTriangleMeshShape btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)collisionShape; BridgeTriangleRaycastCallback rcb(rayFromLocal, rayToLocal, &resultCallback, collisionObjectWrap->getCollisionObject(), triangleMesh, colObjWorldTransform); rcb.m_hitFraction = resultCallback.m_closestHitFraction; triangleMesh->performRaycast(&rcb, rayFromLocal, rayToLocal); } else if (collisionShape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) { ///optimized version for btScaledBvhTriangleMeshShape btScaledBvhTriangleMeshShape* scaledTriangleMesh = (btScaledBvhTriangleMeshShape*)collisionShape; btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)scaledTriangleMesh->getChildShape(); //scale the ray positions btVector3 scale = scaledTriangleMesh->getLocalScaling(); btVector3 rayFromLocalScaled = rayFromLocal / scale; btVector3 rayToLocalScaled = rayToLocal / scale; //perform raycast in the underlying btBvhTriangleMeshShape BridgeTriangleRaycastCallback rcb(rayFromLocalScaled, rayToLocalScaled, &resultCallback, collisionObjectWrap->getCollisionObject(), triangleMesh, colObjWorldTransform); rcb.m_hitFraction = resultCallback.m_closestHitFraction; triangleMesh->performRaycast(&rcb, rayFromLocalScaled, rayToLocalScaled); } else if (((resultCallback.m_flags&btTriangleRaycastCallback::kF_DisableHeightfieldAccelerator)==0) && collisionShape->getShapeType() == TERRAIN_SHAPE_PROXYTYPE ) { ///optimized version for btHeightfieldTerrainShape btHeightfieldTerrainShape* heightField = (btHeightfieldTerrainShape*)collisionShape; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); BridgeTriangleRaycastCallback rcb(rayFromLocal, rayToLocal, &resultCallback, collisionObjectWrap->getCollisionObject(), heightField, colObjWorldTransform); rcb.m_hitFraction = resultCallback.m_closestHitFraction; heightField->performRaycast(&rcb, rayFromLocal, rayToLocal); } else { //generic (slower) case btConcaveShape* concaveShape = (btConcaveShape*)collisionShape; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); //ConvexCast::CastResult struct BridgeTriangleRaycastCallback : public btTriangleRaycastCallback { btCollisionWorld::RayResultCallback* m_resultCallback; const btCollisionObject* m_collisionObject; btConcaveShape* m_triangleMesh; btTransform m_colObjWorldTransform; BridgeTriangleRaycastCallback(const btVector3& from, const btVector3& to, btCollisionWorld::RayResultCallback* resultCallback, const btCollisionObject* collisionObject, btConcaveShape* triangleMesh, const btTransform& colObjWorldTransform) : //@BP Mod btTriangleRaycastCallback(from, to, resultCallback->m_flags), m_resultCallback(resultCallback), m_collisionObject(collisionObject), m_triangleMesh(triangleMesh), m_colObjWorldTransform(colObjWorldTransform) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = partId; shapeInfo.m_triangleIndex = triangleIndex; btVector3 hitNormalWorld = m_colObjWorldTransform.getBasis() * hitNormalLocal; btCollisionWorld::LocalRayResult rayResult(m_collisionObject, &shapeInfo, hitNormalWorld, hitFraction); bool normalInWorldSpace = true; return m_resultCallback->addSingleResult(rayResult, normalInWorldSpace); } }; BridgeTriangleRaycastCallback rcb(rayFromLocal, rayToLocal, &resultCallback, collisionObjectWrap->getCollisionObject(), concaveShape, colObjWorldTransform); rcb.m_hitFraction = resultCallback.m_closestHitFraction; btVector3 rayAabbMinLocal = rayFromLocal; rayAabbMinLocal.setMin(rayToLocal); btVector3 rayAabbMaxLocal = rayFromLocal; rayAabbMaxLocal.setMax(rayToLocal); concaveShape->processAllTriangles(&rcb, rayAabbMinLocal, rayAabbMaxLocal); } } else { // BT_PROFILE(""rayTestCompound""); if (collisionShape->isCompound()) { struct LocalInfoAdder2 : public RayResultCallback { RayResultCallback* m_userCallback; int m_i; LocalInfoAdder2(int i, RayResultCallback* user) : m_userCallback(user), m_i(i) { m_closestHitFraction = m_userCallback->m_closestHitFraction; m_flags = m_userCallback->m_flags; } virtual bool needsCollision(btBroadphaseProxy* p) const { return m_userCallback->needsCollision(p); } virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& r, bool b) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = -1; shapeInfo.m_triangleIndex = m_i; if (r.m_localShapeInfo == NULL) r.m_localShapeInfo = &shapeInfo; const btScalar result = m_userCallback->addSingleResult(r, b); m_closestHitFraction = m_userCallback->m_closestHitFraction; return result; } }; struct RayTester : btDbvt::ICollide { const btCollisionObject* m_collisionObject; const btCompoundShape* m_compoundShape; const btTransform& m_colObjWorldTransform; const btTransform& m_rayFromTrans; const btTransform& m_rayToTrans; RayResultCallback& m_resultCallback; RayTester(const btCollisionObject* collisionObject, const btCompoundShape* compoundShape, const btTransform& colObjWorldTransform, const btTransform& rayFromTrans, const btTransform& rayToTrans, RayResultCallback& resultCallback) : m_collisionObject(collisionObject), m_compoundShape(compoundShape), m_colObjWorldTransform(colObjWorldTransform), m_rayFromTrans(rayFromTrans), m_rayToTrans(rayToTrans), m_resultCallback(resultCallback) { } void ProcessLeaf(int i) { const btCollisionShape* childCollisionShape = m_compoundShape->getChildShape(i); const btTransform& childTrans = m_compoundShape->getChildTransform(i); btTransform childWorldTrans = m_colObjWorldTransform * childTrans; btCollisionObjectWrapper tmpOb(0, childCollisionShape, m_collisionObject, childWorldTrans, -1, i); // replace collision shape so that callback can determine the triangle LocalInfoAdder2 my_cb(i, &m_resultCallback); rayTestSingleInternal( m_rayFromTrans, m_rayToTrans, &tmpOb, my_cb); } void Process(const btDbvtNode* leaf) { ProcessLeaf(leaf->dataAsInt); } }; const btCompoundShape* compoundShape = static_cast(collisionShape); const btDbvt* dbvt = compoundShape->getDynamicAabbTree(); RayTester rayCB( collisionObjectWrap->getCollisionObject(), compoundShape, colObjWorldTransform, rayFromTrans, rayToTrans, resultCallback); #ifndef DISABLE_DBVT_COMPOUNDSHAPE_RAYCAST_ACCELERATION if (dbvt) { btVector3 localRayFrom = colObjWorldTransform.inverseTimes(rayFromTrans).getOrigin(); btVector3 localRayTo = colObjWorldTransform.inverseTimes(rayToTrans).getOrigin(); btDbvt::rayTest(dbvt->m_root, localRayFrom, localRayTo, rayCB); } else #endif //DISABLE_DBVT_COMPOUNDSHAPE_RAYCAST_ACCELERATION { for (int i = 0, n = compoundShape->getNumChildShapes(); i < n; ++i) { rayCB.ProcessLeaf(i); } } } } } } void btCollisionWorld::objectQuerySingle(const btConvexShape* castShape, const btTransform& convexFromTrans, const btTransform& convexToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, ConvexResultCallback& resultCallback, btScalar allowedPenetration) { btCollisionObjectWrapper tmpOb(0, collisionShape, collisionObject, colObjWorldTransform, -1, -1); btCollisionWorld::objectQuerySingleInternal(castShape, convexFromTrans, convexToTrans, &tmpOb, resultCallback, allowedPenetration); } void btCollisionWorld::objectQuerySingleInternal(const btConvexShape* castShape, const btTransform& convexFromTrans, const btTransform& convexToTrans, const btCollisionObjectWrapper* colObjWrap, ConvexResultCallback& resultCallback, btScalar allowedPenetration) { const btCollisionShape* collisionShape = colObjWrap->getCollisionShape(); const btTransform& colObjWorldTransform = colObjWrap->getWorldTransform(); if (collisionShape->isConvex()) { //BT_PROFILE(""convexSweepConvex""); btConvexCast::CastResult castResult; castResult.m_allowedPenetration = allowedPenetration; castResult.m_fraction = resultCallback.m_closestHitFraction; //btScalar(1.);//?? btConvexShape* convexShape = (btConvexShape*)collisionShape; btVoronoiSimplexSolver simplexSolver; btGjkEpaPenetrationDepthSolver gjkEpaPenetrationSolver; btContinuousConvexCollision convexCaster1(castShape, convexShape, &simplexSolver, &gjkEpaPenetrationSolver); //btGjkConvexCast convexCaster2(castShape,convexShape,&simplexSolver); //btSubsimplexConvexCast convexCaster3(castShape,convexShape,&simplexSolver); btConvexCast* castPtr = &convexCaster1; if (castPtr->calcTimeOfImpact(convexFromTrans, convexToTrans, colObjWorldTransform, colObjWorldTransform, castResult)) { //add hit if (castResult.m_normal.length2() > btScalar(0.0001)) { if (castResult.m_fraction < resultCallback.m_closestHitFraction) { castResult.m_normal.normalize(); btCollisionWorld::LocalConvexResult localConvexResult( colObjWrap->getCollisionObject(), 0, castResult.m_normal, castResult.m_hitPoint, castResult.m_fraction); bool normalInWorldSpace = true; resultCallback.addSingleResult(localConvexResult, normalInWorldSpace); } } } } else { if (collisionShape->isConcave()) { if (collisionShape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE) { //BT_PROFILE(""convexSweepbtBvhTriangleMesh""); btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)collisionShape; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 convexFromLocal = worldTocollisionObject * convexFromTrans.getOrigin(); btVector3 convexToLocal = worldTocollisionObject * convexToTrans.getOrigin(); // rotation of box in local mesh space = MeshRotation^-1 * ConvexToRotation btTransform rotationXform = btTransform(worldTocollisionObject.getBasis() * convexToTrans.getBasis()); //ConvexCast::CastResult struct BridgeTriangleConvexcastCallback : public btTriangleConvexcastCallback { btCollisionWorld::ConvexResultCallback* m_resultCallback; const btCollisionObject* m_collisionObject; btTriangleMeshShape* m_triangleMesh; BridgeTriangleConvexcastCallback(const btConvexShape* castShape, const btTransform& from, const btTransform& to, btCollisionWorld::ConvexResultCallback* resultCallback, const btCollisionObject* collisionObject, btTriangleMeshShape* triangleMesh, const btTransform& triangleToWorld) : btTriangleConvexcastCallback(castShape, from, to, triangleToWorld, triangleMesh->getMargin()), m_resultCallback(resultCallback), m_collisionObject(collisionObject), m_triangleMesh(triangleMesh) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = partId; shapeInfo.m_triangleIndex = triangleIndex; if (hitFraction <= m_resultCallback->m_closestHitFraction) { btCollisionWorld::LocalConvexResult convexResult(m_collisionObject, &shapeInfo, hitNormalLocal, hitPointLocal, hitFraction); bool normalInWorldSpace = true; return m_resultCallback->addSingleResult(convexResult, normalInWorldSpace); } return hitFraction; } }; BridgeTriangleConvexcastCallback tccb(castShape, convexFromTrans, convexToTrans, &resultCallback, colObjWrap->getCollisionObject(), triangleMesh, colObjWorldTransform); tccb.m_hitFraction = resultCallback.m_closestHitFraction; tccb.m_allowedPenetration = allowedPenetration; btVector3 boxMinLocal, boxMaxLocal; castShape->getAabb(rotationXform, boxMinLocal, boxMaxLocal); triangleMesh->performConvexcast(&tccb, convexFromLocal, convexToLocal, boxMinLocal, boxMaxLocal); } else { if (collisionShape->getShapeType() == STATIC_PLANE_PROXYTYPE) { btConvexCast::CastResult castResult; castResult.m_allowedPenetration = allowedPenetration; castResult.m_fraction = resultCallback.m_closestHitFraction; btStaticPlaneShape* planeShape = (btStaticPlaneShape*)collisionShape; btContinuousConvexCollision convexCaster1(castShape, planeShape); btConvexCast* castPtr = &convexCaster1; if (castPtr->calcTimeOfImpact(convexFromTrans, convexToTrans, colObjWorldTransform, colObjWorldTransform, castResult)) { //add hit if (castResult.m_normal.length2() > btScalar(0.0001)) { if (castResult.m_fraction < resultCallback.m_closestHitFraction) { castResult.m_normal.normalize(); btCollisionWorld::LocalConvexResult localConvexResult( colObjWrap->getCollisionObject(), 0, castResult.m_normal, castResult.m_hitPoint, castResult.m_fraction); bool normalInWorldSpace = true; resultCallback.addSingleResult(localConvexResult, normalInWorldSpace); } } } } else { //BT_PROFILE(""convexSweepConcave""); btConcaveShape* concaveShape = (btConcaveShape*)collisionShape; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 convexFromLocal = worldTocollisionObject * convexFromTrans.getOrigin(); btVector3 convexToLocal = worldTocollisionObject * convexToTrans.getOrigin(); // rotation of box in local mesh space = MeshRotation^-1 * ConvexToRotation btTransform rotationXform = btTransform(worldTocollisionObject.getBasis() * convexToTrans.getBasis()); //ConvexCast::CastResult struct BridgeTriangleConvexcastCallback : public btTriangleConvexcastCallback { btCollisionWorld::ConvexResultCallback* m_resultCallback; const btCollisionObject* m_collisionObject; btConcaveShape* m_triangleMesh; BridgeTriangleConvexcastCallback(const btConvexShape* castShape, const btTransform& from, const btTransform& to, btCollisionWorld::ConvexResultCallback* resultCallback, const btCollisionObject* collisionObject, btConcaveShape* triangleMesh, const btTransform& triangleToWorld) : btTriangleConvexcastCallback(castShape, from, to, triangleToWorld, triangleMesh->getMargin()), m_resultCallback(resultCallback), m_collisionObject(collisionObject), m_triangleMesh(triangleMesh) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = partId; shapeInfo.m_triangleIndex = triangleIndex; if (hitFraction <= m_resultCallback->m_closestHitFraction) { btCollisionWorld::LocalConvexResult convexResult(m_collisionObject, &shapeInfo, hitNormalLocal, hitPointLocal, hitFraction); bool normalInWorldSpace = true; return m_resultCallback->addSingleResult(convexResult, normalInWorldSpace); } return hitFraction; } }; BridgeTriangleConvexcastCallback tccb(castShape, convexFromTrans, convexToTrans, &resultCallback, colObjWrap->getCollisionObject(), concaveShape, colObjWorldTransform); tccb.m_hitFraction = resultCallback.m_closestHitFraction; tccb.m_allowedPenetration = allowedPenetration; btVector3 boxMinLocal, boxMaxLocal; castShape->getAabb(rotationXform, boxMinLocal, boxMaxLocal); btVector3 rayAabbMinLocal = convexFromLocal; rayAabbMinLocal.setMin(convexToLocal); btVector3 rayAabbMaxLocal = convexFromLocal; rayAabbMaxLocal.setMax(convexToLocal); rayAabbMinLocal += boxMinLocal; rayAabbMaxLocal += boxMaxLocal; concaveShape->processAllTriangles(&tccb, rayAabbMinLocal, rayAabbMaxLocal); } } } else { if (collisionShape->isCompound()) { struct btCompoundLeafCallback : btDbvt::ICollide { btCompoundLeafCallback( const btCollisionObjectWrapper* colObjWrap, const btConvexShape* castShape, const btTransform& convexFromTrans, const btTransform& convexToTrans, btScalar allowedPenetration, const btCompoundShape* compoundShape, const btTransform& colObjWorldTransform, ConvexResultCallback& resultCallback) : m_colObjWrap(colObjWrap), m_castShape(castShape), m_convexFromTrans(convexFromTrans), m_convexToTrans(convexToTrans), m_allowedPenetration(allowedPenetration), m_compoundShape(compoundShape), m_colObjWorldTransform(colObjWorldTransform), m_resultCallback(resultCallback) { } const btCollisionObjectWrapper* m_colObjWrap; const btConvexShape* m_castShape; const btTransform& m_convexFromTrans; const btTransform& m_convexToTrans; btScalar m_allowedPenetration; const btCompoundShape* m_compoundShape; const btTransform& m_colObjWorldTransform; ConvexResultCallback& m_resultCallback; public: void ProcessChild(int index, const btTransform& childTrans, const btCollisionShape* childCollisionShape) { btTransform childWorldTrans = m_colObjWorldTransform * childTrans; struct LocalInfoAdder : public ConvexResultCallback { ConvexResultCallback* m_userCallback; int m_i; LocalInfoAdder(int i, ConvexResultCallback* user) : m_userCallback(user), m_i(i) { m_closestHitFraction = m_userCallback->m_closestHitFraction; } virtual bool needsCollision(btBroadphaseProxy* p) const { return m_userCallback->needsCollision(p); } virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& r, bool b) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = -1; shapeInfo.m_triangleIndex = m_i; if (r.m_localShapeInfo == NULL) r.m_localShapeInfo = &shapeInfo; const btScalar result = m_userCallback->addSingleResult(r, b); m_closestHitFraction = m_userCallback->m_closestHitFraction; return result; } }; LocalInfoAdder my_cb(index, &m_resultCallback); btCollisionObjectWrapper tmpObj(m_colObjWrap, childCollisionShape, m_colObjWrap->getCollisionObject(), childWorldTrans, -1, index); objectQuerySingleInternal(m_castShape, m_convexFromTrans, m_convexToTrans, &tmpObj, my_cb, m_allowedPenetration); } void Process(const btDbvtNode* leaf) { // Processing leaf node int index = leaf->dataAsInt; btTransform childTrans = m_compoundShape->getChildTransform(index); const btCollisionShape* childCollisionShape = m_compoundShape->getChildShape(index); ProcessChild(index, childTrans, childCollisionShape); } }; BT_PROFILE(""convexSweepCompound""); const btCompoundShape* compoundShape = static_cast(collisionShape); btVector3 fromLocalAabbMin, fromLocalAabbMax; btVector3 toLocalAabbMin, toLocalAabbMax; castShape->getAabb(colObjWorldTransform.inverse() * convexFromTrans, fromLocalAabbMin, fromLocalAabbMax); castShape->getAabb(colObjWorldTransform.inverse() * convexToTrans, toLocalAabbMin, toLocalAabbMax); fromLocalAabbMin.setMin(toLocalAabbMin); fromLocalAabbMax.setMax(toLocalAabbMax); btCompoundLeafCallback callback(colObjWrap, castShape, convexFromTrans, convexToTrans, allowedPenetration, compoundShape, colObjWorldTransform, resultCallback); const btDbvt* tree = compoundShape->getDynamicAabbTree(); if (tree) { const ATTRIBUTE_ALIGNED16(btDbvtVolume) bounds = btDbvtVolume::FromMM(fromLocalAabbMin, fromLocalAabbMax); tree->collideTV(tree->m_root, bounds, callback); } else { int i; for (i = 0; i < compoundShape->getNumChildShapes(); i++) { const btCollisionShape* childCollisionShape = compoundShape->getChildShape(i); btTransform childTrans = compoundShape->getChildTransform(i); callback.ProcessChild(i, childTrans, childCollisionShape); } } } } } } struct btSingleRayCallback : public btBroadphaseRayCallback { btVector3 m_rayFromWorld; btVector3 m_rayToWorld; btTransform m_rayFromTrans; btTransform m_rayToTrans; btVector3 m_hitNormal; const btCollisionWorld* m_world; btCollisionWorld::RayResultCallback& m_resultCallback; btSingleRayCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld, const btCollisionWorld* world, btCollisionWorld::RayResultCallback& resultCallback) : m_rayFromWorld(rayFromWorld), m_rayToWorld(rayToWorld), m_world(world), m_resultCallback(resultCallback) { m_rayFromTrans.setIdentity(); m_rayFromTrans.setOrigin(m_rayFromWorld); m_rayToTrans.setIdentity(); m_rayToTrans.setOrigin(m_rayToWorld); btVector3 rayDir = (rayToWorld - rayFromWorld); rayDir.normalize(); ///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0]; m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1]; m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2]; m_signs[0] = m_rayDirectionInverse[0] < 0.0; m_signs[1] = m_rayDirectionInverse[1] < 0.0; m_signs[2] = m_rayDirectionInverse[2] < 0.0; m_lambda_max = rayDir.dot(m_rayToWorld - m_rayFromWorld); } virtual bool process(const btBroadphaseProxy* proxy) { ///terminate further ray tests, once the closestHitFraction reached zero if (m_resultCallback.m_closestHitFraction == btScalar(0.f)) return false; btCollisionObject* collisionObject = (btCollisionObject*)proxy->m_clientObject; //only perform raycast if filterMask matches if (m_resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); //btVector3 collisionObjectAabbMin,collisionObjectAabbMax; #if 0 #ifdef RECALCULATE_AABB btVector3 collisionObjectAabbMin,collisionObjectAabbMax; collisionObject->getCollisionShape()->getAabb(collisionObject->getWorldTransform(),collisionObjectAabbMin,collisionObjectAabbMax); #else //getBroadphase()->getAabb(collisionObject->getBroadphaseHandle(),collisionObjectAabbMin,collisionObjectAabbMax); const btVector3& collisionObjectAabbMin = collisionObject->getBroadphaseHandle()->m_aabbMin; const btVector3& collisionObjectAabbMax = collisionObject->getBroadphaseHandle()->m_aabbMax; #endif #endif //btScalar hitLambda = m_resultCallback.m_closestHitFraction; //culling already done by broadphase //if (btRayAabb(m_rayFromWorld,m_rayToWorld,collisionObjectAabbMin,collisionObjectAabbMax,hitLambda,m_hitNormal)) { m_world->rayTestSingle(m_rayFromTrans, m_rayToTrans, collisionObject, collisionObject->getCollisionShape(), collisionObject->getWorldTransform(), m_resultCallback); } } return true; } }; void btCollisionWorld::rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const { //BT_PROFILE(""rayTest""); /// use the broadphase to accelerate the search for objects, based on their aabb /// and for each object with ray-aabb overlap, perform an exact ray test btSingleRayCallback rayCB(rayFromWorld, rayToWorld, this, resultCallback); #ifndef USE_BRUTEFORCE_RAYBROADPHASE m_broadphasePairCache->rayTest(rayFromWorld, rayToWorld, rayCB); #else for (int i = 0; i < this->getNumCollisionObjects(); i++) { rayCB.process(m_collisionObjects[i]->getBroadphaseHandle()); } #endif //USE_BRUTEFORCE_RAYBROADPHASE } struct btSingleSweepCallback : public btBroadphaseRayCallback { btTransform m_convexFromTrans; btTransform m_convexToTrans; btVector3 m_hitNormal; const btCollisionWorld* m_world; btCollisionWorld::ConvexResultCallback& m_resultCallback; btScalar m_allowedCcdPenetration; const btConvexShape* m_castShape; btSingleSweepCallback(const btConvexShape* castShape, const btTransform& convexFromTrans, const btTransform& convexToTrans, const btCollisionWorld* world, btCollisionWorld::ConvexResultCallback& resultCallback, btScalar allowedPenetration) : m_convexFromTrans(convexFromTrans), m_convexToTrans(convexToTrans), m_world(world), m_resultCallback(resultCallback), m_allowedCcdPenetration(allowedPenetration), m_castShape(castShape) { btVector3 unnormalizedRayDir = (m_convexToTrans.getOrigin() - m_convexFromTrans.getOrigin()); btVector3 rayDir = unnormalizedRayDir.fuzzyZero() ? btVector3(btScalar(0.0), btScalar(0.0), btScalar(0.0)) : unnormalizedRayDir.normalized(); ///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0]; m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1]; m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2]; m_signs[0] = m_rayDirectionInverse[0] < 0.0; m_signs[1] = m_rayDirectionInverse[1] < 0.0; m_signs[2] = m_rayDirectionInverse[2] < 0.0; m_lambda_max = rayDir.dot(unnormalizedRayDir); } virtual bool process(const btBroadphaseProxy* proxy) { ///terminate further convex sweep tests, once the closestHitFraction reached zero if (m_resultCallback.m_closestHitFraction == btScalar(0.f)) return false; btCollisionObject* collisionObject = (btCollisionObject*)proxy->m_clientObject; //only perform raycast if filterMask matches if (m_resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); m_world->objectQuerySingle(m_castShape, m_convexFromTrans, m_convexToTrans, collisionObject, collisionObject->getCollisionShape(), collisionObject->getWorldTransform(), m_resultCallback, m_allowedCcdPenetration); } return true; } }; void btCollisionWorld::convexSweepTest(const btConvexShape* castShape, const btTransform& convexFromWorld, const btTransform& convexToWorld, ConvexResultCallback& resultCallback, btScalar allowedCcdPenetration) const { BT_PROFILE(""convexSweepTest""); /// use the broadphase to accelerate the search for objects, based on their aabb /// and for each object with ray-aabb overlap, perform an exact ray test /// unfortunately the implementation for rayTest and convexSweepTest duplicated, albeit practically identical btTransform convexFromTrans, convexToTrans; convexFromTrans = convexFromWorld; convexToTrans = convexToWorld; btVector3 castShapeAabbMin, castShapeAabbMax; /* Compute AABB that encompasses angular movement */ { btVector3 linVel, angVel; btTransformUtil::calculateVelocity(convexFromTrans, convexToTrans, 1.0f, linVel, angVel); btVector3 zeroLinVel; zeroLinVel.setValue(0, 0, 0); btTransform R; R.setIdentity(); R.setRotation(convexFromTrans.getRotation()); castShape->calculateTemporalAabb(R, zeroLinVel, angVel, 1.0f, castShapeAabbMin, castShapeAabbMax); } #ifndef USE_BRUTEFORCE_RAYBROADPHASE btSingleSweepCallback convexCB(castShape, convexFromWorld, convexToWorld, this, resultCallback, allowedCcdPenetration); m_broadphasePairCache->rayTest(convexFromTrans.getOrigin(), convexToTrans.getOrigin(), convexCB, castShapeAabbMin, castShapeAabbMax); #else /// go over all objects, and if the ray intersects their aabb + cast shape aabb, // do a ray-shape query using convexCaster (CCD) int i; for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* collisionObject = m_collisionObjects[i]; //only perform raycast if filterMask matches if (resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); btVector3 collisionObjectAabbMin, collisionObjectAabbMax; collisionObject->getCollisionShape()->getAabb(collisionObject->getWorldTransform(), collisionObjectAabbMin, collisionObjectAabbMax); AabbExpand(collisionObjectAabbMin, collisionObjectAabbMax, castShapeAabbMin, castShapeAabbMax); btScalar hitLambda = btScalar(1.); //could use resultCallback.m_closestHitFraction, but needs testing btVector3 hitNormal; if (btRayAabb(convexFromWorld.getOrigin(), convexToWorld.getOrigin(), collisionObjectAabbMin, collisionObjectAabbMax, hitLambda, hitNormal)) { objectQuerySingle(castShape, convexFromTrans, convexToTrans, collisionObject, collisionObject->getCollisionShape(), collisionObject->getWorldTransform(), resultCallback, allowedCcdPenetration); } } } #endif //USE_BRUTEFORCE_RAYBROADPHASE } struct btBridgedManifoldResult : public btManifoldResult { btCollisionWorld::ContactResultCallback& m_resultCallback; btBridgedManifoldResult(const btCollisionObjectWrapper* obj0Wrap, const btCollisionObjectWrapper* obj1Wrap, btCollisionWorld::ContactResultCallback& resultCallback) : btManifoldResult(obj0Wrap, obj1Wrap), m_resultCallback(resultCallback) { } virtual void addContactPoint(const btVector3& normalOnBInWorld, const btVector3& pointInWorld, btScalar depth) { bool isSwapped = m_manifoldPtr->getBody0() != m_body0Wrap->getCollisionObject(); btVector3 pointA = pointInWorld + normalOnBInWorld * depth; btVector3 localA; btVector3 localB; if (isSwapped) { localA = m_body1Wrap->getCollisionObject()->getWorldTransform().invXform(pointA); localB = m_body0Wrap->getCollisionObject()->getWorldTransform().invXform(pointInWorld); } else { localA = m_body0Wrap->getCollisionObject()->getWorldTransform().invXform(pointA); localB = m_body1Wrap->getCollisionObject()->getWorldTransform().invXform(pointInWorld); } btManifoldPoint newPt(localA, localB, normalOnBInWorld, depth); newPt.m_positionWorldOnA = pointA; newPt.m_positionWorldOnB = pointInWorld; //BP mod, store contact triangles. if (isSwapped) { newPt.m_partId0 = m_partId1; newPt.m_partId1 = m_partId0; newPt.m_index0 = m_index1; newPt.m_index1 = m_index0; } else { newPt.m_partId0 = m_partId0; newPt.m_partId1 = m_partId1; newPt.m_index0 = m_index0; newPt.m_index1 = m_index1; } //experimental feature info, for per-triangle material etc. const btCollisionObjectWrapper* obj0Wrap = isSwapped ? m_body1Wrap : m_body0Wrap; const btCollisionObjectWrapper* obj1Wrap = isSwapped ? m_body0Wrap : m_body1Wrap; m_resultCallback.addSingleResult(newPt, obj0Wrap, newPt.m_partId0, newPt.m_index0, obj1Wrap, newPt.m_partId1, newPt.m_index1); } }; struct btSingleContactCallback : public btBroadphaseAabbCallback { btCollisionObject* m_collisionObject; btCollisionWorld* m_world; btCollisionWorld::ContactResultCallback& m_resultCallback; btSingleContactCallback(btCollisionObject* collisionObject, btCollisionWorld* world, btCollisionWorld::ContactResultCallback& resultCallback) : m_collisionObject(collisionObject), m_world(world), m_resultCallback(resultCallback) { } virtual bool process(const btBroadphaseProxy* proxy) { btCollisionObject* collisionObject = (btCollisionObject*)proxy->m_clientObject; if (collisionObject == m_collisionObject) return true; //only perform raycast if filterMask matches if (m_resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { btCollisionObjectWrapper ob0(0, m_collisionObject->getCollisionShape(), m_collisionObject, m_collisionObject->getWorldTransform(), -1, -1); btCollisionObjectWrapper ob1(0, collisionObject->getCollisionShape(), collisionObject, collisionObject->getWorldTransform(), -1, -1); btCollisionAlgorithm* algorithm = m_world->getDispatcher()->findAlgorithm(&ob0, &ob1, 0, BT_CLOSEST_POINT_ALGORITHMS); if (algorithm) { btBridgedManifoldResult contactPointResult(&ob0, &ob1, m_resultCallback); //discrete collision detection query algorithm->processCollision(&ob0, &ob1, m_world->getDispatchInfo(), &contactPointResult); algorithm->~btCollisionAlgorithm(); m_world->getDispatcher()->freeCollisionAlgorithm(algorithm); } } return true; } }; ///contactTest performs a discrete collision test against all objects in the btCollisionWorld, and calls the resultCallback. ///it reports one or more contact points for every overlapping object (including the one with deepest penetration) void btCollisionWorld::contactTest(btCollisionObject* colObj, ContactResultCallback& resultCallback) { btVector3 aabbMin, aabbMax; colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), aabbMin, aabbMax); btSingleContactCallback contactCB(colObj, this, resultCallback); m_broadphasePairCache->aabbTest(aabbMin, aabbMax, contactCB); } ///contactTest performs a discrete collision test between two collision objects and calls the resultCallback if overlap if detected. ///it reports one or more contact points (including the one with deepest penetration) void btCollisionWorld::contactPairTest(btCollisionObject* colObjA, btCollisionObject* colObjB, ContactResultCallback& resultCallback) { btCollisionObjectWrapper obA(0, colObjA->getCollisionShape(), colObjA, colObjA->getWorldTransform(), -1, -1); btCollisionObjectWrapper obB(0, colObjB->getCollisionShape(), colObjB, colObjB->getWorldTransform(), -1, -1); btCollisionAlgorithm* algorithm = getDispatcher()->findAlgorithm(&obA, &obB, 0, BT_CLOSEST_POINT_ALGORITHMS); if (algorithm) { btBridgedManifoldResult contactPointResult(&obA, &obB, resultCallback); contactPointResult.m_closestPointDistanceThreshold = resultCallback.m_closestDistanceThreshold; //discrete collision detection query algorithm->processCollision(&obA, &obB, getDispatchInfo(), &contactPointResult); algorithm->~btCollisionAlgorithm(); getDispatcher()->freeCollisionAlgorithm(algorithm); } } class DebugDrawcallback : public btTriangleCallback, public btInternalTriangleIndexCallback { btIDebugDraw* m_debugDrawer; btVector3 m_color; btTransform m_worldTrans; public: DebugDrawcallback(btIDebugDraw* debugDrawer, const btTransform& worldTrans, const btVector3& color) : m_debugDrawer(debugDrawer), m_color(color), m_worldTrans(worldTrans) { } virtual void internalProcessTriangleIndex(btVector3* triangle, int partId, int triangleIndex) { processTriangle(triangle, partId, triangleIndex); } virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex) { (void)partId; (void)triangleIndex; btVector3 wv0, wv1, wv2; wv0 = m_worldTrans * triangle[0]; wv1 = m_worldTrans * triangle[1]; wv2 = m_worldTrans * triangle[2]; btVector3 center = (wv0 + wv1 + wv2) * btScalar(1. / 3.); if (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawNormals) { btVector3 normal = (wv1 - wv0).cross(wv2 - wv0); normal.normalize(); btVector3 normalColor(1, 1, 0); m_debugDrawer->drawLine(center, center + normal, normalColor); } m_debugDrawer->drawTriangle(wv0, wv1, wv2, m_color, 1.0); } }; void btCollisionWorld::debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color) { // Draw a small simplex at the center of the object if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawFrames) { getDebugDrawer()->drawTransform(worldTransform, .1); } if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE) { const btCompoundShape* compoundShape = static_cast(shape); for (int i = compoundShape->getNumChildShapes() - 1; i >= 0; i--) { btTransform childTrans = compoundShape->getChildTransform(i); const btCollisionShape* colShape = compoundShape->getChildShape(i); debugDrawObject(worldTransform * childTrans, colShape, color); } } else { switch (shape->getShapeType()) { case BOX_SHAPE_PROXYTYPE: { const btBoxShape* boxShape = static_cast(shape); btVector3 halfExtents = boxShape->getHalfExtentsWithMargin(); getDebugDrawer()->drawBox(-halfExtents, halfExtents, worldTransform, color); break; } case SPHERE_SHAPE_PROXYTYPE: { const btSphereShape* sphereShape = static_cast(shape); btScalar radius = sphereShape->getMargin(); //radius doesn't include the margin, so draw with margin getDebugDrawer()->drawSphere(radius, worldTransform, color); break; } case MULTI_SPHERE_SHAPE_PROXYTYPE: { const btMultiSphereShape* multiSphereShape = static_cast(shape); btTransform childTransform; childTransform.setIdentity(); for (int i = multiSphereShape->getSphereCount() - 1; i >= 0; i--) { childTransform.setOrigin(multiSphereShape->getSpherePosition(i)); getDebugDrawer()->drawSphere(multiSphereShape->getSphereRadius(i), worldTransform * childTransform, color); } break; } case CAPSULE_SHAPE_PROXYTYPE: { const btCapsuleShape* capsuleShape = static_cast(shape); btScalar radius = capsuleShape->getRadius(); btScalar halfHeight = capsuleShape->getHalfHeight(); int upAxis = capsuleShape->getUpAxis(); getDebugDrawer()->drawCapsule(radius, halfHeight, upAxis, worldTransform, color); break; } case CONE_SHAPE_PROXYTYPE: { const btConeShape* coneShape = static_cast(shape); btScalar radius = coneShape->getRadius(); //+coneShape->getMargin(); btScalar height = coneShape->getHeight(); //+coneShape->getMargin(); int upAxis = coneShape->getConeUpIndex(); getDebugDrawer()->drawCone(radius, height, upAxis, worldTransform, color); break; } case CYLINDER_SHAPE_PROXYTYPE: { const btCylinderShape* cylinder = static_cast(shape); int upAxis = cylinder->getUpAxis(); btScalar radius = cylinder->getRadius(); btScalar halfHeight = cylinder->getHalfExtentsWithMargin()[upAxis]; getDebugDrawer()->drawCylinder(radius, halfHeight, upAxis, worldTransform, color); break; } case STATIC_PLANE_PROXYTYPE: { const btStaticPlaneShape* staticPlaneShape = static_cast(shape); btScalar planeConst = staticPlaneShape->getPlaneConstant(); const btVector3& planeNormal = staticPlaneShape->getPlaneNormal(); getDebugDrawer()->drawPlane(planeNormal, planeConst, worldTransform, color); break; } default: { /// for polyhedral shapes if (shape->isPolyhedral()) { btPolyhedralConvexShape* polyshape = (btPolyhedralConvexShape*)shape; int i; if (polyshape->getConvexPolyhedron()) { const btConvexPolyhedron* poly = polyshape->getConvexPolyhedron(); for (i = 0; i < poly->m_faces.size(); i++) { btVector3 centroid(0, 0, 0); int numVerts = poly->m_faces[i].m_indices.size(); if (numVerts) { int lastV = poly->m_faces[i].m_indices[numVerts - 1]; for (int v = 0; v < poly->m_faces[i].m_indices.size(); v++) { int curVert = poly->m_faces[i].m_indices[v]; centroid += poly->m_vertices[curVert]; getDebugDrawer()->drawLine(worldTransform * poly->m_vertices[lastV], worldTransform * poly->m_vertices[curVert], color); lastV = curVert; } } centroid *= btScalar(1.f) / btScalar(numVerts); if (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawNormals) { btVector3 normalColor(1, 1, 0); btVector3 faceNormal(poly->m_faces[i].m_plane[0], poly->m_faces[i].m_plane[1], poly->m_faces[i].m_plane[2]); getDebugDrawer()->drawLine(worldTransform * centroid, worldTransform * (centroid + faceNormal), normalColor); } } } else { for (i = 0; i < polyshape->getNumEdges(); i++) { btVector3 a, b; polyshape->getEdge(i, a, b); btVector3 wa = worldTransform * a; btVector3 wb = worldTransform * b; getDebugDrawer()->drawLine(wa, wb, color); } } } if (shape->isConcave()) { btConcaveShape* concaveMesh = (btConcaveShape*)shape; ///@todo pass camera, for some culling? no -> we are not a graphics lib btVector3 aabbMax(btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT)); btVector3 aabbMin(btScalar(-BT_LARGE_FLOAT), btScalar(-BT_LARGE_FLOAT), btScalar(-BT_LARGE_FLOAT)); DebugDrawcallback drawCallback(getDebugDrawer(), worldTransform, color); concaveMesh->processAllTriangles(&drawCallback, aabbMin, aabbMax); } if (shape->getShapeType() == CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE) { btConvexTriangleMeshShape* convexMesh = (btConvexTriangleMeshShape*)shape; //todo: pass camera for some culling btVector3 aabbMax(btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT)); btVector3 aabbMin(btScalar(-BT_LARGE_FLOAT), btScalar(-BT_LARGE_FLOAT), btScalar(-BT_LARGE_FLOAT)); //DebugDrawcallback drawCallback; DebugDrawcallback drawCallback(getDebugDrawer(), worldTransform, color); convexMesh->getMeshInterface()->InternalProcessAllTriangles(&drawCallback, aabbMin, aabbMax); } } } } } void btCollisionWorld::debugDrawWorld() { if (getDebugDrawer()) { getDebugDrawer()->clearLines(); btIDebugDraw::DefaultColors defaultColors = getDebugDrawer()->getDefaultColors(); if (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints) { if (getDispatcher()) { int numManifolds = getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = getDispatcher()->getManifoldByIndexInternal(i); //btCollisionObject* obA = static_cast(contactManifold->getBody0()); //btCollisionObject* obB = static_cast(contactManifold->getBody1()); int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& cp = contactManifold->getContactPoint(j); getDebugDrawer()->drawContactPoint(cp.m_positionWorldOnB, cp.m_normalWorldOnB, cp.getDistance(), cp.getLifeTime(), defaultColors.m_contactPoint); } } } } if ((getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb))) { int i; for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* colObj = m_collisionObjects[i]; if ((colObj->getCollisionFlags() & btCollisionObject::CF_DISABLE_VISUALIZE_OBJECT) == 0) { if (getDebugDrawer() && (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawWireframe)) { btVector3 color(btScalar(0.4), btScalar(0.4), btScalar(0.4)); switch (colObj->getActivationState()) { case ACTIVE_TAG: color = defaultColors.m_activeObject; break; case ISLAND_SLEEPING: color = defaultColors.m_deactivatedObject; break; case WANTS_DEACTIVATION: color = defaultColors.m_wantsDeactivationObject; break; case DISABLE_DEACTIVATION: color = defaultColors.m_disabledDeactivationObject; break; case DISABLE_SIMULATION: color = defaultColors.m_disabledSimulationObject; break; default: { color = btVector3(btScalar(.3), btScalar(0.3), btScalar(0.3)); } }; colObj->getCustomDebugColor(color); debugDrawObject(colObj->getWorldTransform(), colObj->getCollisionShape(), color); } if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb)) { btVector3 minAabb, maxAabb; btVector3 colorvec = defaultColors.m_aabb; colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb, maxAabb); btVector3 contactThreshold(gContactBreakingThreshold, gContactBreakingThreshold, gContactBreakingThreshold); minAabb -= contactThreshold; maxAabb += contactThreshold; btVector3 minAabb2, maxAabb2; if (getDispatchInfo().m_useContinuous && colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY && !colObj->isStaticOrKinematicObject()) { colObj->getCollisionShape()->getAabb(colObj->getInterpolationWorldTransform(), minAabb2, maxAabb2); minAabb2 -= contactThreshold; maxAabb2 += contactThreshold; minAabb.setMin(minAabb2); maxAabb.setMax(maxAabb2); } m_debugDrawer->drawAabb(minAabb, maxAabb, colorvec); } } } } } } void btCollisionWorld::serializeCollisionObjects(btSerializer* serializer) { int i; ///keep track of shapes already serialized btHashMap serializedShapes; for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* colObj = m_collisionObjects[i]; btCollisionShape* shape = colObj->getCollisionShape(); if (!serializedShapes.find(shape)) { serializedShapes.insert(shape, shape); shape->serializeSingleShape(serializer); } } //serialize all collision objects for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* colObj = m_collisionObjects[i]; if (colObj->getInternalType() == btCollisionObject::CO_COLLISION_OBJECT) { colObj->serializeSingleObject(serializer); } } } void btCollisionWorld::serializeContactManifolds(btSerializer* serializer) { if (serializer->getSerializationFlags() & BT_SERIALIZE_CONTACT_MANIFOLDS) { int numManifolds = getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { const btPersistentManifold* manifold = getDispatcher()->getInternalManifoldPointer()[i]; //don't serialize empty manifolds, they just take space //(may have to do it anyway if it destroys determinism) if (manifold->getNumContacts() == 0) continue; btChunk* chunk = serializer->allocate(manifold->calculateSerializeBufferSize(), 1); const char* structType = manifold->serialize(manifold, chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk, structType, BT_CONTACTMANIFOLD_CODE, (void*)manifold); } } } void btCollisionWorld::serialize(btSerializer* serializer) { serializer->startSerialization(); serializeCollisionObjects(serializer); serializeContactManifolds(serializer); serializer->finishSerialization(); } ",16342,True,3032.2423857174927,median "CLASS zcl_abapgit_gui_page_diff DEFINITION PUBLIC INHERITING FROM zcl_abapgit_gui_page CREATE PUBLIC. PUBLIC SECTION. INTERFACES: zif_abapgit_gui_hotkeys. TYPES: BEGIN OF ty_file_diff, path TYPE string, filename TYPE string, obj_type TYPE string, obj_name TYPE string, lstate TYPE c LENGTH 1, rstate TYPE c LENGTH 1, fstate TYPE c LENGTH 1, "" FILE state - Abstraction for shorter ifs o_diff TYPE REF TO zcl_abapgit_diff, changed_by TYPE xubname, type TYPE string, END OF ty_file_diff. TYPES: ty_file_diffs TYPE STANDARD TABLE OF ty_file_diff WITH NON-UNIQUE DEFAULT KEY WITH NON-UNIQUE SORTED KEY secondary COMPONENTS path filename. CONSTANTS: BEGIN OF c_fstate, local TYPE c LENGTH 1 VALUE 'L', remote TYPE c LENGTH 1 VALUE 'R', both TYPE c LENGTH 1 VALUE 'B', END OF c_fstate. METHODS constructor IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key !is_file TYPE zif_abapgit_definitions=>ty_file OPTIONAL !is_object TYPE zif_abapgit_definitions=>ty_item OPTIONAL !it_files TYPE zif_abapgit_definitions=>ty_stage_tt OPTIONAL RAISING zcx_abapgit_exception. METHODS zif_abapgit_gui_event_handler~on_event REDEFINITION. PROTECTED SECTION. CONSTANTS: BEGIN OF c_actions, toggle_unified TYPE string VALUE 'toggle_unified', toggle_hidden_chars TYPE string VALUE 'toggle_hidden_chars', refresh_prefix TYPE string VALUE 'refresh', refresh_all TYPE string VALUE 'refresh_all', refresh_local TYPE string VALUE 'refresh_local', refresh_local_object TYPE string VALUE 'refresh_local_object', END OF c_actions , BEGIN OF c_action_texts, refresh_all TYPE string VALUE `Refresh All`, refresh_local TYPE string VALUE `Refresh Local`, END OF c_action_texts, BEGIN OF c_action_titles, refresh_local TYPE string VALUE `Refresh all local objects, without refreshing the remote`, refresh_all TYPE string VALUE `Complete refresh of all objects, local and remote`, END OF c_action_titles. DATA mv_unified TYPE abap_bool VALUE abap_true ##NO_TEXT. DATA mo_repo TYPE REF TO zcl_abapgit_repo . DATA mt_diff_files TYPE ty_file_diffs . METHODS get_normalized_fname_with_path IMPORTING !is_diff TYPE ty_file_diff RETURNING VALUE(rv_filename) TYPE string . METHODS normalize_path IMPORTING !iv_path TYPE string RETURNING VALUE(rv_normalized) TYPE string . METHODS normalize_filename IMPORTING !iv_filename TYPE string RETURNING VALUE(rv_normalized) TYPE string . METHODS add_menu_end IMPORTING !io_menu TYPE REF TO zcl_abapgit_html_toolbar . METHODS calculate_diff IMPORTING !is_file TYPE zif_abapgit_definitions=>ty_file OPTIONAL !is_object TYPE zif_abapgit_definitions=>ty_item OPTIONAL !it_files TYPE zif_abapgit_definitions=>ty_stage_tt OPTIONAL RAISING zcx_abapgit_exception . METHODS add_menu_begin IMPORTING !io_menu TYPE REF TO zcl_abapgit_html_toolbar . METHODS render_table_head_non_unified IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_diff TYPE ty_file_diff . METHODS render_beacon_begin_of_row IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_diff TYPE ty_file_diff . METHODS render_diff_head_after_state IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_diff TYPE ty_file_diff . METHODS insert_nav RETURNING VALUE(rv_insert_nav) TYPE abap_bool . METHODS render_line_split_row IMPORTING !ii_html TYPE REF TO zif_abapgit_html !iv_filename TYPE string !is_diff_line TYPE zif_abapgit_definitions=>ty_diff !iv_index TYPE sy-tabix !iv_fstate TYPE char1 !iv_new TYPE string !iv_old TYPE string RAISING zcx_abapgit_exception . METHODS build_menu RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . METHODS set_layout. METHODS refresh IMPORTING iv_action TYPE clike RAISING zcx_abapgit_exception . METHODS refresh_full RAISING zcx_abapgit_exception . METHODS refresh_local RAISING zcx_abapgit_exception . METHODS refresh_local_object IMPORTING iv_action TYPE clike RAISING zcx_abapgit_exception . METHODS is_refresh IMPORTING iv_action TYPE string RETURNING VALUE(rv_is_refrseh) TYPE abap_bool. METHODS modify_files_before_diff_calc IMPORTING !it_diff_files_old TYPE ty_file_diffs RETURNING VALUE(rt_files) TYPE zif_abapgit_definitions=>ty_stage_tt. METHODS render_content REDEFINITION . PRIVATE SECTION. DATA mt_delayed_lines TYPE zif_abapgit_definitions=>ty_diffs_tt . DATA mv_repo_key TYPE zif_abapgit_persistence=>ty_repo-key . DATA mv_seed TYPE string . "" Unique page id to bind JS sessionStorage DATA mv_hidden_chars TYPE abap_bool . METHODS render_diff IMPORTING !is_diff TYPE ty_file_diff RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS render_diff_head IMPORTING !is_diff TYPE ty_file_diff RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS render_table_head IMPORTING !is_diff TYPE ty_file_diff RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS render_beacon IMPORTING !is_diff_line TYPE zif_abapgit_definitions=>ty_diff !is_diff TYPE ty_file_diff RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . METHODS render_line_split IMPORTING !is_diff_line TYPE zif_abapgit_definitions=>ty_diff !iv_filename TYPE string !iv_fstate TYPE char1 !iv_index TYPE sy-tabix RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS render_line_unified IMPORTING !is_diff_line TYPE zif_abapgit_definitions=>ty_diff OPTIONAL RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . METHODS append_diff IMPORTING !it_remote TYPE zif_abapgit_definitions=>ty_files_tt !it_local TYPE zif_abapgit_definitions=>ty_files_item_tt !is_status TYPE zif_abapgit_definitions=>ty_result RAISING zcx_abapgit_exception . METHODS is_binary IMPORTING !iv_d1 TYPE xstring !iv_d2 TYPE xstring RETURNING VALUE(rv_yes) TYPE abap_bool . METHODS add_jump_sub_menu IMPORTING !io_menu TYPE REF TO zcl_abapgit_html_toolbar . METHODS add_filter_sub_menu IMPORTING !io_menu TYPE REF TO zcl_abapgit_html_toolbar . METHODS render_lines IMPORTING !is_diff TYPE ty_file_diff RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS render_table_head_unified IMPORTING !ii_html TYPE REF TO zif_abapgit_html . METHODS render_scripts RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . METHODS is_file_requested IMPORTING it_files TYPE zif_abapgit_definitions=>ty_stage_tt is_status TYPE zif_abapgit_definitions=>ty_result RETURNING VALUE(rv_is_file_requested) TYPE abap_bool. ENDCLASS. CLASS zcl_abapgit_gui_page_diff IMPLEMENTATION. METHOD add_filter_sub_menu. DATA: lo_sub_filter TYPE REF TO zcl_abapgit_html_toolbar, lv_user TYPE string, lt_extensions TYPE SORTED TABLE OF string WITH UNIQUE DEFAULT KEY, lt_obj_types TYPE SORTED TABLE OF string WITH UNIQUE DEFAULT KEY, lt_users TYPE SORTED TABLE OF string WITH UNIQUE DEFAULT KEY. FIELD-SYMBOLS: LIKE LINE OF mt_diff_files, TYPE string. "" Get unique filter values LOOP AT mt_diff_files ASSIGNING . lv_user = -changed_by. INSERT -type INTO TABLE lt_extensions. INSERT -obj_type INTO TABLE lt_obj_types. INSERT lv_user INTO TABLE lt_users. ENDLOOP. IF lines( lt_extensions ) > 1 OR lines( lt_obj_types ) > 1 OR lines( lt_users ) > 1. CREATE OBJECT lo_sub_filter EXPORTING iv_id = 'diff-filter'. IF lines( lt_users ) > 1. lo_sub_filter->add( iv_txt = 'Only my changes' iv_typ = zif_abapgit_html=>c_action_type-onclick iv_aux = |{ sy-uname }| iv_chk = abap_false ). ENDIF. "" File extensions IF lines( lt_extensions ) > 1. lo_sub_filter->add( iv_txt = 'Extension' iv_typ = zif_abapgit_html=>c_action_type-separator ). LOOP AT lt_extensions ASSIGNING . lo_sub_filter->add( iv_txt = iv_typ = zif_abapgit_html=>c_action_type-onclick iv_aux = 'extension' iv_chk = abap_true ). ENDLOOP. ENDIF. "" Object types IF lines( lt_obj_types ) > 1. lo_sub_filter->add( iv_txt = 'Object Type' iv_typ = zif_abapgit_html=>c_action_type-separator ). LOOP AT lt_obj_types ASSIGNING . lo_sub_filter->add( iv_txt = iv_typ = zif_abapgit_html=>c_action_type-onclick iv_aux = 'object-type' iv_chk = abap_true ). ENDLOOP. ENDIF. "" Changed by IF lines( lt_users ) > 1. lo_sub_filter->add( iv_txt = 'Changed By' iv_typ = zif_abapgit_html=>c_action_type-separator ). LOOP AT lt_users ASSIGNING . lo_sub_filter->add( iv_txt = iv_typ = zif_abapgit_html=>c_action_type-onclick iv_aux = 'changed-by' iv_chk = abap_true ). ENDLOOP. ENDIF. io_menu->add( iv_txt = 'Filter' io_sub = lo_sub_filter ). ENDIF. ENDMETHOD. METHOD add_jump_sub_menu. DATA: lo_sub_jump TYPE REF TO zcl_abapgit_html_toolbar, lv_jump_target TYPE string. FIELD-SYMBOLS: LIKE LINE OF mt_diff_files. CREATE OBJECT lo_sub_jump EXPORTING iv_id = 'jump'. LOOP AT mt_diff_files ASSIGNING . lv_jump_target = -path && -filename. lo_sub_jump->add( iv_id = |li_jump_{ sy-tabix }| iv_txt = lv_jump_target iv_typ = zif_abapgit_html=>c_action_type-onclick ). ENDLOOP. io_menu->add( iv_txt = 'Jump' io_sub = lo_sub_jump ). ENDMETHOD. METHOD add_menu_begin. io_menu->add( iv_txt = c_action_texts-refresh_local iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_act = c_actions-refresh_local iv_id = c_actions-refresh_local iv_title = c_action_titles-refresh_local ). io_menu->add( iv_txt = c_action_texts-refresh_all iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_act = c_actions-refresh_all iv_id = c_actions-refresh_all iv_title = c_action_titles-refresh_all ). ENDMETHOD. METHOD add_menu_end. io_menu->add( iv_txt = 'Split/Unified' iv_act = c_actions-toggle_unified ). io_menu->add( iv_txt = '¶' iv_title = 'Toggle Hidden Characters' iv_act = c_actions-toggle_hidden_chars ). ENDMETHOD. METHOD append_diff. DATA: lv_offs TYPE i, ls_r_dummy LIKE LINE OF it_remote ##NEEDED, ls_l_dummy LIKE LINE OF it_local ##NEEDED. FIELD-SYMBOLS: LIKE LINE OF it_remote, LIKE LINE OF it_local, LIKE LINE OF mt_diff_files. READ TABLE it_remote ASSIGNING WITH KEY file_path COMPONENTS path = is_status-path filename = is_status-filename. IF sy-subrc <> 0. ASSIGN ls_r_dummy TO . ENDIF. READ TABLE it_local ASSIGNING WITH KEY file-filename = is_status-filename file-path = is_status-path. IF sy-subrc <> 0. ASSIGN ls_l_dummy TO . ENDIF. IF IS INITIAL AND IS INITIAL. zcx_abapgit_exception=>raise( |DIFF: file not found { is_status-filename }| ). ENDIF. APPEND INITIAL LINE TO mt_diff_files ASSIGNING . -path = is_status-path. -filename = is_status-filename. -obj_type = is_status-obj_type. -obj_name = is_status-obj_name. -lstate = is_status-lstate. -rstate = is_status-rstate. IF -lstate IS NOT INITIAL AND -rstate IS NOT INITIAL. -fstate = c_fstate-both. ELSEIF -lstate IS NOT INITIAL. -fstate = c_fstate-local. ELSE. ""rstate IS NOT INITIAL, lstate = empty. -fstate = c_fstate-remote. ENDIF. "" Changed by IF -item-obj_type IS NOT INITIAL. -changed_by = zcl_abapgit_objects=>changed_by( -item ). ENDIF. IF -changed_by IS INITIAL. -changed_by = zcl_abapgit_objects_super=>c_user_unknown. ENDIF. "" Extension IF -file-filename IS NOT INITIAL. -type = reverse( -file-filename ). ELSE. -type = reverse( -filename ). ENDIF. FIND FIRST OCCURRENCE OF '.' IN -type MATCH OFFSET lv_offs. -type = reverse( substring( val = -type len = lv_offs ) ). IF -type <> 'xml' AND -type <> 'abap'. -type = 'other'. ENDIF. IF -type = 'other' AND is_binary( iv_d1 = -data iv_d2 = -file-data ) = abap_true. -type = 'binary'. ENDIF. "" Diff data IF -type <> 'binary'. IF -fstate = c_fstate-remote. "" Remote file leading changes CREATE OBJECT -o_diff EXPORTING iv_new = -data iv_old = -file-data. ELSE. "" Local leading changes or both were modified CREATE OBJECT -o_diff EXPORTING iv_new = -file-data iv_old = -data. ENDIF. ENDIF. ENDMETHOD. METHOD build_menu. CREATE OBJECT ro_menu EXPORTING iv_id = 'toolbar-main'. add_menu_begin( ro_menu ). add_jump_sub_menu( ro_menu ). add_filter_sub_menu( ro_menu ). add_menu_end( ro_menu ). ENDMETHOD. METHOD calculate_diff. DATA: lt_remote TYPE zif_abapgit_definitions=>ty_files_tt, lt_local TYPE zif_abapgit_definitions=>ty_files_item_tt, lt_status TYPE zif_abapgit_definitions=>ty_results_tt. DATA li_exit TYPE REF TO zif_abapgit_exit. FIELD-SYMBOLS: LIKE LINE OF lt_status. CLEAR: mt_diff_files. lt_remote = mo_repo->get_files_remote( ). lt_local = mo_repo->get_files_local( ). mo_repo->reset_status( ). lt_status = mo_repo->status( ). li_exit = zcl_abapgit_exit=>get_instance( ). li_exit->pre_calculate_repo_status( EXPORTING is_repo_meta = mo_repo->ms_data CHANGING ct_local = lt_local ct_remote = lt_remote ). IF is_file IS NOT INITIAL. "" Diff for one file READ TABLE lt_status ASSIGNING WITH KEY path = is_file-path filename = is_file-filename. append_diff( it_remote = lt_remote it_local = lt_local is_status = ). ELSEIF is_object IS NOT INITIAL. "" Diff for whole object LOOP AT lt_status ASSIGNING WHERE obj_type = is_object-obj_type AND obj_name = is_object-obj_name AND match IS INITIAL. append_diff( it_remote = lt_remote it_local = lt_local is_status = ). ENDLOOP. ELSE. "" Diff for the whole repo SORT lt_status BY path ASCENDING filename ASCENDING. LOOP AT lt_status ASSIGNING WHERE match IS INITIAL. IF is_file_requested( it_files = it_files is_status = ) = abap_true. append_diff( it_remote = lt_remote it_local = lt_local is_status = ). ENDIF. ENDLOOP. ENDIF. ENDMETHOD. METHOD constructor. DATA: lv_ts TYPE timestamp. super->constructor( ). ms_control-page_title = 'Diff'. mv_unified = zcl_abapgit_persistence_user=>get_instance( )->get_diff_unified( ). set_layout( ). mv_repo_key = iv_key. mo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). GET TIME STAMP FIELD lv_ts. mv_seed = |diff{ lv_ts }|. "" Generate based on time ASSERT is_file IS INITIAL OR is_object IS INITIAL. "" just one passed calculate_diff( is_file = is_file is_object = is_object it_files = it_files ). IF lines( mt_diff_files ) = 0. zcx_abapgit_exception=>raise( 'There are no differences to show. The local state completely matches the remote repository.' ). ENDIF. ms_control-page_menu = build_menu( ). ENDMETHOD. METHOD get_normalized_fname_with_path. rv_filename = normalize_path( is_diff-path ) && `_` && normalize_filename( is_diff-filename ). ENDMETHOD. METHOD insert_nav. ENDMETHOD. METHOD is_binary. FIELD-SYMBOLS LIKE iv_d1. IF iv_d1 IS NOT INITIAL. "" One of them might be new and so empty ASSIGN iv_d1 TO . ELSE. ASSIGN iv_d2 TO . ENDIF. rv_yes = zcl_abapgit_utils=>is_binary( ). ENDMETHOD. METHOD is_file_requested. IF lines( it_files ) = 0. rv_is_file_requested = abap_true. RETURN. ENDIF. READ TABLE it_files WITH KEY file-path = is_status-path file-filename = is_status-filename TRANSPORTING NO FIELDS. rv_is_file_requested = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD is_refresh. FIND FIRST OCCURRENCE OF REGEX |^{ c_actions-refresh_prefix }| IN iv_action. rv_is_refrseh = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD modify_files_before_diff_calc. DATA ls_file LIKE LINE OF rt_files. FIELD-SYMBOLS TYPE ty_file_diff. "" We need to supply files again in calculate_diff. Because "" we only want to refresh the visible files. Otherwise all "" diff files would appear. "" Which is not wanted when we previously only selected particular files. LOOP AT it_diff_files_old ASSIGNING . CLEAR ls_file. MOVE-CORRESPONDING TO ls_file-file. INSERT ls_file INTO TABLE rt_files. ENDLOOP. ENDMETHOD. METHOD normalize_filename. rv_normalized = replace( val = iv_filename sub = '.' occ = 0 with = '_' ). ENDMETHOD. METHOD normalize_path. rv_normalized = replace( val = iv_path sub = '/' occ = 0 with = '_' ). ENDMETHOD. METHOD refresh. DATA: lt_diff_files_old TYPE ty_file_diffs, lt_files TYPE zif_abapgit_definitions=>ty_stage_tt. lt_diff_files_old = mt_diff_files. CASE iv_action. WHEN c_actions-refresh_all. refresh_full( ). WHEN c_actions-refresh_local. refresh_local( ). WHEN OTHERS. refresh_local_object( iv_action ). ENDCASE. lt_files = modify_files_before_diff_calc( lt_diff_files_old ). calculate_diff( it_files = lt_files ). ENDMETHOD. METHOD refresh_full. mo_repo->refresh( abap_true ). ENDMETHOD. METHOD refresh_local. mo_repo->refresh_local_objects( ). ENDMETHOD. METHOD refresh_local_object. DATA: lv_regex TYPE string, lv_obj_type TYPE tadir-object, lv_obj_name TYPE tadir-obj_name. lv_regex = c_actions-refresh_local_object && `_(\\w{4})_(.*)`. FIND FIRST OCCURRENCE OF REGEX lv_regex IN iv_action SUBMATCHES lv_obj_type lv_obj_name. IF sy-subrc = 0. mo_repo->refresh_local_object( iv_obj_type = lv_obj_type iv_obj_name = lv_obj_name ). ELSE. zcx_abapgit_exception=>raise( |Invalid refresh action { iv_action }| ). ENDIF. ENDMETHOD. METHOD render_beacon. DATA: lv_beacon TYPE string, lt_beacons TYPE zif_abapgit_definitions=>ty_string_tt. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF is_diff_line-beacon > 0. lt_beacons = is_diff-o_diff->get_beacons( ). READ TABLE lt_beacons INTO lv_beacon INDEX is_diff_line-beacon. ELSE. lv_beacon = '---'. ENDIF. ri_html->add( '' ). ri_html->add( '' ). render_beacon_begin_of_row( ii_html = ri_html is_diff = is_diff ). IF mv_unified = abap_true. ri_html->add( '' ). ri_html->add( '' ). ri_html->add( |@@ { is_diff_line-new_num } @@ { lv_beacon }| ). ELSE. ri_html->add( |@@ { is_diff_line-new_num } @@ { lv_beacon }| ). ENDIF. ri_html->add( '' ). ri_html->add( '' ). ENDMETHOD. METHOD render_beacon_begin_of_row. ii_html->add( '' ). ENDMETHOD. METHOD render_content. DATA: ls_diff_file LIKE LINE OF mt_diff_files, li_progress TYPE REF TO zif_abapgit_progress. CREATE OBJECT ri_html TYPE zcl_abapgit_html. li_progress = zcl_abapgit_progress=>get_instance( lines( mt_diff_files ) ). ri_html->add( `
` ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_repo_top( mo_repo ) ). ri_html->add( `
` ). ri_html->add( |
| ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_js_error_banner( ) ). LOOP AT mt_diff_files INTO ls_diff_file. li_progress->show( iv_current = sy-tabix iv_text = |Render Diff - { ls_diff_file-filename }| ). ri_html->add( render_diff( ls_diff_file ) ). ENDLOOP. IF sy-subrc <> 0. ri_html->add( |No more diffs| ). ENDIF. ri_html->add( '
' ). register_deferred_script( render_scripts( ) ). li_progress->off( ). gui_services( )->get_hotkeys_ctl( )->register_hotkeys( zif_abapgit_gui_hotkeys~get_hotkey_actions( ) ). ENDMETHOD. METHOD render_diff. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( |
| ). ri_html->add( render_diff_head( is_diff ) ). "" Content IF is_diff-type <> 'binary'. ri_html->add( '
' ). ri_html->add( || ). ri_html->add( render_table_head( is_diff ) ). ri_html->add( render_lines( is_diff ) ). ri_html->add( '
' ). ELSE. ri_html->add( '
' ). ri_html->add( 'The content seems to be binary.' ). ri_html->add( 'Cannot display as diff.' ). ENDIF. ri_html->add( '
' ). ri_html->add( '
' ). ENDMETHOD. METHOD render_diff_head. DATA: ls_stats TYPE zif_abapgit_definitions=>ty_count, lv_link TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '
' ). ri_html->add_icon( iv_name = 'chevron-down' iv_hint = 'Collapse/Expand' iv_class = 'cursor-pointer' iv_onclick = 'onDiffCollapse(event)' ). IF is_diff-type <> 'binary'. ls_stats = is_diff-o_diff->stats( ). IF is_diff-fstate = c_fstate-both. "" Merge stats into 'update' if both were changed ls_stats-update = ls_stats-update + ls_stats-insert + ls_stats-delete. CLEAR: ls_stats-insert, ls_stats-delete. ENDIF. ri_html->add( |+ { ls_stats-insert }| ). ri_html->add( |- { ls_stats-delete }| ). ri_html->add( |~ { ls_stats-update }| ). ENDIF. "" no links for nonexistent or deleted objects IF NOT ( is_diff-lstate = zif_abapgit_definitions=>c_state-unchanged AND is_diff-rstate = zif_abapgit_definitions=>c_state-added ) AND NOT is_diff-lstate = zif_abapgit_definitions=>c_state-deleted. lv_link = ri_html->a( iv_txt = |{ is_diff-path }{ is_diff-filename }| iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_act = |jump?TYPE={ is_diff-obj_type }&NAME={ is_diff-obj_name }| ). ENDIF. IF lv_link IS NOT INITIAL. ri_html->add( |{ lv_link }| ). ELSE. ri_html->add( |{ is_diff-path }{ is_diff-filename }| ). ENDIF. ri_html->add( zcl_abapgit_gui_chunk_lib=>render_item_state( iv_lstate = is_diff-lstate iv_rstate = is_diff-rstate ) ). render_diff_head_after_state( ii_html = ri_html is_diff = is_diff ). ri_html->add( 'Last Changed by: ' ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_user_name( is_diff-changed_by ) ). ri_html->add( '' ). ri_html->add( '
' ). ENDMETHOD. METHOD render_diff_head_after_state. IF is_diff-fstate = c_fstate-both AND mv_unified = abap_true. ii_html->add( 'Attention: Unified mode' && ' highlighting for MM assumes local file is newer ! ' ). ENDIF. IF is_diff-obj_type IS NOT INITIAL AND is_diff-obj_name IS NOT INITIAL. ii_html->add( '' ). ii_html->add_a( iv_txt = ii_html->icon( iv_name = 'redo-alt-solid' iv_class = 'pad-sides' iv_hint = 'Local refresh of this object' ) iv_act = |{ c_actions-refresh_local_object }_{ is_diff-obj_type }_{ is_diff-obj_name }| iv_class = |url| ). ii_html->add( '' ). ENDIF. ENDMETHOD. METHOD render_lines. DATA: lo_highlighter TYPE REF TO zcl_abapgit_syntax_highlighter, lt_diffs TYPE zif_abapgit_definitions=>ty_diffs_tt, lv_insert_nav TYPE abap_bool, lv_tabix TYPE syst-tabix. FIELD-SYMBOLS LIKE LINE OF lt_diffs. lo_highlighter = zcl_abapgit_syntax_factory=>create( iv_filename = is_diff-filename iv_hidden_chars = mv_hidden_chars ). CREATE OBJECT ri_html TYPE zcl_abapgit_html. lt_diffs = is_diff-o_diff->get( ). lv_insert_nav = insert_nav( ). LOOP AT lt_diffs ASSIGNING . lv_tabix = sy-tabix. IF -short = abap_false. lv_insert_nav = abap_true. CONTINUE. ENDIF. IF lv_insert_nav = abap_true. "" Insert separator line with navigation ri_html->add( render_beacon( is_diff_line = is_diff = is_diff ) ). lv_insert_nav = abap_false. ENDIF. IF lo_highlighter IS BOUND. -new = lo_highlighter->process_line( -new ). -old = lo_highlighter->process_line( -old ). ELSE. -new = escape( val = -new format = cl_abap_format=>e_html_attr ). -old = escape( val = -old format = cl_abap_format=>e_html_attr ). ENDIF. CONDENSE -new_num. ""get rid of leading spaces CONDENSE -old_num. IF mv_unified = abap_true. ri_html->add( render_line_unified( is_diff_line = ) ). ELSE. ri_html->add( render_line_split( is_diff_line = iv_filename = get_normalized_fname_with_path( is_diff ) iv_fstate = is_diff-fstate iv_index = lv_tabix ) ). ENDIF. ENDLOOP. IF mv_unified = abap_true. ri_html->add( render_line_unified( ) ). "" Release delayed lines ENDIF. ENDMETHOD. METHOD render_line_split. DATA: lv_new TYPE string, lv_old TYPE string, lv_mark TYPE string, lv_bg TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. "" New line lv_mark = ` `. IF is_diff_line-result IS NOT INITIAL. IF iv_fstate = c_fstate-both OR is_diff_line-result = zif_abapgit_definitions=>c_diff-update. lv_bg = ' diff_upd'. lv_mark = `~`. ELSEIF is_diff_line-result = zif_abapgit_definitions=>c_diff-insert. lv_bg = ' diff_ins'. lv_mark = `+`. ENDIF. ENDIF. lv_new = || && |{ lv_mark }| && |{ is_diff_line-new }|. "" Old line CLEAR lv_bg. lv_mark = ` `. IF is_diff_line-result IS NOT INITIAL. IF iv_fstate = c_fstate-both OR is_diff_line-result = zif_abapgit_definitions=>c_diff-update. lv_bg = ' diff_upd'. lv_mark = `~`. ELSEIF is_diff_line-result = zif_abapgit_definitions=>c_diff-delete. lv_bg = ' diff_del'. lv_mark = `-`. ENDIF. ENDIF. lv_old = || && |{ lv_mark }| && |{ is_diff_line-old }|. "" render line, inverse sides if remote is newer ri_html->add( '' ). render_line_split_row( ii_html = ri_html iv_filename = iv_filename is_diff_line = is_diff_line iv_index = iv_index iv_fstate = iv_fstate iv_old = lv_old iv_new = lv_new ). ri_html->add( '' ). ENDMETHOD. METHOD render_line_split_row. IF iv_fstate = c_fstate-remote. "" Remote file leading changes ii_html->add( iv_old ). "" local ii_html->add( iv_new ). "" remote ELSE. "" Local leading changes or both were modified ii_html->add( iv_new ). "" local ii_html->add( iv_old ). "" remote ENDIF. ENDMETHOD. METHOD render_line_unified. FIELD-SYMBOLS LIKE LINE OF mt_delayed_lines. CREATE OBJECT ri_html TYPE zcl_abapgit_html. "" Release delayed subsequent update lines IF is_diff_line-result <> zif_abapgit_definitions=>c_diff-update. LOOP AT mt_delayed_lines ASSIGNING . ri_html->add( '' ). ri_html->add( |-old_num }"">| && || && |-| && |{ -old }| ). ri_html->add( '' ). ENDLOOP. LOOP AT mt_delayed_lines ASSIGNING . ri_html->add( '' ). ri_html->add( || && |-new_num }"">| && |+| && |{ -new }| ). ri_html->add( '' ). ENDLOOP. CLEAR mt_delayed_lines. ENDIF. ri_html->add( '' ). CASE is_diff_line-result. WHEN zif_abapgit_definitions=>c_diff-update. APPEND is_diff_line TO mt_delayed_lines. "" Delay output of subsequent updates WHEN zif_abapgit_definitions=>c_diff-insert. ri_html->add( || && || && |+| && |{ is_diff_line-new }| ). WHEN zif_abapgit_definitions=>c_diff-delete. ri_html->add( || && || && |-| && |{ is_diff_line-old }| ). WHEN OTHERS. ""none ri_html->add( || && || && | | && |{ is_diff_line-old }| ). ENDCASE. ri_html->add( '' ). ENDMETHOD. METHOD render_scripts. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->set_title( cl_abap_typedescr=>describe_by_object_ref( me )->get_relative_name( ) ). ri_html->add( 'restoreScrollPosition();' ). ri_html->add( 'var gHelper = new DiffHelper({' ). ri_html->add( | seed: ""{ mv_seed }"",| ). ri_html->add( ' ids: {' ). ri_html->add( ' jump: ""jump"",' ). ri_html->add( ' diffList: ""diff-list"",' ). ri_html->add( ' filterMenu: ""diff-filter"",' ). ri_html->add( ' }' ). ri_html->add( '});' ). ri_html->add( 'addMarginBottom();' ). ri_html->add( 'var gGoJumpPalette = new CommandPalette(enumerateJumpAllFiles, {' ). ri_html->add( ' toggleKey: ""F2"",' ). ri_html->add( ' hotkeyDescription: ""Jump to file ...""' ). ri_html->add( '});' ). "" Feature for selecting ABAP code by column and copy to clipboard ri_html->add( 'var columnSelection = new DiffColumnSelection();' ). ENDMETHOD. METHOD render_table_head. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '' ). ri_html->add( '' ). IF mv_unified = abap_true. render_table_head_unified( ri_html ). ELSE. render_table_head_non_unified( ii_html = ri_html is_diff = is_diff ). ENDIF. ri_html->add( '' ). ri_html->add( '' ). ENDMETHOD. METHOD render_table_head_non_unified. ii_html->add( '' ). ii_html->add( '' ). ii_html->add( 'LOCAL' ). ii_html->add( '' ). ii_html->add( '' ). ii_html->add( 'REMOTE' ). ENDMETHOD. METHOD render_table_head_unified. ii_html->add( 'old' ). ii_html->add( 'new' ). ii_html->add( '' ). ii_html->add( 'code' ). ENDMETHOD. METHOD set_layout. IF mv_unified = abap_true. ms_control-page_layout = c_page_layout-centered. ELSE. ms_control-page_layout = c_page_layout-full_width. ENDIF. ENDMETHOD. METHOD zif_abapgit_gui_event_handler~on_event. CASE ii_event->mv_action. WHEN c_actions-toggle_unified. "" Toggle file diplay mv_unified = zcl_abapgit_persistence_user=>get_instance( )->toggle_diff_unified( ). set_layout( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN c_actions-toggle_hidden_chars. "" Toggle display of hidden characters mv_hidden_chars = boolc( mv_hidden_chars = abap_false ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN OTHERS. IF is_refresh( ii_event->mv_action ) = abap_true. refresh( ii_event->mv_action ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ELSE. rs_handled = super->zif_abapgit_gui_event_handler~on_event( ii_event ). ENDIF. ENDCASE. ENDMETHOD. METHOD zif_abapgit_gui_hotkeys~get_hotkey_actions. DATA: ls_hotkey_action LIKE LINE OF rt_hotkey_actions. ls_hotkey_action-ui_component = 'Diff'. ls_hotkey_action-description = |Refresh Local|. ls_hotkey_action-action = c_actions-refresh_local. ls_hotkey_action-hotkey = |r|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Refresh All|. ls_hotkey_action-action = c_actions-refresh_all. ls_hotkey_action-hotkey = |a|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Toogle Split/Unified|. ls_hotkey_action-action = c_actions-toggle_unified. ls_hotkey_action-hotkey = |u|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ls_hotkey_action-description = |Toogle Hidden Characters|. ls_hotkey_action-action = c_actions-toggle_hidden_chars. ls_hotkey_action-hotkey = |h|. INSERT ls_hotkey_action INTO TABLE rt_hotkey_actions. ENDMETHOD. ENDCLASS. ",10044,False,1852.6212417826125,median "/**************************************************************************************************************************** ConfigOnSwitchFS_MQTT_Ptr.ino For ESP8266 / ESP32 boards ESP_WiFiManager is a library for the ESP8266/ESP32 platform (https://github.com/esp8266/Arduino) to enable easy configuration and reconfiguration of WiFi credentials using a Captive Portal. Inspired by: http://www.esp8266.com/viewtopic.php?f=29&t=2520 https://github.com/chriscook8/esp-arduino-apboot https://github.com/esp8266/Arduino/blob/master/libraries/DNSServer/examples/CaptivePortalAdvanced/ Modified from Tzapu https://github.com/tzapu/WiFiManager and from Ken Taylor https://github.com/kentaylor Built by Khoi Hoang https://github.com/khoih-prog/ESP_WiFiManager Licensed under MIT license Version: 1.4.3 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.0 K Hoang 07/10/2019 Initial coding 1.0.1 K Hoang 13/12/2019 Fix bug. Add features. Add support for ESP32 1.0.2 K Hoang 19/12/2019 Fix bug thatkeeps ConfigPortal in endless loop if Portal/Router SSID or Password is NULL. 1.0.3 K Hoang 05/01/2020 Option not displaying AvailablePages in Info page. Enhance README.md. Modify examples 1.0.4 K Hoang 07/01/2020 Add RFC952 setHostname feature. 1.0.5 K Hoang 15/01/2020 Add configurable DNS feature. Thanks to @Amorphous of https://community.blynk.cc 1.0.6 K Hoang 03/02/2020 Add support for ArduinoJson version 6.0.0+ ( tested with v6.14.1 ) 1.0.7 K Hoang 13/04/2020 Reduce start time, fix SPIFFS bug in examples, update README.md 1.0.8 K Hoang 10/06/2020 Fix STAstaticIP issue. Restructure code. Add LittleFS support for ESP8266 core 2.7.1+ 1.0.9 K Hoang 29/07/2020 Fix ESP32 STAstaticIP bug. Permit changing from DHCP <-> static IP using Config Portal. Add, enhance examples (fix MDNS for ESP32) 1.0.10 K Hoang 08/08/2020 Add more features to Config Portal. Use random WiFi AP channel to avoid conflict. 1.0.11 K Hoang 17/08/2020 Add CORS feature. Fix bug in softAP, autoConnect, resetSettings. 1.1.0 K Hoang 28/08/2020 Add MultiWiFi feature to autoconnect to best WiFi at runtime 1.1.1 K Hoang 30/08/2020 Add setCORSHeader function to allow flexible CORS. Fix typo and minor improvement. 1.1.2 K Hoang 17/08/2020 Fix bug. Add example. 1.2.0 K Hoang 09/10/2020 Restore cpp code besides Impl.h code to use if linker error. Fix bug. 1.3.0 K Hoang 04/12/2020 Add LittleFS support to ESP32 using LITTLEFS Library 1.4.1 K Hoang 22/12/2020 Fix staticIP not saved. Add functions. Add complex examples. Sync with ESPAsync_WiFiManager 1.4.2 K Hoang 14/01/2021 Fix examples' bug not using saved WiFi Credentials after losing all WiFi connections. 1.4.3 K Hoang 23/01/2021 Fix examples' bug not saving Static IP in certain cases. *****************************************************************************************************************************/ /**************************************************************************************************************************** This example will open a configuration portal when no WiFi configuration has been previously entered or when a button is pushed. It is the easiest scenario for configuration but requires a pin and a button on the ESP8266/ESP32 device. The Flash button is convenient for this on NodeMCU devices. Also in this example a password is required to connect to the configuration portal network. This is inconvenient but means that only those who know the password or those already connected to the target WiFi network can access the configuration portal and the WiFi network credentials will be sent from the browser over an encrypted connection and can not be read by observers. The Credentials, being input via Config Portal, will then be saved into LittleFS / SPIFFS file, and be used to connect to Adafruit MQTT Server at ""io.adafruit.com"" and publish a Temperature Topic Based on original sketch posted by user ""wackoo"" on https://forum.arduino.cc/index.php?topic=692108 *****************************************************************************************************************************/ #if !( defined(ESP8266) || defined(ESP32) ) #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting. #endif #define ESP_WIFIMANAGER_VERSION_MIN_TARGET ""ESP_WiFiManager v1.4.3"" // Use from 0 to 4. Higher number, more debugging messages and memory usage. #define _WIFIMGR_LOGLEVEL_ 3 #include // for button #include // for button #include // Now support ArduinoJson 6.0.0+ ( tested with v6.15.2 to v6.16.1 ) #include // get it from https://arduinojson.org/ or install via Arduino library manager //For ESP32, To use ESP32 Dev Module, QIO, Flash 4MB/80MHz, Upload 921600 //Ported to ESP32 #ifdef ESP32 #include #include #include // From v1.1.0 #include WiFiMulti wifiMulti; // LittleFS has higher priority than SPIFFS #define USE_LITTLEFS true #define USE_SPIFFS false #if USE_LITTLEFS // Use LittleFS #include ""FS.h"" // The library will be depreciated after being merged to future major Arduino esp32 core release 2.x // At that time, just remove this library inclusion #include // https://github.com/lorol/LITTLEFS FS* filesystem = &LITTLEFS; #define FileFS LITTLEFS #define FS_Name ""LittleFS"" #elif USE_SPIFFS #include FS* filesystem = &SPIFFS; #define FileFS SPIFFS #define FS_Name ""SPIFFS"" #else // Use FFat #include FS* filesystem = &FFat; #define FileFS FFat #define FS_Name ""FFat"" #endif ////// #define ESP_getChipId() ((uint32_t)ESP.getEfuseMac()) #define LED_BUILTIN 2 #define LED_ON HIGH #define LED_OFF LOW #else #include //https://github.com/esp8266/Arduino //needed for library #include #include // From v1.1.0 #include ESP8266WiFiMulti wifiMulti; #define USE_LITTLEFS true #if USE_LITTLEFS #include FS* filesystem = &LittleFS; #define FileFS LittleFS #define FS_Name ""LittleFS"" #else FS* filesystem = &SPIFFS; #define FileFS SPIFFS #define FS_Name ""SPIFFS"" #endif ////// #define ESP_getChipId() (ESP.getChipId()) #define LED_ON LOW #define LED_OFF HIGH #endif #include ""Adafruit_MQTT.h"" //https://github.com/adafruit/Adafruit_MQTT_Library #include ""Adafruit_MQTT_Client.h"" //https://github.com/adafruit/Adafruit_MQTT_Library #if ESP32 //See file .../hardware/espressif/esp32/variants/(esp32|doitESP32devkitV1)/pins_arduino.h #define LED_BUILTIN 2 // Pin D2 mapped to pin GPIO2/ADC12 of ESP32, control on-board LED #define PIN_LED 2 // Pin D2 mapped to pin GPIO2/ADC12 of ESP32, control on-board LED #define PIN_D0 0 // Pin D0 mapped to pin GPIO0/BOOT/ADC11/TOUCH1 of ESP32 #define PIN_D1 1 // Pin D1 mapped to pin GPIO1/TX0 of ESP32 #define PIN_D2 2 // Pin D2 mapped to pin GPIO2/ADC12/TOUCH2 of ESP32 #define PIN_D3 3 // Pin D3 mapped to pin GPIO3/RX0 of ESP32 #define PIN_D4 4 // Pin D4 mapped to pin GPIO4/ADC10/TOUCH0 of ESP32 #define PIN_D5 5 // Pin D5 mapped to pin GPIO5/SPISS/VSPI_SS of ESP32 #define PIN_D6 6 // Pin D6 mapped to pin GPIO6/FLASH_SCK of ESP32 #define PIN_D7 7 // Pin D7 mapped to pin GPIO7/FLASH_D0 of ESP32 #define PIN_D8 8 // Pin D8 mapped to pin GPIO8/FLASH_D1 of ESP32 #define PIN_D9 9 // Pin D9 mapped to pin GPIO9/FLASH_D2 of ESP32 #define PIN_D10 10 // Pin D10 mapped to pin GPIO10/FLASH_D3 of ESP32 #define PIN_D11 11 // Pin D11 mapped to pin GPIO11/FLASH_CMD of ESP32 #define PIN_D12 12 // Pin D12 mapped to pin GPIO12/HSPI_MISO/ADC15/TOUCH5/TDI of ESP32 #define PIN_D13 13 // Pin D13 mapped to pin GPIO13/HSPI_MOSI/ADC14/TOUCH4/TCK of ESP32 #define PIN_D14 14 // Pin D14 mapped to pin GPIO14/HSPI_SCK/ADC16/TOUCH6/TMS of ESP32 #define PIN_D15 15 // Pin D15 mapped to pin GPIO15/HSPI_SS/ADC13/TOUCH3/TDO of ESP32 #define PIN_D16 16 // Pin D16 mapped to pin GPIO16/TX2 of ESP32 #define PIN_D17 17 // Pin D17 mapped to pin GPIO17/RX2 of ESP32 #define PIN_D18 18 // Pin D18 mapped to pin GPIO18/VSPI_SCK of ESP32 #define PIN_D19 19 // Pin D19 mapped to pin GPIO19/VSPI_MISO of ESP32 #define PIN_D21 21 // Pin D21 mapped to pin GPIO21/SDA of ESP32 #define PIN_D22 22 // Pin D22 mapped to pin GPIO22/SCL of ESP32 #define PIN_D23 23 // Pin D23 mapped to pin GPIO23/VSPI_MOSI of ESP32 #define PIN_D24 24 // Pin D24 mapped to pin GPIO24 of ESP32 #define PIN_D25 25 // Pin D25 mapped to pin GPIO25/ADC18/DAC1 of ESP32 #define PIN_D26 26 // Pin D26 mapped to pin GPIO26/ADC19/DAC2 of ESP32 #define PIN_D27 27 // Pin D27 mapped to pin GPIO27/ADC17/TOUCH7 of ESP32 #define PIN_D32 32 // Pin D32 mapped to pin GPIO32/ADC4/TOUCH9 of ESP32 #define PIN_D33 33 // Pin D33 mapped to pin GPIO33/ADC5/TOUCH8 of ESP32 #define PIN_D34 34 // Pin D34 mapped to pin GPIO34/ADC6 of ESP32 //Only GPIO pin < 34 can be used as output. Pins >= 34 can be only inputs //See .../cores/esp32/esp32-hal-gpio.h/c //#define digitalPinIsValid(pin) ((pin) < 40 && esp32_gpioMux[(pin)].reg) //#define digitalPinCanOutput(pin) ((pin) < 34 && esp32_gpioMux[(pin)].reg) //#define digitalPinToRtcPin(pin) (((pin) < 40)?esp32_gpioMux[(pin)].rtc:-1) //#define digitalPinToAnalogChannel(pin) (((pin) < 40)?esp32_gpioMux[(pin)].adc:-1) //#define digitalPinToTouchChannel(pin) (((pin) < 40)?esp32_gpioMux[(pin)].touch:-1) //#define digitalPinToDacChannel(pin) (((pin) == 25)?0:((pin) == 26)?1:-1) #define PIN_D35 35 // Pin D35 mapped to pin GPIO35/ADC7 of ESP32 #define PIN_D36 36 // Pin D36 mapped to pin GPIO36/ADC0/SVP of ESP32 #define PIN_D39 39 // Pin D39 mapped to pin GPIO39/ADC3/SVN of ESP32 #define PIN_RX0 3 // Pin RX0 mapped to pin GPIO3/RX0 of ESP32 #define PIN_TX0 1 // Pin TX0 mapped to pin GPIO1/TX0 of ESP32 #define PIN_SCL 22 // Pin SCL mapped to pin GPIO22/SCL of ESP32 #define PIN_SDA 21 // Pin SDA mapped to pin GPIO21/SDA of ESP32 #else //PIN_D0 can't be used for PWM/I2C #define PIN_D0 16 // Pin D0 mapped to pin GPIO16/USER/WAKE of ESP8266. This pin is also used for Onboard-Blue LED. PIN_D0 = 0 => LED ON #define PIN_D1 5 // Pin D1 mapped to pin GPIO5 of ESP8266 #define PIN_D2 4 // Pin D2 mapped to pin GPIO4 of ESP8266 #define PIN_D3 0 // Pin D3 mapped to pin GPIO0/FLASH of ESP8266 #define PIN_D4 2 // Pin D4 mapped to pin GPIO2/TXD1 of ESP8266 #define PIN_LED 2 // Pin D4 mapped to pin GPIO2/TXD1 of ESP8266, NodeMCU and WeMoS, control on-board LED #define PIN_D5 14 // Pin D5 mapped to pin GPIO14/HSCLK of ESP8266 #define PIN_D6 12 // Pin D6 mapped to pin GPIO12/HMISO of ESP8266 #define PIN_D7 13 // Pin D7 mapped to pin GPIO13/RXD2/HMOSI of ESP8266 #define PIN_D8 15 // Pin D8 mapped to pin GPIO15/TXD2/HCS of ESP8266 //Don't use pins GPIO6 to GPIO11 as already connected to flash, etc. Use them can crash the program //GPIO9(D11/SD2) and GPIO11 can be used only if flash in DIO mode ( not the default QIO mode) #define PIN_D11 9 // Pin D11/SD2 mapped to pin GPIO9/SDD2 of ESP8266 #define PIN_D12 10 // Pin D12/SD3 mapped to pin GPIO10/SDD3 of ESP8266 #define PIN_SD2 9 // Pin SD2 mapped to pin GPIO9/SDD2 of ESP8266 #define PIN_SD3 10 // Pin SD3 mapped to pin GPIO10/SDD3 of ESP8266 #define PIN_D9 3 // Pin D9 /RX mapped to pin GPIO3/RXD0 of ESP8266 #define PIN_D10 1 // Pin D10/TX mapped to pin GPIO1/TXD0 of ESP8266 #define PIN_RX 3 // Pin RX mapped to pin GPIO3/RXD0 of ESP8266 #define PIN_TX 1 // Pin RX mapped to pin GPIO1/TXD0 of ESP8266 #define LED_PIN 16 // Pin D0 mapped to pin GPIO16 of ESP8266. This pin is also used for Onboard-Blue LED. PIN_D0 = 0 => LED ON #endif //ESP32 #if ESP32 const int BUTTON_PIN = PIN_D27; const int RED_LED = PIN_D26; const int BLUE_LED = PIN_D25; #else const int BUTTON_PIN = PIN_D1; const int RED_LED = PIN_D2; const int BLUE_LED = PIN_D5; #endif //ESP32 uint32_t timer = millis(); const char* CONFIG_FILE = ""/ConfigMQTT.json""; // Indicates whether ESP has WiFi credentials saved from previous session bool initialConfig = true; //default false // Default configuration values for Adafruit IO MQTT // This actually works #define AIO_SERVER ""io.adafruit.com"" #define AIO_SERVERPORT ""1883"" //1883, or 8883 for SSL #define AIO_USERNAME ""private"" //Adafruit IO #define AIO_KEY ""private"" // Labels for custom parameters in WiFi manager #define AIO_SERVER_Label ""AIO_SERVER_Label"" #define AIO_SERVERPORT_Label ""AIO_SERVERPORT_Label"" #define AIO_USERNAME_Label ""AIO_USERNAME_Label"" #define AIO_KEY_Label ""AIO_KEY_Label"" // Just dummy topics. To be updated later when got valid data from FS or Config Portal String MQTT_Pub_Topic = ""private/feeds/Temperature""; // Variables to save custom parameters to... // I would like to use these instead of #defines // Variables to save custom parameters to... // I would like to use these instead of #defines #define custom_AIO_SERVER_LEN 20 #define custom_AIO_PORT_LEN 5 #define custom_AIO_USERNAME_LEN 20 #define custom_AIO_KEY_LEN 40 char custom_AIO_SERVER[custom_AIO_SERVER_LEN]; char custom_AIO_SERVERPORT[custom_AIO_PORT_LEN]; char custom_AIO_USERNAME[custom_AIO_USERNAME_LEN]; char custom_AIO_KEY[custom_AIO_KEY_LEN]; // Function Prototypes void MQTT_connect(); bool readConfigFile(); bool writeConfigFile(); // For Config Portal // SSID and PW for Config Portal String ssid = ""ESP_"" + String(ESP_getChipId(), HEX); const char* password = ""your_password""; // SSID and PW for your Router String Router_SSID; String Router_Pass; // From v1.1.0 // You only need to format the filesystem once //#define FORMAT_FILESYSTEM true #define FORMAT_FILESYSTEM false #define MIN_AP_PASSWORD_SIZE 8 #define SSID_MAX_LEN 32 //From v1.0.10, WPA2 passwords can be up to 63 characters long. #define PASS_MAX_LEN 64 typedef struct { char wifi_ssid[SSID_MAX_LEN]; char wifi_pw [PASS_MAX_LEN]; } WiFi_Credentials; typedef struct { String wifi_ssid; String wifi_pw; } WiFi_Credentials_String; #define NUM_WIFI_CREDENTIALS 2 typedef struct { WiFi_Credentials WiFi_Creds [NUM_WIFI_CREDENTIALS]; } WM_Config; WM_Config WM_config; #define CONFIG_FILENAME F(""/wifi_cred.dat"") ////// // Indicates whether ESP has WiFi credentials saved from previous session //bool initialConfig = false; // Use false if you don't like to display Available Pages in Information Page of Config Portal // Comment out or use true to display Available Pages in Information Page of Config Portal // Must be placed before #include #define USE_AVAILABLE_PAGES false // From v1.0.10 to permit disable/enable StaticIP configuration in Config Portal from sketch. Valid only if DHCP is used. // You'll loose the feature of dynamically changing from DHCP to static IP, or vice versa // You have to explicitly specify false to disable the feature. //#define USE_STATIC_IP_CONFIG_IN_CP false // Use false to disable NTP config. Advisable when using Cellphone, Tablet to access Config Portal. // See Issue 23: On Android phone ConfigPortal is unresponsive (https://github.com/khoih-prog/ESP_WiFiManager/issues/23) #define USE_ESP_WIFIMANAGER_NTP false // Use true to enable CloudFlare NTP service. System can hang if you don't have Internet access while accessing CloudFlare // See Issue #21: CloudFlare link in the default portal (https://github.com/khoih-prog/ESP_WiFiManager/issues/21) #define USE_CLOUDFLARE_NTP false // New in v1.0.11 #define USING_CORS_FEATURE true ////// // Use USE_DHCP_IP == true for dynamic DHCP IP, false to use static IP which you have to change accordingly to your network #if (defined(USE_STATIC_IP_CONFIG_IN_CP) && !USE_STATIC_IP_CONFIG_IN_CP) // Force DHCP to be true #if defined(USE_DHCP_IP) #undef USE_DHCP_IP #endif #define USE_DHCP_IP true #else // You can select DHCP or Static IP here //#define USE_DHCP_IP true #define USE_DHCP_IP false #endif // Use USE_DHCP_IP == true for dynamic DHCP IP, false to use static IP which you have to change accordingly to your network #if (defined(USE_STATIC_IP_CONFIG_IN_CP) && !USE_STATIC_IP_CONFIG_IN_CP) // Force DHCP to be true #if defined(USE_DHCP_IP) #undef USE_DHCP_IP #endif #define USE_DHCP_IP true #else // You can select DHCP or Static IP here //#define USE_DHCP_IP true #define USE_DHCP_IP false #endif #if ( USE_DHCP_IP ) // Use DHCP #warning Using DHCP IP IPAddress stationIP = IPAddress(0, 0, 0, 0); IPAddress gatewayIP = IPAddress(192, 168, 2, 1); IPAddress netMask = IPAddress(255, 255, 255, 0); #else // Use static IP #warning Using static IP #ifdef ESP32 IPAddress stationIP = IPAddress(192, 168, 2, 232); #else IPAddress stationIP = IPAddress(192, 168, 2, 186); #endif IPAddress gatewayIP = IPAddress(192, 168, 2, 1); IPAddress netMask = IPAddress(255, 255, 255, 0); #endif #define USE_CONFIGURABLE_DNS true IPAddress dns1IP = gatewayIP; IPAddress dns2IP = IPAddress(8, 8, 8, 8); // New in v1.4.0 IPAddress APStaticIP = IPAddress(192, 168, 100, 1); IPAddress APStaticGW = IPAddress(192, 168, 100, 1); IPAddress APStaticSN = IPAddress(255, 255, 255, 0); #include //https://github.com/khoih-prog/ESP_WiFiManager //Button config OneButton btn = OneButton( BUTTON_PIN, // Input pin for the button true, // Button is active LOW true // Enable internal pull-up resistor ); // Create an ESP32 WiFiClient class to connect to the MQTT server WiFiClient *client = NULL; Adafruit_MQTT_Client *mqtt = NULL; Adafruit_MQTT_Publish *Temperature = NULL; /////////////////////////////////////////// // New in v1.4.0 /****************************************** * // Defined in ESPAsync_WiFiManager.h typedef struct { IPAddress _ap_static_ip; IPAddress _ap_static_gw; IPAddress _ap_static_sn; } WiFi_AP_IPConfig; typedef struct { IPAddress _sta_static_ip; IPAddress _sta_static_gw; IPAddress _sta_static_sn; #if USE_CONFIGURABLE_DNS IPAddress _sta_static_dns1; IPAddress _sta_static_dns2; #endif } WiFi_STA_IPConfig; ******************************************/ WiFi_AP_IPConfig WM_AP_IPconfig; WiFi_STA_IPConfig WM_STA_IPconfig; void initAPIPConfigStruct(WiFi_AP_IPConfig &in_WM_AP_IPconfig) { in_WM_AP_IPconfig._ap_static_ip = APStaticIP; in_WM_AP_IPconfig._ap_static_gw = APStaticGW; in_WM_AP_IPconfig._ap_static_sn = APStaticSN; } void initSTAIPConfigStruct(WiFi_STA_IPConfig &in_WM_STA_IPconfig) { in_WM_STA_IPconfig._sta_static_ip = stationIP; in_WM_STA_IPconfig._sta_static_gw = gatewayIP; in_WM_STA_IPconfig._sta_static_sn = netMask; #if USE_CONFIGURABLE_DNS in_WM_STA_IPconfig._sta_static_dns1 = dns1IP; in_WM_STA_IPconfig._sta_static_dns2 = dns2IP; #endif } void displayIPConfigStruct(WiFi_STA_IPConfig in_WM_STA_IPconfig) { LOGERROR3(F(""stationIP =""), in_WM_STA_IPconfig._sta_static_ip, "", gatewayIP ="", in_WM_STA_IPconfig._sta_static_gw); LOGERROR1(F(""netMask =""), in_WM_STA_IPconfig._sta_static_sn); #if USE_CONFIGURABLE_DNS LOGERROR3(F(""dns1IP =""), in_WM_STA_IPconfig._sta_static_dns1, "", dns2IP ="", in_WM_STA_IPconfig._sta_static_dns2); #endif } void configWiFi(WiFi_STA_IPConfig in_WM_STA_IPconfig) { #if USE_CONFIGURABLE_DNS // Set static IP, Gateway, Subnetmask, DNS1 and DNS2. New in v1.0.5 WiFi.config(in_WM_STA_IPconfig._sta_static_ip, in_WM_STA_IPconfig._sta_static_gw, in_WM_STA_IPconfig._sta_static_sn, in_WM_STA_IPconfig._sta_static_dns1, in_WM_STA_IPconfig._sta_static_dns2); #else // Set static IP, Gateway, Subnetmask, Use auto DNS1 and DNS2. WiFi.config(in_WM_STA_IPconfig._sta_static_ip, in_WM_STA_IPconfig._sta_static_gw, in_WM_STA_IPconfig._sta_static_sn); #endif } /////////////////////////////////////////// uint8_t connectMultiWiFi() { #if ESP32 // For ESP32, this better be 0 to shorten the connect time #define WIFI_MULTI_1ST_CONNECT_WAITING_MS 0 #else // For ESP8266, this better be 2200 to enable connect the 1st time #define WIFI_MULTI_1ST_CONNECT_WAITING_MS 2200L #endif #define WIFI_MULTI_CONNECT_WAITING_MS 100L uint8_t status; LOGERROR(F(""ConnectMultiWiFi with :"")); if ( (Router_SSID != """") && (Router_Pass != """") ) { LOGERROR3(F(""* Flash-stored Router_SSID = ""), Router_SSID, F("", Router_Pass = ""), Router_Pass ); } for (uint8_t i = 0; i < NUM_WIFI_CREDENTIALS; i++) { // Don't permit NULL SSID and password len < MIN_AP_PASSWORD_SIZE (8) if ( (String(WM_config.WiFi_Creds[i].wifi_ssid) != """") && (strlen(WM_config.WiFi_Creds[i].wifi_pw) >= MIN_AP_PASSWORD_SIZE) ) { LOGERROR3(F(""* Additional SSID = ""), WM_config.WiFi_Creds[i].wifi_ssid, F("", PW = ""), WM_config.WiFi_Creds[i].wifi_pw ); } } LOGERROR(F(""Connecting MultiWifi..."")); WiFi.mode(WIFI_STA); #if !USE_DHCP_IP // New in v1.4.0 configWiFi(WM_STA_IPconfig); ////// #endif int i = 0; status = wifiMulti.run(); delay(WIFI_MULTI_1ST_CONNECT_WAITING_MS); while ( ( i++ < 20 ) && ( status != WL_CONNECTED ) ) { status = wifiMulti.run(); if ( status == WL_CONNECTED ) break; else delay(WIFI_MULTI_CONNECT_WAITING_MS); } if ( status == WL_CONNECTED ) { LOGERROR1(F(""WiFi connected after time: ""), i); LOGERROR3(F(""SSID:""), WiFi.SSID(), F("",RSSI=""), WiFi.RSSI()); LOGERROR3(F(""Channel:""), WiFi.channel(), F("",IP address:""), WiFi.localIP() ); } else LOGERROR(F(""WiFi not connected"")); return status; } void toggleLED() { //toggle state digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } void heartBeatPrint() { static int num = 1; if (WiFi.status() == WL_CONNECTED) Serial.print(F(""W"")); // W means connected to WiFi else Serial.print(F(""N"")); // N means not connected to WiFi if (num == 40) { Serial.println(); num = 1; } else if (num++ % 5 == 0) { Serial.print(F("" "")); } } void publishMQTT() { float some_number = 25.0 + (float) ( millis() % 100 ) / 100; // For debug only //Serial.print(F(""Published Temp = "")); //Serial.println(some_number); MQTT_connect(); if (Temperature->publish(some_number)) { //Serial.println(F(""Failed to send value to Temperature feed!"")); Serial.print(F(""T"")); // T means publishing OK } else { //Serial.println(F(""Value to Temperature feed sucessfully sent!"")); Serial.print(F(""F"")); // F means publishing failure } } void check_WiFi() { if ( (WiFi.status() != WL_CONNECTED) ) { Serial.println(F(""\\nWiFi lost. Call connectMultiWiFi in loop"")); connectMultiWiFi(); } } void check_status() { static ulong checkstatus_timeout = 0; static ulong LEDstatus_timeout = 0; static ulong checkwifi_timeout = 0; static ulong mqtt_publish_timeout = 0; ulong current_millis = millis(); #define WIFICHECK_INTERVAL 1000L #define LED_INTERVAL 2000L #define HEARTBEAT_INTERVAL 10000L #define PUBLISH_INTERVAL 60000L // Check WiFi every WIFICHECK_INTERVAL (1) seconds. if ((current_millis > checkwifi_timeout) || (checkwifi_timeout == 0)) { check_WiFi(); checkwifi_timeout = current_millis + WIFICHECK_INTERVAL; } if ((current_millis > LEDstatus_timeout) || (LEDstatus_timeout == 0)) { // Toggle LED at LED_INTERVAL = 2s toggleLED(); LEDstatus_timeout = current_millis + LED_INTERVAL; } // Print hearbeat every HEARTBEAT_INTERVAL (10) seconds. if ((current_millis > checkstatus_timeout) || (checkstatus_timeout == 0)) { heartBeatPrint(); checkstatus_timeout = current_millis + HEARTBEAT_INTERVAL; } // Check every PUBLISH_INTERVAL (60) seconds. if ((current_millis > mqtt_publish_timeout) || (mqtt_publish_timeout == 0)) { if (WiFi.status() == WL_CONNECTED) { publishMQTT(); } mqtt_publish_timeout = current_millis + PUBLISH_INTERVAL; } } bool loadConfigData() { File file = FileFS.open(CONFIG_FILENAME, ""r""); LOGERROR(F(""LoadWiFiCfgFile "")); memset(&WM_config, 0, sizeof(WM_config)); // New in v1.4.0 memset(&WM_STA_IPconfig, 0, sizeof(WM_STA_IPconfig)); ////// if (file) { file.readBytes((char *) &WM_config, sizeof(WM_config)); // New in v1.4.0 file.readBytes((char *) &WM_STA_IPconfig, sizeof(WM_STA_IPconfig)); ////// file.close(); LOGERROR(F(""OK"")); // New in v1.4.0 displayIPConfigStruct(WM_STA_IPconfig); ////// return true; } else { LOGERROR(F(""failed"")); return false; } } void saveConfigData() { File file = FileFS.open(CONFIG_FILENAME, ""w""); LOGERROR(F(""SaveWiFiCfgFile "")); if (file) { file.write((uint8_t*) &WM_config, sizeof(WM_config)); displayIPConfigStruct(WM_STA_IPconfig); // New in v1.4.0 file.write((uint8_t*) &WM_STA_IPconfig, sizeof(WM_STA_IPconfig)); ////// file.close(); LOGERROR(F(""OK"")); } else { LOGERROR(F(""failed"")); } } void deleteOldInstances() { // Delete previous instances if (mqtt) { delete mqtt; mqtt = NULL; Serial.println(F(""Deleting old MQTT object"")); } if (Temperature) { delete Temperature; Temperature = NULL; Serial.println(F(""Deleting old Temperature object"")); } } void createNewInstances() { if (!client) { client = new WiFiClient; Serial.print(F(""\\nCreating new WiFi client object : "")); Serial.println(client? F(""OK"") : F(""failed"")); } // Create new instances from new data if (!mqtt) { // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. mqtt = new Adafruit_MQTT_Client(client, custom_AIO_SERVER, atoi(custom_AIO_SERVERPORT), custom_AIO_USERNAME, custom_AIO_KEY); Serial.print(F(""Creating new MQTT object : "")); if (mqtt) { Serial.println(F(""OK"")); Serial.println(String(""AIO_SERVER = "") + custom_AIO_SERVER + "", AIO_SERVERPORT = "" + custom_AIO_SERVERPORT); Serial.println(String(""AIO_USERNAME = "") + custom_AIO_USERNAME + "", AIO_KEY = "" + custom_AIO_KEY); } else Serial.println(F(""Failed"")); } if (!Temperature) { Serial.print(F(""Creating new MQTT_Pub_Topic, Temperature = "")); Serial.println(MQTT_Pub_Topic); Temperature = new Adafruit_MQTT_Publish(mqtt, MQTT_Pub_Topic.c_str()); Serial.print(F(""Creating new Temperature object : "")); if (Temperature) { Serial.println(F(""OK"")); Serial.println(String(""Temperature MQTT_Pub_Topic = "") + MQTT_Pub_Topic); } else Serial.println(F(""Failed"")); } } //event handler functions for button static void handleClick() { Serial.println(F(""Button clicked!"")); wifi_manager(); } static void handleDoubleClick() { Serial.println(F(""Button double clicked!"")); } static void handleLongPressStop() { Serial.println(F(""Button pressed for long time and then released!"")); newConfigData(); } void wifi_manager() { Serial.println(F(""\\nConfig Portal requested."")); digitalWrite(LED_BUILTIN, LED_ON); // turn the LED on by making the voltage LOW to tell us we are in configuration mode. //Local intialization. Once its business is done, there is no need to keep it around ESP_WiFiManager ESP_wifiManager(""ConfigOnSwitchFS-MQTT""); //Check if there is stored WiFi router/password credentials. //If not found, device will remain in configuration mode until switched off via webserver. Serial.print(F(""Opening Configuration Portal. "")); Router_SSID = ESP_wifiManager.WiFi_SSID(); Router_Pass = ESP_wifiManager.WiFi_Pass(); // From v1.1.1, Don't permit NULL password if ( !initialConfig && (Router_SSID != """") && (Router_Pass != """") ) { //If valid AP credential and not DRD, set timeout 120s. ESP_wifiManager.setConfigPortalTimeout(120); Serial.println(F(""Got stored Credentials. Timeout 120s"")); } else { ESP_wifiManager.setConfigPortalTimeout(0); Serial.print(F(""No timeout : "")); if (initialConfig) { Serial.println(F(""DRD or No stored Credentials.."")); } else { Serial.println(F(""No stored Credentials."")); } } //Local intialization. Once its business is done, there is no need to keep it around // Extra parameters to be configured // After connecting, parameter.getValue() will get you the configured value // Format: