text,length,is_long_context,metric_val,label_metric "// // Copyright (C) 2013-2016 Alexey Khokholov (Nuke.YKT) // // 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 2 // 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. // // // Nuked OPL3 emulator. // Thanks: // MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): // Feedback and Rhythm part calculation information. // forums.submarine.org.uk(carbon14, opl3): // Tremolo and phase generator calculation information. // OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): // OPL2 ROMs. // // version: 1.7.4 // #include #include #include #include ""opl3.h"" #define RSM_FRAC 10 // Channel types enum { ch_2op = 0, ch_4op = 1, ch_4op2 = 2, ch_drum = 3 }; // Envelope key types enum { egk_norm = 0x01, egk_drum = 0x02 }; // // logsin table // static const Bit16u logsinrom[256] = { 0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471, 0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5, 0x398, 0x37e, 0x365, 0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd, 0x2bd, 0x2af, 0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261, 0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218, 0x20f, 0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd, 0x1c5, 0x1be, 0x1b7, 0x1b0, 0x1a9, 0x1a2, 0x19b, 0x195, 0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166, 0x160, 0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c, 0x137, 0x133, 0x12e, 0x129, 0x125, 0x121, 0x11c, 0x118, 0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8, 0x0f4, 0x0f0, 0x0ec, 0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db, 0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1, 0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9, 0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c, 0x099, 0x097, 0x094, 0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081, 0x07f, 0x07d, 0x07a, 0x078, 0x076, 0x074, 0x072, 0x070, 0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062, 0x060, 0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052, 0x050, 0x04e, 0x04d, 0x04b, 0x04a, 0x048, 0x046, 0x045, 0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039, 0x038, 0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f, 0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028, 0x027, 0x026, 0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e, 0x01d, 0x01c, 0x01b, 0x01a, 0x019, 0x018, 0x017, 0x017, 0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011, 0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c, 0x00b, 0x00a, 0x00a, 0x009, 0x009, 0x008, 0x008, 0x007, 0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004, 0x004, 0x004, 0x003, 0x003, 0x003, 0x002, 0x002, 0x002, 0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000 }; // // exp table // static const Bit16u exprom[256] = { 0x000, 0x003, 0x006, 0x008, 0x00b, 0x00e, 0x011, 0x014, 0x016, 0x019, 0x01c, 0x01f, 0x022, 0x025, 0x028, 0x02a, 0x02d, 0x030, 0x033, 0x036, 0x039, 0x03c, 0x03f, 0x042, 0x045, 0x048, 0x04b, 0x04e, 0x051, 0x054, 0x057, 0x05a, 0x05d, 0x060, 0x063, 0x066, 0x069, 0x06c, 0x06f, 0x072, 0x075, 0x078, 0x07b, 0x07e, 0x082, 0x085, 0x088, 0x08b, 0x08e, 0x091, 0x094, 0x098, 0x09b, 0x09e, 0x0a1, 0x0a4, 0x0a8, 0x0ab, 0x0ae, 0x0b1, 0x0b5, 0x0b8, 0x0bb, 0x0be, 0x0c2, 0x0c5, 0x0c8, 0x0cc, 0x0cf, 0x0d2, 0x0d6, 0x0d9, 0x0dc, 0x0e0, 0x0e3, 0x0e7, 0x0ea, 0x0ed, 0x0f1, 0x0f4, 0x0f8, 0x0fb, 0x0ff, 0x102, 0x106, 0x109, 0x10c, 0x110, 0x114, 0x117, 0x11b, 0x11e, 0x122, 0x125, 0x129, 0x12c, 0x130, 0x134, 0x137, 0x13b, 0x13e, 0x142, 0x146, 0x149, 0x14d, 0x151, 0x154, 0x158, 0x15c, 0x160, 0x163, 0x167, 0x16b, 0x16f, 0x172, 0x176, 0x17a, 0x17e, 0x181, 0x185, 0x189, 0x18d, 0x191, 0x195, 0x199, 0x19c, 0x1a0, 0x1a4, 0x1a8, 0x1ac, 0x1b0, 0x1b4, 0x1b8, 0x1bc, 0x1c0, 0x1c4, 0x1c8, 0x1cc, 0x1d0, 0x1d4, 0x1d8, 0x1dc, 0x1e0, 0x1e4, 0x1e8, 0x1ec, 0x1f0, 0x1f5, 0x1f9, 0x1fd, 0x201, 0x205, 0x209, 0x20e, 0x212, 0x216, 0x21a, 0x21e, 0x223, 0x227, 0x22b, 0x230, 0x234, 0x238, 0x23c, 0x241, 0x245, 0x249, 0x24e, 0x252, 0x257, 0x25b, 0x25f, 0x264, 0x268, 0x26d, 0x271, 0x276, 0x27a, 0x27f, 0x283, 0x288, 0x28c, 0x291, 0x295, 0x29a, 0x29e, 0x2a3, 0x2a8, 0x2ac, 0x2b1, 0x2b5, 0x2ba, 0x2bf, 0x2c4, 0x2c8, 0x2cd, 0x2d2, 0x2d6, 0x2db, 0x2e0, 0x2e5, 0x2e9, 0x2ee, 0x2f3, 0x2f8, 0x2fd, 0x302, 0x306, 0x30b, 0x310, 0x315, 0x31a, 0x31f, 0x324, 0x329, 0x32e, 0x333, 0x338, 0x33d, 0x342, 0x347, 0x34c, 0x351, 0x356, 0x35b, 0x360, 0x365, 0x36a, 0x370, 0x375, 0x37a, 0x37f, 0x384, 0x38a, 0x38f, 0x394, 0x399, 0x39f, 0x3a4, 0x3a9, 0x3ae, 0x3b4, 0x3b9, 0x3bf, 0x3c4, 0x3c9, 0x3cf, 0x3d4, 0x3da, 0x3df, 0x3e4, 0x3ea, 0x3ef, 0x3f5, 0x3fa }; // // freq mult table multiplied by 2 // // 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 12, 15, 15 // static const Bit8u mt[16] = { 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 24, 24, 30, 30 }; // // ksl table // static const Bit8u kslrom[16] = { 0, 32, 40, 45, 48, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64 }; static const Bit8u kslshift[4] = { 8, 1, 2, 0 }; // // envelope generator constants // static const Bit8u eg_incstep[3][4][8] = { { { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 } }, { { 0, 1, 0, 1, 0, 1, 0, 1 }, { 0, 1, 0, 1, 1, 1, 0, 1 }, { 0, 1, 1, 1, 0, 1, 1, 1 }, { 0, 1, 1, 1, 1, 1, 1, 1 } }, { { 1, 1, 1, 1, 1, 1, 1, 1 }, { 2, 2, 1, 1, 1, 1, 1, 1 }, { 2, 2, 1, 1, 2, 2, 1, 1 }, { 2, 2, 2, 2, 2, 2, 1, 1 } } }; static const Bit8u eg_incdesc[16] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2 }; static const Bit8s eg_incsh[16] = { 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, -1, -2 }; // // address decoding // static const Bit8s ad_slot[0x20] = { 0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 10, 11, -1, -1, 12, 13, 14, 15, 16, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static const Bit8u ch_slot[18] = { 0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20, 24, 25, 26, 30, 31, 32 }; // // Envelope generator // typedef Bit16s(*envelope_sinfunc)(Bit16u phase, Bit16u envelope); typedef void(*envelope_genfunc)(opl3_slot *slott); static Bit16s OPL3_EnvelopeCalcExp(Bit32u level) { if (level > 0x1fff) { level = 0x1fff; } return ((exprom[(level & 0xff) ^ 0xff] | 0x400) << 1) >> (level >> 8); } static Bit16s OPL3_EnvelopeCalcSin0(Bit16u phase, Bit16u envelope) { Bit16u out = 0; Bit16u neg = 0; phase &= 0x3ff; if (phase & 0x200) { neg = ~0; } if (phase & 0x100) { out = logsinrom[(phase & 0xff) ^ 0xff]; } else { out = logsinrom[phase & 0xff]; } return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; } static Bit16s OPL3_EnvelopeCalcSin1(Bit16u phase, Bit16u envelope) { Bit16u out = 0; phase &= 0x3ff; if (phase & 0x200) { out = 0x1000; } else if (phase & 0x100) { out = logsinrom[(phase & 0xff) ^ 0xff]; } else { out = logsinrom[phase & 0xff]; } return OPL3_EnvelopeCalcExp(out + (envelope << 3)); } static Bit16s OPL3_EnvelopeCalcSin2(Bit16u phase, Bit16u envelope) { Bit16u out = 0; phase &= 0x3ff; if (phase & 0x100) { out = logsinrom[(phase & 0xff) ^ 0xff]; } else { out = logsinrom[phase & 0xff]; } return OPL3_EnvelopeCalcExp(out + (envelope << 3)); } static Bit16s OPL3_EnvelopeCalcSin3(Bit16u phase, Bit16u envelope) { Bit16u out = 0; phase &= 0x3ff; if (phase & 0x100) { out = 0x1000; } else { out = logsinrom[phase & 0xff]; } return OPL3_EnvelopeCalcExp(out + (envelope << 3)); } static Bit16s OPL3_EnvelopeCalcSin4(Bit16u phase, Bit16u envelope) { Bit16u out = 0; Bit16u neg = 0; phase &= 0x3ff; if ((phase & 0x300) == 0x100) { neg = ~0; } if (phase & 0x200) { out = 0x1000; } else if (phase & 0x80) { out = logsinrom[((phase ^ 0xff) << 1) & 0xff]; } else { out = logsinrom[(phase << 1) & 0xff]; } return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; } static Bit16s OPL3_EnvelopeCalcSin5(Bit16u phase, Bit16u envelope) { Bit16u out = 0; phase &= 0x3ff; if (phase & 0x200) { out = 0x1000; } else if (phase & 0x80) { out = logsinrom[((phase ^ 0xff) << 1) & 0xff]; } else { out = logsinrom[(phase << 1) & 0xff]; } return OPL3_EnvelopeCalcExp(out + (envelope << 3)); } static Bit16s OPL3_EnvelopeCalcSin6(Bit16u phase, Bit16u envelope) { Bit16u neg = 0; phase &= 0x3ff; if (phase & 0x200) { neg = ~0; } return OPL3_EnvelopeCalcExp(envelope << 3) ^ neg; } static Bit16s OPL3_EnvelopeCalcSin7(Bit16u phase, Bit16u envelope) { Bit16u out = 0; Bit16u neg = 0; phase &= 0x3ff; if (phase & 0x200) { neg = ~0; phase = (phase & 0x1ff) ^ 0x1ff; } out = phase << 3; return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; } static const envelope_sinfunc envelope_sin[8] = { OPL3_EnvelopeCalcSin0, OPL3_EnvelopeCalcSin1, OPL3_EnvelopeCalcSin2, OPL3_EnvelopeCalcSin3, OPL3_EnvelopeCalcSin4, OPL3_EnvelopeCalcSin5, OPL3_EnvelopeCalcSin6, OPL3_EnvelopeCalcSin7 }; static void OPL3_EnvelopeGenOff(opl3_slot *slot); static void OPL3_EnvelopeGenAttack(opl3_slot *slot); static void OPL3_EnvelopeGenDecay(opl3_slot *slot); static void OPL3_EnvelopeGenSustain(opl3_slot *slot); static void OPL3_EnvelopeGenRelease(opl3_slot *slot); envelope_genfunc envelope_gen[5] = { OPL3_EnvelopeGenOff, OPL3_EnvelopeGenAttack, OPL3_EnvelopeGenDecay, OPL3_EnvelopeGenSustain, OPL3_EnvelopeGenRelease }; enum envelope_gen_num { envelope_gen_num_off = 0, envelope_gen_num_attack = 1, envelope_gen_num_decay = 2, envelope_gen_num_sustain = 3, envelope_gen_num_release = 4 }; static Bit8u OPL3_EnvelopeCalcRate(opl3_slot *slot, Bit8u reg_rate) { Bit8u rate; if (reg_rate == 0x00) { return 0x00; } rate = (reg_rate << 2) + (slot->reg_ksr ? slot->channel->ksv : (slot->channel->ksv >> 2)); if (rate > 0x3c) { rate = 0x3c; } return rate; } static void OPL3_EnvelopeUpdateKSL(opl3_slot *slot) { Bit16s ksl = (kslrom[slot->channel->f_num >> 6] << 2) - ((0x08 - slot->channel->block) << 5); if (ksl < 0) { ksl = 0; } slot->eg_ksl = (Bit8u)ksl; } static void OPL3_EnvelopeUpdateRate(opl3_slot *slot) { switch (slot->eg_gen) { case envelope_gen_num_off: case envelope_gen_num_attack: slot->eg_rate = OPL3_EnvelopeCalcRate(slot, slot->reg_ar); break; case envelope_gen_num_decay: slot->eg_rate = OPL3_EnvelopeCalcRate(slot, slot->reg_dr); break; case envelope_gen_num_sustain: case envelope_gen_num_release: slot->eg_rate = OPL3_EnvelopeCalcRate(slot, slot->reg_rr); break; } } static void OPL3_EnvelopeGenOff(opl3_slot *slot) { slot->eg_rout = 0x1ff; } static void OPL3_EnvelopeGenAttack(opl3_slot *slot) { if (slot->eg_rout == 0x00) { slot->eg_gen = envelope_gen_num_decay; OPL3_EnvelopeUpdateRate(slot); return; } slot->eg_rout += ((~slot->eg_rout) * slot->eg_inc) >> 3; if (slot->eg_rout < 0x00) { slot->eg_rout = 0x00; } } static void OPL3_EnvelopeGenDecay(opl3_slot *slot) { if (slot->eg_rout >= slot->reg_sl << 4) { slot->eg_gen = envelope_gen_num_sustain; OPL3_EnvelopeUpdateRate(slot); return; } slot->eg_rout += slot->eg_inc; } static void OPL3_EnvelopeGenSustain(opl3_slot *slot) { if (!slot->reg_type) { OPL3_EnvelopeGenRelease(slot); } } static void OPL3_EnvelopeGenRelease(opl3_slot *slot) { if (slot->eg_rout >= 0x1ff) { slot->eg_gen = envelope_gen_num_off; slot->eg_rout = 0x1ff; OPL3_EnvelopeUpdateRate(slot); return; } slot->eg_rout += slot->eg_inc; } static void OPL3_EnvelopeCalc(opl3_slot *slot) { Bit8u rate_h, rate_l; Bit8u inc = 0; rate_h = slot->eg_rate >> 2; rate_l = slot->eg_rate & 3; if (eg_incsh[rate_h] > 0) { if ((slot->chip->timer & ((1 << eg_incsh[rate_h]) - 1)) == 0) { inc = eg_incstep[eg_incdesc[rate_h]][rate_l] [((slot->chip->timer) >> eg_incsh[rate_h]) & 0x07]; } } else { inc = eg_incstep[eg_incdesc[rate_h]][rate_l] [slot->chip->timer & 0x07] << (-eg_incsh[rate_h]); } slot->eg_inc = inc; slot->eg_out = slot->eg_rout + (slot->reg_tl << 2) + (slot->eg_ksl >> kslshift[slot->reg_ksl]) + *slot->trem; envelope_gen[slot->eg_gen](slot); } static void OPL3_EnvelopeKeyOn(opl3_slot *slot, Bit8u type) { if (!slot->key) { slot->eg_gen = envelope_gen_num_attack; OPL3_EnvelopeUpdateRate(slot); if ((slot->eg_rate >> 2) == 0x0f) { slot->eg_gen = envelope_gen_num_decay; OPL3_EnvelopeUpdateRate(slot); slot->eg_rout = 0x00; } slot->pg_phase = 0x00; } slot->key |= type; } static void OPL3_EnvelopeKeyOff(opl3_slot *slot, Bit8u type) { if (slot->key) { slot->key &= (~type); if (!slot->key) { slot->eg_gen = envelope_gen_num_release; OPL3_EnvelopeUpdateRate(slot); } } } // // Phase Generator // static void OPL3_PhaseGenerate(opl3_slot *slot) { Bit16u f_num; Bit32u basefreq; f_num = slot->channel->f_num; if (slot->reg_vib) { Bit8s range; Bit8u vibpos; range = (f_num >> 7) & 7; vibpos = slot->chip->vibpos; if (!(vibpos & 3)) { range = 0; } else if (vibpos & 1) { range >>= 1; } range >>= slot->chip->vibshift; if (vibpos & 4) { range = -range; } f_num += range; } basefreq = (f_num << slot->channel->block) >> 1; slot->pg_phase += (basefreq * mt[slot->reg_mult]) >> 1; } // // Noise Generator // static void OPL3_NoiseGenerate(opl3_chip *chip) { if (chip->noise & 0x01) { chip->noise ^= 0x800302; } chip->noise >>= 1; } // // Slot // static void OPL3_SlotWrite20(opl3_slot *slot, Bit8u data) { if ((data >> 7) & 0x01) { slot->trem = &slot->chip->tremolo; } else { slot->trem = (Bit8u*)&slot->chip->zeromod; } slot->reg_vib = (data >> 6) & 0x01; slot->reg_type = (data >> 5) & 0x01; slot->reg_ksr = (data >> 4) & 0x01; slot->reg_mult = data & 0x0f; OPL3_EnvelopeUpdateRate(slot); } static void OPL3_SlotWrite40(opl3_slot *slot, Bit8u data) { slot->reg_ksl = (data >> 6) & 0x03; slot->reg_tl = data & 0x3f; OPL3_EnvelopeUpdateKSL(slot); } static void OPL3_SlotWrite60(opl3_slot *slot, Bit8u data) { slot->reg_ar = (data >> 4) & 0x0f; slot->reg_dr = data & 0x0f; OPL3_EnvelopeUpdateRate(slot); } static void OPL3_SlotWrite80(opl3_slot *slot, Bit8u data) { slot->reg_sl = (data >> 4) & 0x0f; if (slot->reg_sl == 0x0f) { slot->reg_sl = 0x1f; } slot->reg_rr = data & 0x0f; OPL3_EnvelopeUpdateRate(slot); } static void OPL3_SlotWriteE0(opl3_slot *slot, Bit8u data) { slot->reg_wf = data & 0x07; if (slot->chip->newm == 0x00) { slot->reg_wf &= 0x03; } } static void OPL3_SlotGeneratePhase(opl3_slot *slot, Bit16u phase) { slot->out = envelope_sin[slot->reg_wf](phase, slot->eg_out); } static void OPL3_SlotGenerate(opl3_slot *slot) { OPL3_SlotGeneratePhase(slot, (Bit16u)(slot->pg_phase >> 9) + *slot->mod); } static void OPL3_SlotGenerateZM(opl3_slot *slot) { OPL3_SlotGeneratePhase(slot, (Bit16u)(slot->pg_phase >> 9)); } static void OPL3_SlotCalcFB(opl3_slot *slot) { if (slot->channel->fb != 0x00) { slot->fbmod = (slot->prout + slot->out) >> (0x09 - slot->channel->fb); } else { slot->fbmod = 0; } slot->prout = slot->out; } // // Channel // static void OPL3_ChannelSetupAlg(opl3_channel *channel); static void OPL3_ChannelUpdateRhythm(opl3_chip *chip, Bit8u data) { opl3_channel *channel6; opl3_channel *channel7; opl3_channel *channel8; Bit8u chnum; chip->rhy = data & 0x3f; if (chip->rhy & 0x20) { channel6 = &chip->channel[6]; channel7 = &chip->channel[7]; channel8 = &chip->channel[8]; channel6->out[0] = &channel6->slots[1]->out; channel6->out[1] = &channel6->slots[1]->out; channel6->out[2] = &chip->zeromod; channel6->out[3] = &chip->zeromod; channel7->out[0] = &channel7->slots[0]->out; channel7->out[1] = &channel7->slots[0]->out; channel7->out[2] = &channel7->slots[1]->out; channel7->out[3] = &channel7->slots[1]->out; channel8->out[0] = &channel8->slots[0]->out; channel8->out[1] = &channel8->slots[0]->out; channel8->out[2] = &channel8->slots[1]->out; channel8->out[3] = &channel8->slots[1]->out; for (chnum = 6; chnum < 9; chnum++) { chip->channel[chnum].chtype = ch_drum; } OPL3_ChannelSetupAlg(channel6); //hh if (chip->rhy & 0x01) { OPL3_EnvelopeKeyOn(channel7->slots[0], egk_drum); } else { OPL3_EnvelopeKeyOff(channel7->slots[0], egk_drum); } //tc if (chip->rhy & 0x02) { OPL3_EnvelopeKeyOn(channel8->slots[1], egk_drum); } else { OPL3_EnvelopeKeyOff(channel8->slots[1], egk_drum); } //tom if (chip->rhy & 0x04) { OPL3_EnvelopeKeyOn(channel8->slots[0], egk_drum); } else { OPL3_EnvelopeKeyOff(channel8->slots[0], egk_drum); } //sd if (chip->rhy & 0x08) { OPL3_EnvelopeKeyOn(channel7->slots[1], egk_drum); } else { OPL3_EnvelopeKeyOff(channel7->slots[1], egk_drum); } //bd if (chip->rhy & 0x10) { OPL3_EnvelopeKeyOn(channel6->slots[0], egk_drum); OPL3_EnvelopeKeyOn(channel6->slots[1], egk_drum); } else { OPL3_EnvelopeKeyOff(channel6->slots[0], egk_drum); OPL3_EnvelopeKeyOff(channel6->slots[1], egk_drum); } } else { for (chnum = 6; chnum < 9; chnum++) { chip->channel[chnum].chtype = ch_2op; OPL3_ChannelSetupAlg(&chip->channel[chnum]); OPL3_EnvelopeKeyOff(chip->channel[chnum].slots[0], egk_drum); OPL3_EnvelopeKeyOff(chip->channel[chnum].slots[1], egk_drum); } } } static void OPL3_ChannelWriteA0(opl3_channel *channel, Bit8u data) { if (channel->chip->newm && channel->chtype == ch_4op2) { return; } channel->f_num = (channel->f_num & 0x300) | data; channel->ksv = (channel->block << 1) | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01); OPL3_EnvelopeUpdateKSL(channel->slots[0]); OPL3_EnvelopeUpdateKSL(channel->slots[1]); OPL3_EnvelopeUpdateRate(channel->slots[0]); OPL3_EnvelopeUpdateRate(channel->slots[1]); if (channel->chip->newm && channel->chtype == ch_4op) { channel->pair->f_num = channel->f_num; channel->pair->ksv = channel->ksv; OPL3_EnvelopeUpdateKSL(channel->pair->slots[0]); OPL3_EnvelopeUpdateKSL(channel->pair->slots[1]); OPL3_EnvelopeUpdateRate(channel->pair->slots[0]); OPL3_EnvelopeUpdateRate(channel->pair->slots[1]); } } static void OPL3_ChannelWriteB0(opl3_channel *channel, Bit8u data) { if (channel->chip->newm && channel->chtype == ch_4op2) { return; } channel->f_num = (channel->f_num & 0xff) | ((data & 0x03) << 8); channel->block = (data >> 2) & 0x07; channel->ksv = (channel->block << 1) | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01); OPL3_EnvelopeUpdateKSL(channel->slots[0]); OPL3_EnvelopeUpdateKSL(channel->slots[1]); OPL3_EnvelopeUpdateRate(channel->slots[0]); OPL3_EnvelopeUpdateRate(channel->slots[1]); if (channel->chip->newm && channel->chtype == ch_4op) { channel->pair->f_num = channel->f_num; channel->pair->block = channel->block; channel->pair->ksv = channel->ksv; OPL3_EnvelopeUpdateKSL(channel->pair->slots[0]); OPL3_EnvelopeUpdateKSL(channel->pair->slots[1]); OPL3_EnvelopeUpdateRate(channel->pair->slots[0]); OPL3_EnvelopeUpdateRate(channel->pair->slots[1]); } } static void OPL3_ChannelSetupAlg(opl3_channel *channel) { if (channel->chtype == ch_drum) { switch (channel->alg & 0x01) { case 0x00: channel->slots[0]->mod = &channel->slots[0]->fbmod; channel->slots[1]->mod = &channel->slots[0]->out; break; case 0x01: channel->slots[0]->mod = &channel->slots[0]->fbmod; channel->slots[1]->mod = &channel->chip->zeromod; break; } return; } if (channel->alg & 0x08) { return; } if (channel->alg & 0x04) { channel->pair->out[0] = &channel->chip->zeromod; channel->pair->out[1] = &channel->chip->zeromod; channel->pair->out[2] = &channel->chip->zeromod; channel->pair->out[3] = &channel->chip->zeromod; switch (channel->alg & 0x03) { case 0x00: channel->pair->slots[0]->mod = &channel->pair->slots[0]->fbmod; channel->pair->slots[1]->mod = &channel->pair->slots[0]->out; channel->slots[0]->mod = &channel->pair->slots[1]->out; channel->slots[1]->mod = &channel->slots[0]->out; channel->out[0] = &channel->slots[1]->out; channel->out[1] = &channel->chip->zeromod; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; case 0x01: channel->pair->slots[0]->mod = &channel->pair->slots[0]->fbmod; channel->pair->slots[1]->mod = &channel->pair->slots[0]->out; channel->slots[0]->mod = &channel->chip->zeromod; channel->slots[1]->mod = &channel->slots[0]->out; channel->out[0] = &channel->pair->slots[1]->out; channel->out[1] = &channel->slots[1]->out; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; case 0x02: channel->pair->slots[0]->mod = &channel->pair->slots[0]->fbmod; channel->pair->slots[1]->mod = &channel->chip->zeromod; channel->slots[0]->mod = &channel->pair->slots[1]->out; channel->slots[1]->mod = &channel->slots[0]->out; channel->out[0] = &channel->pair->slots[0]->out; channel->out[1] = &channel->slots[1]->out; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; case 0x03: channel->pair->slots[0]->mod = &channel->pair->slots[0]->fbmod; channel->pair->slots[1]->mod = &channel->chip->zeromod; channel->slots[0]->mod = &channel->pair->slots[1]->out; channel->slots[1]->mod = &channel->chip->zeromod; channel->out[0] = &channel->pair->slots[0]->out; channel->out[1] = &channel->slots[0]->out; channel->out[2] = &channel->slots[1]->out; channel->out[3] = &channel->chip->zeromod; break; } } else { switch (channel->alg & 0x01) { case 0x00: channel->slots[0]->mod = &channel->slots[0]->fbmod; channel->slots[1]->mod = &channel->slots[0]->out; channel->out[0] = &channel->slots[1]->out; channel->out[1] = &channel->chip->zeromod; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; case 0x01: channel->slots[0]->mod = &channel->slots[0]->fbmod; channel->slots[1]->mod = &channel->chip->zeromod; channel->out[0] = &channel->slots[0]->out; channel->out[1] = &channel->slots[1]->out; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; } } } static void OPL3_ChannelWriteC0(opl3_channel *channel, Bit8u data) { channel->fb = (data & 0x0e) >> 1; channel->con = data & 0x01; channel->alg = channel->con; if (channel->chip->newm) { if (channel->chtype == ch_4op) { channel->pair->alg = 0x04 | (channel->con << 1) | (channel->pair->con); channel->alg = 0x08; OPL3_ChannelSetupAlg(channel->pair); } else if (channel->chtype == ch_4op2) { channel->alg = 0x04 | (channel->pair->con << 1) | (channel->con); channel->pair->alg = 0x08; OPL3_ChannelSetupAlg(channel); } else { OPL3_ChannelSetupAlg(channel); } } else { OPL3_ChannelSetupAlg(channel); } if (channel->chip->newm) { channel->cha = ((data >> 4) & 0x01) ? ~0 : 0; channel->chb = ((data >> 5) & 0x01) ? ~0 : 0; } else { channel->cha = channel->chb = ~0; } } static void OPL3_ChannelKeyOn(opl3_channel *channel) { if (channel->chip->newm) { if (channel->chtype == ch_4op) { OPL3_EnvelopeKeyOn(channel->slots[0], egk_norm); OPL3_EnvelopeKeyOn(channel->slots[1], egk_norm); OPL3_EnvelopeKeyOn(channel->pair->slots[0], egk_norm); OPL3_EnvelopeKeyOn(channel->pair->slots[1], egk_norm); } else if (channel->chtype == ch_2op || channel->chtype == ch_drum) { OPL3_EnvelopeKeyOn(channel->slots[0], egk_norm); OPL3_EnvelopeKeyOn(channel->slots[1], egk_norm); } } else { OPL3_EnvelopeKeyOn(channel->slots[0], egk_norm); OPL3_EnvelopeKeyOn(channel->slots[1], egk_norm); } } static void OPL3_ChannelKeyOff(opl3_channel *channel) { if (channel->chip->newm) { if (channel->chtype == ch_4op) { OPL3_EnvelopeKeyOff(channel->slots[0], egk_norm); OPL3_EnvelopeKeyOff(channel->slots[1], egk_norm); OPL3_EnvelopeKeyOff(channel->pair->slots[0], egk_norm); OPL3_EnvelopeKeyOff(channel->pair->slots[1], egk_norm); } else if (channel->chtype == ch_2op || channel->chtype == ch_drum) { OPL3_EnvelopeKeyOff(channel->slots[0], egk_norm); OPL3_EnvelopeKeyOff(channel->slots[1], egk_norm); } } else { OPL3_EnvelopeKeyOff(channel->slots[0], egk_norm); OPL3_EnvelopeKeyOff(channel->slots[1], egk_norm); } } static void OPL3_ChannelSet4Op(opl3_chip *chip, Bit8u data) { Bit8u bit; Bit8u chnum; for (bit = 0; bit < 6; bit++) { chnum = bit; if (bit >= 3) { chnum += 9 - 3; } if ((data >> bit) & 0x01) { chip->channel[chnum].chtype = ch_4op; chip->channel[chnum + 3].chtype = ch_4op2; } else { chip->channel[chnum].chtype = ch_2op; chip->channel[chnum + 3].chtype = ch_2op; } } } static Bit16s OPL3_ClipSample(Bit32s sample) { if (sample > 32767) { sample = 32767; } else if (sample < -32768) { sample = -32768; } return (Bit16s)sample; } static void OPL3_GenerateRhythm1(opl3_chip *chip) { opl3_channel *channel6; opl3_channel *channel7; opl3_channel *channel8; Bit16u phase14; Bit16u phase17; Bit16u phase; Bit16u phasebit; channel6 = &chip->channel[6]; channel7 = &chip->channel[7]; channel8 = &chip->channel[8]; OPL3_SlotGenerate(channel6->slots[0]); phase14 = (channel7->slots[0]->pg_phase >> 9) & 0x3ff; phase17 = (channel8->slots[1]->pg_phase >> 9) & 0x3ff; phase = 0x00; //hh tc phase bit phasebit = ((phase14 & 0x08) | (((phase14 >> 5) ^ phase14) & 0x04) | (((phase17 >> 2) ^ phase17) & 0x08)) ? 0x01 : 0x00; //hh phase = (phasebit << 9) | (0x34 << ((phasebit ^ (chip->noise & 0x01)) << 1)); OPL3_SlotGeneratePhase(channel7->slots[0], phase); //tt OPL3_SlotGenerateZM(channel8->slots[0]); } static void OPL3_GenerateRhythm2(opl3_chip *chip) { opl3_channel *channel6; opl3_channel *channel7; opl3_channel *channel8; Bit16u phase14; Bit16u phase17; Bit16u phase; Bit16u phasebit; channel6 = &chip->channel[6]; channel7 = &chip->channel[7]; channel8 = &chip->channel[8]; OPL3_SlotGenerate(channel6->slots[1]); phase14 = (channel7->slots[0]->pg_phase >> 9) & 0x3ff; phase17 = (channel8->slots[1]->pg_phase >> 9) & 0x3ff; phase = 0x00; //hh tc phase bit phasebit = ((phase14 & 0x08) | (((phase14 >> 5) ^ phase14) & 0x04) | (((phase17 >> 2) ^ phase17) & 0x08)) ? 0x01 : 0x00; //sd phase = (0x100 << ((phase14 >> 8) & 0x01)) ^ ((chip->noise & 0x01) << 8); OPL3_SlotGeneratePhase(channel7->slots[1], phase); //tc phase = 0x100 | (phasebit << 9); OPL3_SlotGeneratePhase(channel8->slots[1], phase); } void OPL3_Generate(opl3_chip *chip, Bit16s *buf) { Bit8u ii; Bit8u jj; Bit16s accm; buf[1] = OPL3_ClipSample(chip->mixbuff[1]); for (ii = 0; ii < 12; ii++) { OPL3_SlotCalcFB(&chip->slot[ii]); OPL3_PhaseGenerate(&chip->slot[ii]); OPL3_EnvelopeCalc(&chip->slot[ii]); OPL3_SlotGenerate(&chip->slot[ii]); } for (ii = 12; ii < 15; ii++) { OPL3_SlotCalcFB(&chip->slot[ii]); OPL3_PhaseGenerate(&chip->slot[ii]); OPL3_EnvelopeCalc(&chip->slot[ii]); } if (chip->rhy & 0x20) { OPL3_GenerateRhythm1(chip); } else { OPL3_SlotGenerate(&chip->slot[12]); OPL3_SlotGenerate(&chip->slot[13]); OPL3_SlotGenerate(&chip->slot[14]); } chip->mixbuff[0] = 0; for (ii = 0; ii < 18; ii++) { accm = 0; for (jj = 0; jj < 4; jj++) { accm += *chip->channel[ii].out[jj]; } chip->mixbuff[0] += (Bit16s)(accm & chip->channel[ii].cha); } for (ii = 15; ii < 18; ii++) { OPL3_SlotCalcFB(&chip->slot[ii]); OPL3_PhaseGenerate(&chip->slot[ii]); OPL3_EnvelopeCalc(&chip->slot[ii]); } if (chip->rhy & 0x20) { OPL3_GenerateRhythm2(chip); } else { OPL3_SlotGenerate(&chip->slot[15]); OPL3_SlotGenerate(&chip->slot[16]); OPL3_SlotGenerate(&chip->slot[17]); } buf[0] = OPL3_ClipSample(chip->mixbuff[0]); for (ii = 18; ii < 33; ii++) { OPL3_SlotCalcFB(&chip->slot[ii]); OPL3_PhaseGenerate(&chip->slot[ii]); OPL3_EnvelopeCalc(&chip->slot[ii]); OPL3_SlotGenerate(&chip->slot[ii]); } chip->mixbuff[1] = 0; for (ii = 0; ii < 18; ii++) { accm = 0; for (jj = 0; jj < 4; jj++) { accm += *chip->channel[ii].out[jj]; } chip->mixbuff[1] += (Bit16s)(accm & chip->channel[ii].chb); } for (ii = 33; ii < 36; ii++) { OPL3_SlotCalcFB(&chip->slot[ii]); OPL3_PhaseGenerate(&chip->slot[ii]); OPL3_EnvelopeCalc(&chip->slot[ii]); OPL3_SlotGenerate(&chip->slot[ii]); } OPL3_NoiseGenerate(chip); if ((chip->timer & 0x3f) == 0x3f) { chip->tremolopos = (chip->tremolopos + 1) % 210; } if (chip->tremolopos < 105) { chip->tremolo = chip->tremolopos >> chip->tremoloshift; } else { chip->tremolo = (210 - chip->tremolopos) >> chip->tremoloshift; } if ((chip->timer & 0x3ff) == 0x3ff) { chip->vibpos = (chip->vibpos + 1) & 7; } chip->timer++; while (chip->writebuf[chip->writebuf_cur].time <= chip->writebuf_samplecnt) { if (!(chip->writebuf[chip->writebuf_cur].reg & 0x200)) { break; } chip->writebuf[chip->writebuf_cur].reg &= 0x1ff; OPL3_WriteReg(chip, chip->writebuf[chip->writebuf_cur].reg, chip->writebuf[chip->writebuf_cur].data); chip->writebuf_cur = (chip->writebuf_cur + 1) % OPL_WRITEBUF_SIZE; } chip->writebuf_samplecnt++; } void OPL3_GenerateResampled(opl3_chip *chip, Bit16s *buf) { while (chip->samplecnt >= chip->rateratio) { chip->oldsamples[0] = chip->samples[0]; chip->oldsamples[1] = chip->samples[1]; OPL3_Generate(chip, chip->samples); chip->samplecnt -= chip->rateratio; } buf[0] = (Bit16s)((chip->oldsamples[0] * (chip->rateratio - chip->samplecnt) + chip->samples[0] * chip->samplecnt) / chip->rateratio); buf[1] = (Bit16s)((chip->oldsamples[1] * (chip->rateratio - chip->samplecnt) + chip->samples[1] * chip->samplecnt) / chip->rateratio); chip->samplecnt += 1 << RSM_FRAC; } void OPL3_Reset(opl3_chip *chip, Bit32u samplerate) { Bit8u slotnum; Bit8u channum; //memset(chip, 0, sizeof(opl3_chip)); for (slotnum = 0; slotnum < 36; slotnum++) { chip->slot[slotnum].chip = chip; chip->slot[slotnum].mod = &chip->zeromod; chip->slot[slotnum].eg_rout = 0x1ff; chip->slot[slotnum].eg_out = 0x1ff; chip->slot[slotnum].eg_gen = envelope_gen_num_off; chip->slot[slotnum].trem = (Bit8u*)&chip->zeromod; } for (channum = 0; channum < 18; channum++) { chip->channel[channum].slots[0] = &chip->slot[ch_slot[channum]]; chip->channel[channum].slots[1] = &chip->slot[ch_slot[channum] + 3]; chip->slot[ch_slot[channum]].channel = &chip->channel[channum]; chip->slot[ch_slot[channum] + 3].channel = &chip->channel[channum]; if ((channum % 9) < 3) { chip->channel[channum].pair = &chip->channel[channum + 3]; } else if ((channum % 9) < 6) { chip->channel[channum].pair = &chip->channel[channum - 3]; } chip->channel[channum].chip = chip; chip->channel[channum].out[0] = &chip->zeromod; chip->channel[channum].out[1] = &chip->zeromod; chip->channel[channum].out[2] = &chip->zeromod; chip->channel[channum].out[3] = &chip->zeromod; chip->channel[channum].chtype = ch_2op; chip->channel[channum].cha = ~0; chip->channel[channum].chb = ~0; OPL3_ChannelSetupAlg(&chip->channel[channum]); } chip->noise = 0x306600; chip->rateratio = (samplerate << RSM_FRAC) / 49716; chip->tremoloshift = 4; chip->vibshift = 1; } void OPL3_WriteReg(opl3_chip *chip, Bit16u reg, Bit8u v) { Bit8u high = (reg >> 8) & 0x01; Bit8u regm = reg & 0xff; switch (regm & 0xf0) { case 0x00: if (high) { switch (regm & 0x0f) { case 0x04: OPL3_ChannelSet4Op(chip, v); break; case 0x05: chip->newm = v & 0x01; break; } } else { switch (regm & 0x0f) { case 0x08: chip->nts = (v >> 6) & 0x01; break; } } break; case 0x20: case 0x30: if (ad_slot[regm & 0x1f] >= 0) { OPL3_SlotWrite20(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); } break; case 0x40: case 0x50: if (ad_slot[regm & 0x1f] >= 0) { OPL3_SlotWrite40(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); } break; case 0x60: case 0x70: if (ad_slot[regm & 0x1f] >= 0) { OPL3_SlotWrite60(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); } break; case 0x80: case 0x90: if (ad_slot[regm & 0x1f] >= 0) { OPL3_SlotWrite80(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); } break; case 0xe0: case 0xf0: if (ad_slot[regm & 0x1f] >= 0) { OPL3_SlotWriteE0(&chip->slot[18 * high + ad_slot[regm & 0x1f]], v); } break; case 0xa0: if ((regm & 0x0f) < 9) { OPL3_ChannelWriteA0(&chip->channel[9 * high + (regm & 0x0f)], v); } break; case 0xb0: if (regm == 0xbd && !high) { chip->tremoloshift = (((v >> 7) ^ 1) << 1) + 2; chip->vibshift = ((v >> 6) & 0x01) ^ 1; OPL3_ChannelUpdateRhythm(chip, v); } else if ((regm & 0x0f) < 9) { OPL3_ChannelWriteB0(&chip->channel[9 * high + (regm & 0x0f)], v); if (v & 0x20) { OPL3_ChannelKeyOn(&chip->channel[9 * high + (regm & 0x0f)]); } else { OPL3_ChannelKeyOff(&chip->channel[9 * high + (regm & 0x0f)]); } } break; case 0xc0: if ((regm & 0x0f) < 9) { OPL3_ChannelWriteC0(&chip->channel[9 * high + (regm & 0x0f)], v); } break; } } void OPL3_WriteRegBuffered(opl3_chip *chip, Bit16u reg, Bit8u v) { Bit64u time1, time2; if (chip->writebuf[chip->writebuf_last].reg & 0x200) { OPL3_WriteReg(chip, chip->writebuf[chip->writebuf_last].reg & 0x1ff, chip->writebuf[chip->writebuf_last].data); chip->writebuf_cur = (chip->writebuf_last + 1) % OPL_WRITEBUF_SIZE; chip->writebuf_samplecnt = chip->writebuf[chip->writebuf_last].time; } chip->writebuf[chip->writebuf_last].reg = reg | 0x200; chip->writebuf[chip->writebuf_last].data = v; time1 = chip->writebuf_lasttime + OPL_WRITEBUF_DELAY; time2 = chip->writebuf_samplecnt; if (time1 < time2) { time1 = time2; } chip->writebuf[chip->writebuf_last].time = time1; chip->writebuf_lasttime = time1; chip->writebuf_last = (chip->writebuf_last + 1) % OPL_WRITEBUF_SIZE; } void OPL3_GenerateStream(opl3_chip *chip, Bit16s *sndptr, Bit32u numsamples) { Bit32u i; for (i = 0; i < numsamples; i++) { OPL3_GenerateResampled(chip, sndptr); sndptr += 2; } } ",16165,False,2319.2617550539294,median " [[springSpringBoot]] === Spring Boot Spring Boot is an application framework which, according to link:$$http://projects.spring.io/spring-boot/$$[its website], _makes it easy to create stand-alone, production-grade Spring based Applications that you can ""just run"". It takes an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration_. For more information on Spring Boot, see link:$$http://projects.spring.io/spring-boot/$$[http://projects.spring.io/spring-boot/] The Spring Boot - Flowable integration has been developed together with Spring committers. ==== Compatibility Flowable supports both Spring Boot 2.0 and 1.5 with the same starters. The base support is for Spring Boot 2.0, which means that the actuator endpoints are only supported on 2.0. The Flowable starters are also puling spring boot starter transitively, which means that users will have to define the 1.5 version of the spring boot starters in their own build files. [[springSpringBootGettingStarted]] ==== Getting started Spring Boot is all about convention over configuration. To get started, you would need to create a Spring Boot project. The easiest way to do this would be to create a project via link:$$https://start.spring.io/$$[start.spring.io]. For example create a project with web and h2 dependencies. Then in the created project simply add the _flowable-spring-boot-starter_ or _flowable-spring-boot-starter-rest_ dependency. In case you don't need all the engines see the other <>. For example for Maven: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter ${flowable.version} ---- That's all that's needed. This dependency will transitively add the correct Flowable dependencies to the classpath. You can now run your Spring Boot application: [source,java,,linenums] ---- import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ---- You will see an output like this: ---- . ____ _ __ _ _ /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\ ( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\ \\\\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.0.RELEASE) MyApplication : Starting MyApplication on ... MyApplication : No active profile set, falling back to default profiles: default ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4fdfa676: startup date [Wed Mar 28 12:04:00 CEST 2018]; root of context hierarchy o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) o.apache.catalina.core.StandardService : Starting service [Tomcat] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28 o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3085 ms o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable IDM Rest API mapped to [/idm-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable Form Rest API mapped to [/form-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable DMN Rest API mapped to [/dmn-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable Content Rest API mapped to [/content-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable CMMN Rest API mapped to [/cmmn-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable BPMN Rest API mapped to [/process-api/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] uration$$EnhancerBySpringCGLIB$$3d0c70ac : No deployment resources were found for autodeployment uration$$EnhancerBySpringCGLIB$$8131eb1a : No deployment resources were found for autodeployment o.f.e.i.c.ProcessEngineConfigurationImpl : Found 5 Engine Configurators in total: o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) .d.AbstractSqlScriptBasedDbSchemaManager : performing create on identity with resource org/flowable/idm/db/create/flowable.h2.create.identity.sql o.f.idm.engine.impl.IdmEngineImpl : IdmEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.dmn.engine.impl.DmnEngineImpl : DmnEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.form.engine.impl.FormEngineImpl : FormEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.c.engine.ContentEngineConfiguration : Content file system root : ... o.f.c.engine.impl.ContentEngineImpl : ContentEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) o.f.cmmn.engine.CmmnEngineConfiguration : Found 1 Engine Configurators in total: o.f.cmmn.engine.CmmnEngineConfiguration : class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.cmmn.engine.CmmnEngineConfiguration : Executing beforeInit() of class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.cmmn.engine.CmmnEngineConfiguration : Executing configure() of class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.idm.engine.impl.IdmEngineImpl : IdmEngine default created o.f.cmmn.engine.impl.CmmnEngineImpl : CmmnEngine default created o.f.engine.impl.ProcessEngineImpl : ProcessEngine default created o.f.j.s.i.a.AbstractAsyncExecutor : Starting up the async job executor [org.flowable.spring.job.service.SpringAsyncExecutor]. o.f.j.s.i.a.AcquireAsyncJobsDueRunnable : starting to acquire async jobs due o.f.j.s.i.a.AcquireTimerJobsRunnable : starting to acquire async jobs due o.f.j.s.i.a.ResetExpiredJobsRunnable : starting to reset expired jobs o.f.e.impl.cmd.ValidateV5EntitiesCmd : Total of v5 deployments found: 0 s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4fdfa676: startup date [Wed Mar 28 12:04:00 CEST 2018]; root of context hierarchy s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped ""{[/error]}"" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped ""{[/error],produces=[text/html]}"" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -20 o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 20 o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' flowable.Application : Started Application in 18.235 seconds (JVM running for 19.661) ---- So, by just adding the dependency to the classpath and using the _@SpringBootAplication_ annotation a lot has happened behind the scenes: * An in-memory datasource is created automatically (because the H2 driver is on the classpath) and passed to the Flowable process engine configuration * A Flowable ProcessEngine, CmmnEngine, DmnEngine, FormEngine, ContentEngine and IdmEngine beans have been created and exposed * All the Flowable services are exposed as Spring beans * The Spring Job Executor is created Also: * Any BPMN 2.0 process definitions in the _processes_ folder will be automatically deployed. Create a folder _processes_ and add a dummy process definition (named _one-task-process.bpmn20.xml_) to this folder. The content of this file is shown below. * Any CMMN 1.1 case definitions in the _cases_ folder will be automatically deployed. * Any DMN 1.1 dmn definitions in the _dmn_ folder will be automatically deployed. * Any Form definitions in the _forms_ folder will be automatically deployed. The XML content of the process definition is shown below. Notice that, for the moment, we are hard-coding an assignee called ""kermit"" to the user task. We'll come back to this later. [source,xml,linenums] ---- ---- Also, add following code lines to test if the deployment actually worked. The _CommandLineRunner_ is a special kind of Spring bean that is executed when the application boots: [source,java,linenums] ---- @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public CommandLineRunner init(final RepositoryService repositoryService, final RuntimeService runtimeService, final TaskService taskService) { return new CommandLineRunner() { @Override public void run(String... strings) throws Exception { System.out.println(""Number of process definitions : "" + repositoryService.createProcessDefinitionQuery().count()); System.out.println(""Number of tasks : "" + taskService.createTaskQuery().count()); runtimeService.startProcessInstanceByKey(""oneTaskProcess""); System.out.println(""Number of tasks after process start: "" + taskService.createTaskQuery().count()); } }; } } ---- The output expected will be: ---- Number of process definitions : 1 Number of tasks : 0 Number of tasks after process start : 1 ---- ==== Changing the database and connection pool As stated above, Spring Boot is about convention over configuration. By default, by having only H2 on the classpath, it created an in-memory datasource and passed that to the Flowable process engine configuration. To change the datasource, simply add the database driver dependencies and provide the URL to the database. For example, to switch to a MySQL database: [source,linenums] ---- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable-spring-boot?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- Remove H2 from the Maven dependencies and add the MySQL driver to the classpath: [source,xml,linenums] ---- mysql mysql-connector-java 5.1.45 ---- When the app is now booted up, you'll see it uses MySQL as database (and the HikariCP connection pooling framework): ---- org.flowable.engine.impl.db.DbSqlSession : performing create on engine with resource org/flowable/db/create/flowable.mysql.create.engine.sql org.flowable.engine.impl.db.DbSqlSession : performing create on history with resource org/flowable/db/create/flowable.mysql.create.history.sql org.flowable.engine.impl.db.DbSqlSession : performing create on identity with resource org/flowable/db/create/flowable.mysql.create.identity.sql ---- When you reboot the application multiple times, you'll see the number of tasks go up (the H2 in-memory database does not survive a shutdown, MySQL does). For more information about how to configure the datasource have a look in link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-configure-datasource$$[Configure a DataSource] in the Spring Boot reference guide. ==== REST support Often, a REST API is used on top of the embedded Flowable engine (interacting with the different services in a company). Spring Boot makes this really easy. Add following dependency to the classpath: [source,xml,linenums] ---- org.springframework.boot spring-boot-starter-web ${spring.boot.version} ---- Create a new class, a Spring service and create two methods: one to start our process and one to get a task list for a given assignee. We simply wrap Flowable calls here, but in real-life scenarios this will be more complex. [source,java,linenums] ---- @Service public class MyService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Transactional public void startProcess() { runtimeService.startProcessInstanceByKey(""oneTaskProcess""); } @Transactional public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } } ---- We can now create a REST endpoint by annotating a class with _@RestController_. Here, we simply delegate to the service defined above. [source,java,linenums] ---- @RestController public class MyRestController { @Autowired private MyService myService; @PostMapping(value=""/process"") public void startProcessInstance() { myService.startProcess(); } @RequestMapping(value=""/tasks"", method= RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) public List getTasks(@RequestParam String assignee) { List tasks = myService.getTasks(assignee); List dtos = new ArrayList(); for (Task task : tasks) { dtos.add(new TaskRepresentation(task.getId(), task.getName())); } return dtos; } static class TaskRepresentation { private String id; private String name; public TaskRepresentation(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ---- Both the _@Service_ and the _@RestController_ will be found by the automatic component scan for a Spring Boot application. Run the application class again. We can now interact with the REST API, for example, by using cURL: ---- curl http://localhost:8080/tasks?assignee=kermit [] curl -X POST http://localhost:8080/process curl http://localhost:8080/tasks?assignee=kermit [{""id"":""10004"",""name"":""my task""}] ---- As can be seen, we are referring to the assignee, ""kermit"", which was hard-coded into the process definition XML earlier. We'll change this later on to allow the assignee to be set when the workflow instance is started. ==== JPA support To add JPA support for Flowable in Spring Boot, add following dependency: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter ${flowable.version} org.springframework.boot spring-boot-starter-data-jpa ${spring-boot.version ---- This will add in the Spring configuration and beans for using JPA. By default, the JPA provider will be Hibernate. Let's create a simple Entity class: [source,java,linenums] ---- @Entity class Person { @Id @GeneratedValue private Long id; private String username; private String firstName; private String lastName; private Date birthDate; public Person() { } public Person(String username, String firstName, String lastName, Date birthDate) { this.username = username; this.firstName = firstName; this.lastName = lastName; this.birthDate = birthDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } } ---- By default, when not using an in-memory database, the tables won't be created automatically. Create a file _application.properties_ on the classpath and add following property: ---- spring.jpa.hibernate.ddl-auto=update ---- Add following class: [source,java,linenums] ---- @Repository public interface PersonRepository extends JpaRepository { Person findByUsername(String username); } ---- This is a Spring repository, which offers CRUD out of the box. We add the method to find a Person by username. Spring will automatically implement this based on conventions (typically, the property names used). We now enhance our service further: * by adding _@Transactional_ to the class. Note that by adding the JPA dependency above, the DataSourceTransactionManager which we were using before is now automatically swapped out by a JpaTransactionManager. * The _startProcess_ now gets an assignee username passed in, which is used to look up the Person, and put the Person JPA object as a process variable in the process instance. * A method to create Dummy users is added. This is used in the CommandLineRunner to populate the database. [source,java,linenums] ---- @Service @Transactional public class MyService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private PersonRepository personRepository; public void startProcess(String assignee) { Person person = personRepository.findByUsername(assignee); Map variables = new HashMap(); variables.put(""person"", person); runtimeService.startProcessInstanceByKey(""oneTaskProcess"", variables); } public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } public void createDemoUsers() { if (personRepository.findAll().size() == 0) { personRepository.save(new Person(""jbarrez"", ""Joram"", ""Barrez"", new Date())); personRepository.save(new Person(""trademakers"", ""Tijs"", ""Rademakers"", new Date())); } } } ---- The CommandLineRunner now looks like: [source,java,linenums] ---- @Bean public CommandLineRunner init(final MyService myService) { return new CommandLineRunner() { public void run(String... strings) throws Exception { myService.createDemoUsers(); } }; } ---- The RestController is also modified slightly to incorporate the changes above (only showing new methods) and the HTTP POST now has a body that contains the assignee username: ---- @RestController public class MyRestController { @Autowired private MyService myService; @PostMapping(value=""/process"") public void startProcessInstance(@RequestBody StartProcessRepresentation startProcessRepresentation) { myService.startProcess(startProcessRepresentation.getAssignee()); } ... static class StartProcessRepresentation { private String assignee; public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } } ---- And finally, to try out the Spring-JPA-Flowable integration, we assign the task using the ID of the Person JPA object in the process definition: [source,xml,linenums] ---- ---- This replaces the hard-coded recipient, ""kermit"", which we had initially set. We can now start a new process instance, providing the user name in the POST body: ---- curl -H ""Content-Type: application/json"" -d '{""assignee"" : ""jbarrez""}' http://localhost:8080/process ---- And the task list is now fetched using the person ID: ---- curl http://localhost:8080/tasks?assignee=1 [{""id"":""12505"",""name"":""my task""}] ---- [[springBootActuatorEndpoint]] ==== Flowable Actuator Endpoints Flowable provides a Spring Boot Actuator Endpoint that exposes information for the Processes that are running. By default the `flowable` endpoint is mapped to `/actuator/flowable`. Spring Boot by default only exposes the `info` and `health` endpoints. In order to enable the `flowable` endpoint you need to add `management.endpoint.flowable.enabled=true` to your `application.properties`. In order to make enable Actuator endpoints you need to add a dependency on Actuator, e.g. by using {sc-flowable-starter}/flowable-spring-boot-starter-actuator/pom.xml[flowable-spring-boot-starter-actuator]. `curl http://localhost:8080/actuator/flowable` [source,json] ---- { ""completedTaskCountToday"": 0, ""deployedProcessDefinitions"": [ ""oneTaskProcess (v1)"" ], ""processDefinitionCount"": 1, ""cachedProcessDefinitionCount"": 0, ""runningProcessInstanceCount"": { ""oneTaskProcess (v1)"": 0 }, ""completedTaskCount"": 2, ""completedActivities"": 3, ""completedProcessInstanceCount"": { ""oneTaskProcess (v1)"": 0 }, ""openTaskCount"": 0 } ---- For more information about Spring Boot Actuator see link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html$$[Production Ready Endpoint] in the Spring Boot reference documentation. [[springBootInfoContributor]] ==== Flowable Info Contributor Flowable also provides a Spring Boot `InfoContributor` which looks like: `curl http://localhost:8080/actuator/info` [source,json] ---- { ""flowable"": { ""version"": ""6.5.0-SNAPSHOT"" } } ---- [[springBootFlowableProperties]] ==== Flowable Application Properties The Flowable auto configuration is leveraging the Spring Boot properties and configuration mechanism. See link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html$$[Properties and Configuration] in the Spring Boot reference guide. Here is a list of configuration properties that the Flowable Spring Boot support consumes. [source,properties,indent=0,subs=""verbatim,attributes,macros""] ---- # =================================================================== # Common Flowable Spring Boot Properties # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # =================================================================== # Core (Process) {sc-flowable-boot}/FlowableProperties.java[FlowableProperties] flowable.check-process-definitions=true # Whether process definitions need to be auto deployed. flowable.custom-mybatis-mappers= # The FQN of custom Mybatis mappers that need to be added to the engine. flowable.custom-mybatis-x-m-l-mappers= # The location of the custom Mybatis XML Mappers that need to be added to the engine. flowable.database-schema= # In some situations you want to set the schema to use for table checks / generation if the database metadata doesn't return that correctly. flowable.database-schema-update=true # The strategy that should be used for the database schema. flowable.db-history-used=true # Whether db history should be used. flowable.deployment-name=SpringBootAutoDeployment # The name of the auto deployment. flowable.history-level=audit # The history level that needs to be used. flowable.process-definition-location-prefix=classpath*:/processes/ # The folder in which processes need to be searched for auto deployment. flowable.process-definition-location-suffixes=**.bpmn20.xml,**.bpmn # The suffixes (extensions) of the files that needs to be deployed from the 'processDefinitionLocationPrefix' location. # Process {sc-flowable-boot}/process/FlowableProcessProperties.java[FlowableProcessProperties] flowable.process.definition-cache-limit=-1 # The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions). flowable.process.enable-safe-xml=true # Enables extra checks on the BPMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.process.servlet.load-on-startup=-1 # Load on startup of the Process dispatcher servlet. flowable.process.servlet.name=Flowable BPMN Rest API # The name of the Process servlet. flowable.process.servlet.path=/process-api # The context path for the Process rest servlet. # Process Async Executor flowable.process.async-executor-activate=true # Whether the async executor should be activated. flowable.process.async.executor.async-job-lock-time-in-millis=300000 # The amount of time (in milliseconds) an async job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. flowable.process.async.executor.default-async-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the async job acquisition thread will wait to execute the next acquirement query. This happens when no new async jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.process.async.executor.default-queue-size-full-wait-time-in-millis=0 # The time (in milliseconds) the async job (both timer and async continuations) acquisition thread will wait when the queue is full to execute the next query. By default set to 0 (for backwards compatibility) flowable.process.async.executor.default-timer-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the timer job acquisition thread will wait to execute the next acquirement query. This happens when no new timer jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.process.async.executor.max-async-jobs-due-per-acquisition=1 # ??? flowable.process.async.executor.retry-wait-time-in-millis=500 # ??? flowable.process.async.executor.timer-lock-time-in-millis=300000 # The amount of time (in milliseconds) a timer job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. # CMMN {sc-flowable-boot}/cmmn/FlowableCmmnProperties.java[FlowableCmmnProperties] flowable.cmmn.deploy-resources=true # Whether to perform deployment of resources, default is 'true'. flowable.cmmn.deployment-name=SpringBootAutoDeployment # The name of the deployment for the CMMN resources. flowable.cmmn.enable-safe-xml=true # Enables extra checks on the DMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.cmmn.enabled=true # Whether the CMMN engine needs to be started. flowable.cmmn.resource-location=classpath*:/cases/ # The location where the CMMN resources are located. flowable.cmmn.resource-suffixes=**.cmmn,**.cmmn11,**.cmmn.xml,**.cmmn11.xml # The suffixes for the resources that need to be scanned. flowable.cmmn.servlet.load-on-startup=-1 # Load on startup of the CMMN dispatcher servlet. flowable.cmmn.servlet.name=Flowable CMMN Rest API # The name of the CMMN servlet. flowable.cmmn.servlet.path=/cmmn-api # The context path for the CMMN rest servlet. # CMMN Async Executor flowable.cmmn.async-executor-activate=true # Whether the async executor should be activated. flowable.cmmn.async.executor.async-job-lock-time-in-millis=300000 # The amount of time (in milliseconds) an async job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. flowable.cmmn.async.executor.default-async-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the async job acquisition thread will wait to execute the next acquirement query. This happens when no new async jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.cmmn.async.executor.default-queue-size-full-wait-time-in-millis=0 # The time (in milliseconds) the async job (both timer and async continuations) acquisition thread will wait when the queue is full to execute the next query. By default set to 0 (for backwards compatibility) flowable.cmmn.async.executor.default-timer-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the timer job acquisition thread will wait to execute the next acquirement query. This happens when no new timer jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.cmmn.async.executor.max-async-jobs-due-per-acquisition=1 # ??? flowable.cmmn.async.executor.retry-wait-time-in-millis=500 # ??? flowable.cmmn.async.executor.timer-lock-time-in-millis=300000 # The amount of time (in milliseconds) a timer job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. # Content {sc-flowable-boot}/content/FlowableContentProperties.java[FlowableContentProperties] flowable.content.enabled=true # Whether the content engine needs to be started. flowable.content.servlet.load-on-startup=-1 # Load on startup of the Content dispatcher servlet. flowable.content.servlet.name=Flowable Content Rest API # The name of the Content servlet. flowable.content.servlet.path=/content-api # The context path for the Content rest servlet. flowable.content.storage.create-root=true # If the root folder doesn't exist, should it be created? flowable.content.storage.root-folder= # Root folder location where content files will be stored, for example, task attachments or form file uploads. # DMN {sc-flowable-boot}/dmn/FlowableDmnProperties.java[FlowableDmnProperties] flowable.dmn.deploy-resources=true # Whether to perform deployment of resources, default is 'true'. flowable.dmn.deployment-name=SpringBootAutoDeployment # The name of the deployment for the dmn resources. flowable.dmn.enable-safe-xml=true # Enables extra checks on the DMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.dmn.enabled=true # Whether the dmn engine needs to be started. flowable.dmn.history-enabled=true # Whether the history for the DMN engine should be enabled. flowable.dmn.resource-location=classpath*:/dmn/ # The location where the dmn resources are located. flowable.dmn.resource-suffixes=**.dmn,**.dmn.xml,**.dmn11,**.dmn11.xml # The suffixes for the resources that need to be scanned. flowable.dmn.servlet.load-on-startup=-1 # Load on startup of the DMN dispatcher servlet. flowable.dmn.servlet.name=Flowable DMN Rest API # The name of the DMN servlet. flowable.dmn.servlet.path=/dmn-api # The context path for the DMN rest servlet. flowable.dmn.strict-mode=true # Set this to false if you want to ignore the decision table hit policy validity checks to result in an failed decision table state. A result is that intermediate results created up to the point the validation error occurs are returned. # Form {sc-flowable-boot}/form/FlowableFormProperties.java[FlowableFormProperties] flowable.form.deploy-resources=true # Whether to perform deployment of resources, default is true. flowable.form.deployment-name=SpringBootAutoDeployment # The name of the deployment for the form resources. flowable.form.enabled=true # Whether the form engine needs to be started. flowable.form.resource-location=classpath*:/forms/ # The location where the form resources are located. flowable.form.resource-suffixes=**.form # The suffixes for the resources that need to be scanned. flowable.form.servlet.load-on-startup=-1 # Load on startup of the Form dispatcher servlet. flowable.form.servlet.name=Flowable Form Rest API # The name of the Form servlet. flowable.form.servlet.path=/form-api # The context path for the Form rest servlet. # IDM {sc-flowable-boot}/idm/FlowableIdmProperties.java[FlowableIdmProperties] flowable.idm.enabled=true # Whether the idm engine needs to be started. flowable.idm.password-encoder= # The type of the password encoder that needs to be used. flowable.idm.servlet.load-on-startup=-1 # Load on startup of the IDM dispatcher servlet. flowable.idm.servlet.name=Flowable IDM Rest API # The name of the IDM servlet. flowable.idm.servlet.path=/idm-api # The context path for the IDM rest servlet. # IDM Ldap {sc-flowable-boot}/ldap/FlowableLdapProperties.java[FlowableLdapProperties] flowable.idm.ldap.attribute.email= # Name of the attribute that matches the user email. flowable.idm.ldap.attribute.first-name= # Name of the attribute that matches the user first name. flowable.idm.ldap.attribute.group-id= # Name of the attribute that matches the group id. flowable.idm.ldap.attribute.group-name= # Name of the attribute that matches the group name. flowable.idm.ldap.attribute.group-type= # Name of the attribute that matches the group type. flowable.idm.ldap.attribute.last-name= # Name of the attribute that matches the user last name. flowable.idm.ldap.attribute.user-id= # Name of the attribute that matches the user id. flowable.idm.ldap.base-dn= # The base 'distinguished name' (DN) from which the searches for users and groups are started. flowable.idm.ldap.cache.group-size=-1 # Allows to set the size of the {@link org.flowable.ldap.LDAPGroupCache}. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. flowable.idm.ldap.custom-connection-parameters= # Allows to set all LDAP connection parameters which do not have a dedicated setter. See for example http://docs.oracle.com/javase/tutorial/jndi/ldap/jndi.html for custom properties. Such properties are for example to configure connection pooling, specific security settings, etc. flowable.idm.ldap.enabled=false # Whether to enable LDAP IDM Service. flowable.idm.ldap.group-base-dn= # The base 'distinguished name' (DN) from which the searches for groups are started. flowable.idm.ldap.initial-context-factory=com.sun.jndi.ldap.LdapCtxFactory # The class name for the initial context factory. flowable.idm.ldap.password= # The password that is used to connect to the LDAP system. flowable.idm.ldap.port=-1 # The port on which the LDAP system is running. flowable.idm.ldap.query.all-groups= # The query that is executed when searching for all groups. flowable.idm.ldap.query.all-users= # The query that is executed when searching for all users. flowable.idm.ldap.query.groups-for-user= # The query that is executed when searching for the groups of a specific user. flowable.idm.ldap.query.user-by-full-name-like= # The query that is executed when searching for a user by full name. flowable.idm.ldap.query.user-by-id= # The query that is executed when searching for a user by userId. flowable.idm.ldap.query.group-by-id= # The query that is executed when searching for a specific group by groupId. flowable.idm.ldap.search-time-limit=0 # The timeout (in milliseconds) that is used when doing a search in LDAP. By default set to '0', which means 'wait forever'. flowable.idm.ldap.security-authentication=simple # The value that is used for the 'java.naming.security.authentication' property used to connect to the LDAP system. flowable.idm.ldap.server= # The server host on which the LDAP system can be reached. For example 'ldap://localhost'. flowable.idm.ldap.user= # The user id that is used to connect to the LDAP system. flowable.idm.ldap.user-base-dn= # The base 'distinguished name' (DN) from which the searches for users are started. # Flowable Mail {sc-flowable-boot}/FlowableMailProperties.java[FlowableMailProperties] flowable.mail.server.default-from=flowable@localhost # The default from address that needs to be used when sending emails. flowable.mail.server.force-to= # The force to address(es) that would be used when sending out emails. IMPORTANT: If this is set then all emails will be send to defined address(es) instead of the address configured in the MailActivity. flowable.mail.server.host=localhost # The host of the mail server. flowable.mail.server.password= # The password for the mail server authentication. flowable.mail.server.port=1025 # The port of the mail server. flowable.mail.server.use-ssl=false # Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). flowable.mail.server.use-tls=false # Set or disable the STARTTLS encryption. flowable.mail.server.username= # The username that needs to be used for the mail server authentication. If empty no authentication would be used. # Flowable Http {sc-flowable-boot}/FlowableHttpProperties.java[FlowableHttpProperties] flowable.http.user-system-properties=false # Whether to use system properties (e.g. http.proxyPort). flowable.http.connect-timeout=5s # Connect timeout for the http client flowable.http.socket-timeout=5s # Socket timeout for the http client flowable.http.connection-request-timeout=5s # Connection Request Timeout for the http client flowable.http.request-retry-limit=3 # Request retry limit for the http client flowable.http.disable-cert-verify=false # Whether to disable certificate validation for the http client # Flowable REST flowable.rest.app.cors.enabled=true # Whether to enable CORS requests at all. If false, the other properties have no effect flowable.rest.app.cors.allow-credentials=true # Whether to include credentials in a CORS request flowable.rest.app.cors.allowed-origins=* # Comma-separated URLs to accept CORS requests from flowable.rest.app.cors.allowed-headers=* # Comma-separated HTTP headers to allow in a CORS request flowable.rest.app.cors.allowed-methods=DELETE,GET,PATCH,POST,PUT # Comma-separated HTTP verbs to allow in a CORS request flowable.rest.app.cors.exposed-headers=* # Comma-separated list of headers to expose in CORS response # Actuator management.endpoint.flowable.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.flowable.enabled=true # Whether to enable the flowable endpoint. ---- .Deprecated properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.mail.server.host |flowable.mail-server-host |localhost |The host of the mail server. |flowable.mail.server.password |flowable.mail-server-password |- |The password for the mail server authentication. |flowable.mail.server.port |flowable.mail-server-port |1025 |The port of the mail server. |flowable.mail.server.use-ssl |flowable.mail-server-use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |flowable.mail-server-use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |flowable.mail-server-user-name |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions) |=============== [[springBootFlowableAutoConfiguration]] ==== Flowable Auto-configuration classes Here is a list of all auto-configuration classes provided by Flowable, with links to documentation and source code. Remember to also look at the conditions report in your application for more details of which features are switched on. (To do so, start the app with --debug or -Ddebug or, in an Actuator application, use the conditions endpoint). [cols=*,options=""header""] |=== |Configuration Class |{sc-flowable-boot}/content/ContentEngineAutoConfiguration.java[ContentEngineAutoConfiguration] |{sc-flowable-boot}/content/ContentEngineServicesAutoConfiguration.java[ContentEngineServicesAutoConfiguration] |{sc-flowable-boot}/cmmn/CmmnEngineAutoConfiguration.java[CmmnEngineAutoConfiguration] |{sc-flowable-boot}/cmmn/CmmnEngineServicesAutoConfiguration.java[CmmnEngineServicesAutoConfiguration] |{sc-flowable-boot}/dmn/DmnEngineAutoConfiguration.java[DmnEngineAutoConfiguration] |{sc-flowable-boot}/dmn/DmnEngineServicesAutoConfiguration.java[DmnEngineServicesAutoConfiguration] |{sc-flowable-boot}/EndpointAutoConfiguration.java[EndpointAutoConfiguration] |{sc-flowable-boot}/actuate/info/FlowableInfoAutoConfiguration.java[FlowableInfoAutoConfiguration] |{sc-flowable-boot}/ldap/FlowableLdapAutoConfiguration.java[FlowableLdapAutoConfiguration] |{sc-flowable-boot}/FlowableTransactionAutoConfiguration.java[FlowableTransactionAutoConfiguration] |{sc-flowable-boot}/form/FormEngineAutoConfiguration.java[FormEngineAutoConfiguration] |{sc-flowable-boot}/form/FormEngineServicesAutoConfiguration.java[FormEngineServicesAutoConfiguration] |{sc-flowable-boot}/idm/IdmEngineAutoConfiguration.java[IdmEngineAutoConfiguration] |{sc-flowable-boot}/idm/IdmEngineServicesAutoConfiguration.java[IdmEngineServicesAutoConfiguration] |{sc-flowable-boot}/ProcessEngineAutoConfiguration.java[ProcessEngineAutoConfiguration] |{sc-flowable-boot}/RestApiAutoConfiguration.java[RestApiAutoConfiguration] |{sc-flowable-boot}/SecurityAutoConfiguration.java[SecurityAutoConfiguration] |=== [[springBootFlowableStarter]] ==== Flowable Starters Here is a list of the flowable spring boot starters. [cols=2*,options=""header""] |=== |Starter |Description |{sc-flowable-starter}/flowable-spring-boot-starter-cmmn/pom.xml[flowable-spring-boot-starter-cmmn] |Contains the dependencies for booting the CMMN Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-cmmn-rest/pom.xml[flowable-spring-boot-starter-cmmn-rest] |Contains the dependencies for booting the CMMN Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter-dmn/pom.xml[flowable-spring-boot-starter-dmn] |Contains the dependencies for booting the DMN Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-dmn-rest/pom.xml[flowable-spring-boot-starter-dmn-rest] |Contains the dependencies for booting the DMN Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter-process/pom.xml[flowable-spring-boot-starter-process] |Contains the dependencies for booting the Process Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-process-rest/pom.xml[flowable-spring-boot-starter-process-rest] |Contains the dependencies for booting the Process Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter/pom.xml[flowable-spring-boot-starter] |Contains the dependencies for booting all Flowable Engines (Process, CMMN, DMN, Form, Content and IDM) |{sc-flowable-starter}/flowable-spring-boot-starter-rest/pom.xml[flowable-spring-boot-starter-rest] |Contains the dependencies for booting all Flowable Engines and their respective REST API |{sc-flowable-starter}/flowable-spring-boot-starter-actuator/pom.xml[flowable-spring-boot-starter-actuator] |Contains the required dependencies for Spring Boot |=== ==== Using Liquibase The Flowable engines are using Liquibase to manage the versioning of it's tables. This means that the `LiquibaseAutoConfiguration` from Spring Boot would automatically kick in. However, if you are not using Liquibase then the application will not start and would throw an exception. For this reason Flowable is setting `spring.liquibase.enabled` to `false`, which means that if you need to use Liquibase you have to explicitly enable it. ==== Further Reading Obviously, there is a lot about Spring Boot that hasn't been touched upon yet, like very easy JTA integration or building a WAR file that can be run on major application servers. And there is a lot more to the Spring Boot integration: * Actuator support * Spring Integration support * Rest API integration: boot up the Flowable Rest API embedded within the Spring application * Spring Security support ==== Advanced Configuration ===== Customizing Engine Configuration It's possible to get a hold of the engine configuration by implementing the _org.flowable.spring.boot.EngineConfigurationConfigurer_ interface. Where _T_ is the Spring Type of the particular Engine Configuration. This can be useful for advanced configuration settings or simply because a property has not been exposed (yet). For example: [source, java, linenums] ---- public class MyConfigurer implements EngineConfigurationConfigurer { public void configure(SpringProcessEngineConfiguration processEngineConfiguration) { // advanced configuration } } ---- By exposing an instance of this class as an _@Bean_ in the Spring Boot configuration, the instance will be called before the process engine is fully created. [TIP] ==== You can provide a custom implementation of a Flowable Service by using this. See {sc-flowable-boot}/ldap/FlowableLdapAutoConfiguration.java[FlowableLdapAutoConfiguration] ==== ===== Combining starters In case you need only a combination of the engines then you can add only the required dependencies. For example to use the Process, CMMN, Form and IDM engine and use LDAP you need to add the following dependencies: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter-process ${flowable.version} org.flowable flowable-spring-boot-starter-cmmn ${flowable.version} org.flowable flowable-content-spring-configurator ${flowable.version} org.flowable flowable-form-spring-configurator ${flowable.version} org.flowable flowable-ldap ${flowable.version} ---- ===== Configuring Async Executors The Process and CMMN engines have dedicated `AsyncExecutor`(s) and they can be configured with the `flowable.{engine}.async.executor` property group. Where `engine` is either `process` or `cmmn`. The `AsyncExecutor`(s) per default share the same Spring `TaskExecutor` and `SpringRejectedJobsHandler`. In case you want to provide a dedicated executor for each of the engines you need define a qualified bean with `@Process` and `@Cmmn`. You can configure custom executors in the following way: [source,java,linenums] ---- @Configuration public class MyConfiguration { @Process <1> @Bean public TaskExecutor processTaskExecutor() { return new SimpleAsyncTaskExecutor(); } @Cmmn <2> @Bean public TaskExecutor cmmnTaskExecutor() { return new SyncTaskExecutor(); } } ---- <1> The Async Executor for the Process Engine would use a `SimpleAsyncTaskExecutor` <2> The Async Executor for the CMMN Engine would use a `SyncTaskExecutor` [IMPORTANT] ====== If you define a custom `TaskExecutor` bean the Flowable creation of the bean is not triggered. Which means that if you define a bean qualified with `@Process` you have to define one with `@Cmmn` or `@Primary`, otherwise the Cmmn Async Executor will use the one for the Process ====== ",12192,False,1871.8017517410512,median "/******************************************************************************* * Copyright 2019-2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include ""common/c_types_map.hpp"" #include ""common/nstl.hpp"" #include ""common/type_helpers.hpp"" #include ""common/utils.hpp"" #include ""cpu/x64/injectors/jit_uni_binary_injector.hpp"" #include ""cpu/x64/injectors/jit_uni_eltwise_injector.hpp"" #include ""cpu/x64/jit_avx512_core_bf16_dw_conv_kernel.hpp"" #define GET_OFF(field) offsetof(jit_conv_call_s, field) namespace dnnl { namespace impl { namespace cpu { namespace x64 { using namespace Xbyak; using namespace dnnl::impl::utils; jit_avx512_dw_conv_fwd_kernel_bf16::jit_avx512_dw_conv_fwd_kernel_bf16( const jit_conv_conf_t &ajcp, const memory_desc_t &dst_md, const primitive_attr_t& attr) : jcp(ajcp), attr_(attr) { if (jcp.with_eltwise || jcp.with_binary || jcp.with_depthwise || jcp.with_quantization) { using namespace binary_injector; static constexpr bool preserve_gpr = true; static constexpr bool preserve_vmm = false; static constexpr size_t helper_vmm_idx = 31; static constexpr bool use_exact_tail_scalar_bcast = true; const size_t tail_size = jcp.oc_without_padding % (cpu_isa_traits::vlen / sizeof(float)); const rhs_arg_static_params_t rhs_arg_static_params {helper_vmm_idx, r14, r15, preserve_gpr, preserve_vmm, GET_OFF(post_ops_binary_rhs_arg_vec), memory_desc_wrapper(dst_md), tail_size, k_oc_tail_mask, use_exact_tail_scalar_bcast}; const static_params_t static_params { this->param1, rhs_arg_static_params}; quantization_injector::static_params_t quantization_static_params {zmm_d_weights.getIdx(), zmm_d_bias.getIdx(), reg_d_weights, reg_d_bias}; postops_injector_ = utils::make_unique< injector::jit_uni_postops_injector_t>( this, jcp.post_ops, static_params, quantization_static_params); } if (!isa_has_bf16(jcp.isa)) bf16_emu_ = utils::make_unique(this, bf16_emu_reserv_1, bf16_emu_reserv_2, bf16_emu_reserv_3, bf16_emu_reserv_4, bf16_emu_reserv_5, bf16_emu_reserv_6); } int jit_avx512_dw_conv_fwd_kernel_bf16::get_acc_reg_idx(int idx) const { assert(idx + acc_idx_start <= get_max_regs()); return idx + acc_idx_start; } Xbyak::Zmm jit_avx512_dw_conv_fwd_kernel_bf16::get_acc_reg(int idx) { return Xbyak::Zmm(get_acc_reg_idx(idx)); } void jit_avx512_dw_conv_fwd_kernel_bf16::load_src( int ur_ch_blocks, int ur_w, bool last_ch_block_flag) { const auto dst_layout_nxc = is_dst_layout_nxc(); const auto ch_blk = jcp.ch_block; const auto ocb_stride = dst_layout_nxc ? ch_blk : jcp.oh * jcp.ow * ch_blk; const auto ow_stride = dst_layout_nxc ? jcp.ngroups : ch_blk; for (int ch = 0; ch < ur_ch_blocks; ch++) { const bool mask_flag = last_ch_block_flag && ch == ur_ch_blocks - 1; for (int ow = 0; ow < ur_w; ow++) { Zmm zmm_acc = get_acc_reg(ch * ur_w + ow); const Zmm zmm_acc_msk = mask_flag ? zmm_acc | ktail_mask | T_z : zmm_acc; if (this->jcp.with_bias) { int b_off = ch * ch_blk; uni_vmovups( zmm_acc_msk, vmmword[reg_bias + b_off * sizeof(float)]); } else { uni_vpxor(zmm_acc, zmm_acc, zmm_acc); } if (this->jcp.with_sum) { int o_off = ch * ocb_stride + ow * ow_stride; if (jcp.dst_dt == data_type::bf16) { const Zmm zmm_prev_dst_msk = mask_flag ? zmm_prev_dst | ktail_mask | T_z : zmm_prev_dst; vpmovzxwd(zmm_prev_dst_msk, vmmword[reg_output + o_off * jcp.typesize_out]); vpslld(zmm_prev_dst, zmm_prev_dst, 16); vaddps(zmm_acc, zmm_prev_dst); } else { uni_vaddps(zmm_acc_msk, zmm_acc_msk, vmmword[reg_output + o_off * jcp.typesize_out]); } } } } } void jit_avx512_dw_conv_fwd_kernel_bf16::apply_filter_unrolled(int ur_ch_blocks, int ur_w, int pad_l, int pad_r, bool last_ch_block_flag) { int ch_blk = jcp.ch_block; int dilate_h = jcp.dilate_h + 1; int dilate_w = jcp.dilate_w + 1; int stride_w = jcp.stride_w; const auto src_layout_nxc = is_src_layout_nxc(); const auto iw_stride = src_layout_nxc ? jcp.ngroups : ch_blk; const auto ih_stride = jcp.iw * iw_stride; const auto icb_stride = src_layout_nxc ? ch_blk : (jcp.is_fused_conv ? 1 : jcp.ih) * jcp.iw * ch_blk; Label iter_exit_label; cmp(reg_kh, 0); je(iter_exit_label, T_NEAR); mov(iter_kh, reg_kh); Label kh_label; L(kh_label); { if (jcp.is_fused_conv) { mov(aux_reg_input, ptr[aux_reg_input_buffer_ptr]); add(aux_reg_input, reg_iw_offset); } for (int ch = 0; ch < ur_ch_blocks; ch++) { const bool mask_flag = last_ch_block_flag && ch == ur_ch_blocks - 1; for (int kw = 0; kw < jcp.kw; kw++) { int ker_off = ch * jcp.kh * jcp.kw * ch_blk + kw * ch_blk; const Zmm zmm_ker_reg_msk = mask_flag ? zmm_ker_reg | ktail_mask | T_z : zmm_ker_reg; vpmovzxwd(zmm_ker_reg_msk, ptr[aux_reg_kernel + ker_off * jcp.typesize_in]); int ow_start = get_ow_start(kw, pad_l); int ow_end = get_ow_end(ur_w, kw, pad_r); for (int ow = ow_start; ow < ow_end; ow++) { const Zmm zmm_src_reg_msk = mask_flag ? zmm_src_reg | ktail_mask | T_z : zmm_src_reg; Zmm zmm_acc = get_acc_reg(ch * ur_w + ow); int inp_off = ch * icb_stride + (ow * stride_w - pad_l) * iw_stride + kw * dilate_w * iw_stride; /* zero-extend bf16 to packed 32-bit int */ vpmovzxwd(zmm_src_reg_msk, ptr[aux_reg_input + inp_off * jcp.typesize_in]); if (isa_has_bf16(jcp.isa)) vdpbf16ps(zmm_acc, zmm_ker_reg, zmm_src_reg); else bf16_emu_->vdpbf16ps(zmm_acc, zmm_ker_reg, zmm_src_reg); } } } add(aux_reg_kernel, jcp.kw * ch_blk * jcp.typesize_in); if (jcp.is_fused_conv) { // Move to next row pointer in the buffer add(aux_reg_input_buffer_ptr, sizeof(void *)); } else { add(aux_reg_input, ih_stride * dilate_h * jcp.typesize_in); } dec(iter_kh); cmp(iter_kh, 0); jg(kh_label, T_NEAR); } L(iter_exit_label); } template static void iterate(const int ur_ch_blocks, const int ur_w, const bool mask_tail, const F &f) { for (int ch = 0; ch < ur_ch_blocks; ch++) { const bool mask_flag = mask_tail && ch + 1 == ur_ch_blocks; for (int ow = 0; ow < ur_w; ow++) f(ch, ow, mask_flag); } } template static void iterate(const int ur_ch_blocks, const int ur_w, const F &f) { iterate(ur_ch_blocks, ur_w, false, f); } void jit_avx512_dw_conv_fwd_kernel_bf16::apply_postops( int ur_ch_blocks, int ur_w, bool last_ch_block_flag) { if (this->jcp.with_eltwise || this->jcp.with_binary || this->jcp.with_depthwise || this->jcp.with_quantization) { std::map vmm_idx_off; iterate(ur_ch_blocks, ur_w, [&](int ch, int ow, int) { vmm_idx_off.insert({get_acc_reg_idx(ch * ur_w + ow), ch * jcp.ch_block * sizeof(float)}); }); depthwise_injector::dynamic_params_t ddp {zmm_d_weights.getIdx(), zmm_d_bias.getIdx(), reg_d_weights, reg_d_bias, ptr[this->param1 + GET_OFF(oc_off)], vmm_idx_off, this->rsp, base_post_ops_data_offset}; quantization_injector::dynamic_params_t qdp {ptr[this->param1 + GET_OFF(oc_off)], vmm_idx_off, jcp.dst_dt, this->rsp, base_post_ops_data_offset}; injector_utils::vmm_index_set_t vmm_idxs; if (jcp.with_binary) { binary_injector::rhs_arg_dynamic_params_t rhs_arg_params, rhs_arg_params_tail; const auto mask_tail = jcp.oc_without_padding % jcp.ch_block; const auto dst_layout_nxc = is_dst_layout_nxc(); const auto ch_blk = jcp.ch_block; const auto ocb_stride = dst_layout_nxc ? ch_blk : jcp.oh * jcp.ow * ch_blk; const auto ow_stride = dst_layout_nxc ? jcp.ngroups : ch_blk; const bool mask_tail_blocked_layout = jcp.oc_without_padding % jcp.ch_block && !dst_layout_nxc; iterate(ur_ch_blocks, ur_w, mask_tail, [&](int ch, int ow, int mask_flag) { const int aux_output_l_off = (ch * ocb_stride + ow * ow_stride); const auto vmm_idx = get_acc_reg_idx(ch * ur_w + ow); vmm_idxs.emplace(vmm_idx); rhs_arg_params_tail.vmm_idx_to_oc_elem_off_addr.emplace( vmm_idx, ptr[param1 + GET_OFF(oc_l_off)]); rhs_arg_params_tail.vmm_idx_to_oc_elem_off_val.emplace( vmm_idx, ch * jcp.ch_block); if (dst_layout_nxc) rhs_arg_params_tail.vmm_idx_to_oc_off_oprnd.emplace( vmm_idx, oc_off_oprnd); rhs_arg_params_tail.vmm_idx_to_out_elem_off_val.emplace( vmm_idx, aux_output_l_off); rhs_arg_params_tail.vmm_idx_to_out_off_oprnd.emplace( vmm_idx, out_off_oprnd); if (mask_flag) rhs_arg_params_tail.vmm_tail_idx_.emplace(vmm_idx); }); rhs_arg_params = rhs_arg_params_tail; rhs_arg_params.vmm_tail_idx_.clear(); const injector_utils::conditional_register_preserve_guard_t cond_reg_guard_no_bcast( jcp.with_binary_no_bcast, this, {out_off_oprnd}); if (jcp.with_binary_no_bcast) { mov(out_off_oprnd, reg_output); sub(out_off_oprnd, ptr[param1 + GET_OFF(dst_orig)]); shr(out_off_oprnd, std::log2(types::data_type_size(jcp.dst_dt))); } const injector_utils::conditional_register_preserve_guard_t cond_reg_guard_per_oc( jcp.with_binary_per_oc_bcast && dst_layout_nxc, this, {oc_off_oprnd}); if (jcp.with_binary_per_oc_bcast && dst_layout_nxc) sub(oc_off_oprnd, aux_reg_ch_blocks); Label postops_done; if (mask_tail_blocked_layout) { Label postops_no_tail; const auto reg_tail = oc_off_oprnd; mov(reg_tail, ptr[param1 + GET_OFF(load_work)]); cmp(reg_tail, jcp.nb_ch_blocking * jcp.ch_block); jge(postops_no_tail, T_NEAR); postops_injector_->compute_vector_range( vmm_idxs, rhs_arg_params_tail); jmp(postops_done, T_NEAR); L(postops_no_tail); postops_injector_->compute_vector_range( vmm_idxs, rhs_arg_params, ddp, qdp); } else if (last_ch_block_flag) postops_injector_->compute_vector_range( vmm_idxs, rhs_arg_params_tail, ddp, qdp); else /* if (!last_ch_block_flag) */ postops_injector_->compute_vector_range( vmm_idxs, rhs_arg_params, ddp, qdp); L(postops_done); } else { iterate(ur_ch_blocks, ur_w, [&](int ch, int ow, int) { vmm_idxs.emplace(get_acc_reg_idx(ch * ur_w + ow)); }); postops_injector_->compute_vector_range(vmm_idxs, binary_injector::rhs_arg_dynamic_params_t(), ddp, qdp); } } } void jit_avx512_dw_conv_fwd_kernel_bf16::store_dst( int ur_ch_blocks, int ur_w, bool last_ch_block_flag) { const auto dst_layout_nxc = is_dst_layout_nxc(); const auto ch_blk = jcp.ch_block; const auto ocb_stride = dst_layout_nxc ? ch_blk : jcp.oh * jcp.ow * ch_blk; const auto ow_stride = dst_layout_nxc ? jcp.ngroups : ch_blk; if (jcp.dst_dt == data_type::bf16 && !isa_has_bf16(jcp.isa)) bf16_emu_->init_vcvtneps2bf16(); if (dst_layout_nxc && jcp.dst_dt == data_type::bf16 && isa_has_bf16(jcp.isa)) { for (int j = 0; j < ur_w; ++j) { int n_2bf2ps = (ur_ch_blocks / 2) * 2; int ch = 0; for (; ch < n_2bf2ps; ch += 2) { size_t aux_output_offset = (size_t)ch * ocb_stride + j * ow_stride; auto addr = ptr[reg_output + aux_output_offset * jcp.typesize_out]; auto zmm_dst = get_acc_reg(ch * ur_w + j); vcvtne2ps2bf16( zmm_dst, get_acc_reg((ch + 1) * ur_w + j), zmm_dst); bool mask_flag = last_ch_block_flag && ch + 2 == ur_ch_blocks; Zmm zmm_dst_msk = mask_flag ? zmm_dst | k_ch_tail_mask_extended : zmm_dst; vmovdqu16(addr, zmm_dst_msk); } /* Perform tail write for odd ch sizes */ if (ch < ur_ch_blocks) { size_t aux_output_offset = (size_t)ch * ocb_stride + j * ow_stride; auto addr = ptr[reg_output + aux_output_offset * jcp.typesize_out]; auto zmm_dst = get_acc_reg(ch * ur_w + j); auto ymm_dst = Ymm(zmm_dst.getIdx()); vcvtneps2bf16(ymm_dst, zmm_dst); Ymm ymm_dst_msk = last_ch_block_flag ? ymm_dst | ktail_mask : ymm_dst; vmovdqu16(addr, ymm_dst_msk); } } } else { // also used for case when dst_layout_nxc && dst.dt == f32 if (jcp.dst_dt == data_type::f32) { for (int ch = 0; ch < ur_ch_blocks; ch++) { bool mask_flag = last_ch_block_flag && ch == ur_ch_blocks - 1; for (int ow = 0; ow < ur_w; ow++) { int o_off = ch * ocb_stride + ow * ow_stride; Zmm zmm_dst = get_acc_reg(ch * ur_w + ow); Zmm zmm_dst_msk = mask_flag ? zmm_dst | ktail_mask : zmm_dst; vmovups(vmmword[reg_output + o_off * jcp.typesize_out], zmm_dst_msk); } } } else if (jcp.dst_dt == data_type::bf16) { if (isa_has_bf16(jcp.isa)) { // !dst_layout_nxc() assert(jcp.ngroups % jcp.ch_block == 0); for (int ch = 0; ch < ur_ch_blocks; ch++) { int n_2bf2ps = (ur_w / 2) * 2; int j = 0; for (; j < n_2bf2ps; j += 2) { size_t aux_output_offset = (size_t)ch * ocb_stride + j * ow_stride; auto addr = ptr[reg_output + aux_output_offset * jcp.typesize_out]; auto zmm_dst = get_acc_reg(ch * ur_w + j); vcvtne2ps2bf16(zmm_dst, get_acc_reg(ch * ur_w + j + 1), get_acc_reg(ch * ur_w + j)); vmovups(addr, zmm_dst); } /* Perform tail write for odd ur_w sizes */ if (j < ur_w) { size_t aux_output_offset = (size_t)ch * ocb_stride + j * ow_stride; auto addr = ptr[reg_output + aux_output_offset * jcp.typesize_out]; auto zmm_dst = get_acc_reg(ch * ur_w + j); auto ymm_dst = Ymm(zmm_dst.getIdx()); vcvtneps2bf16(ymm_dst, zmm_dst); vmovups(addr, ymm_dst); } } } else { for (int ch = 0; ch < ur_ch_blocks; ch++) { bool mask_flag = last_ch_block_flag && ch == ur_ch_blocks - 1; for (int ow = 0; ow < ur_w; ow++) { int o_off = ch * ocb_stride + ow * ow_stride; Zmm zmm_dst = get_acc_reg(ch * ur_w + ow); /* down-convert f32 output to bf16 */ auto ymm_dst = Ymm(zmm_dst.getIdx()); bf16_emu_->vcvtneps2bf16(ymm_dst, zmm_dst); Ymm ymm_dst_msk = mask_flag ? ymm_dst | ktail_mask : ymm_dst; vmovdqu16(ptr[reg_output + o_off * jcp.typesize_out], ymm_dst_msk); } } } } else assert(!""unsupported destination type""); } } void jit_avx512_dw_conv_fwd_kernel_bf16::compute_loop( int ur_w, int ur_ch_blocks, int pad_l, int pad_r) { // ch_loop currently happen only when data layout is nxc. The strides are // calculated for this layout only. const size_t wei_ch_stride = (size_t)jcp.nb_ch_blocking * jcp.kh * jcp.kw * jcp.ch_block * jcp.typesize_in; const size_t inp_ch_stride = (size_t)jcp.nb_ch_blocking * jcp.ch_block * jcp.typesize_in; const size_t out_ch_stride = (size_t)jcp.nb_ch_blocking * jcp.ch_block * jcp.typesize_out; const size_t bias_stride = (size_t)jcp.nb_ch_blocking * jcp.ch_block * sizeof(float); auto compute = [&](int ur_ch_blocks, bool last_ch_block_flag = false) { if (jcp.is_fused_conv) { mov(aux_reg_input_buffer_ptr, reg_input_buffer_ptr); } else { mov(aux_reg_input, reg_input); } mov(aux_reg_kernel, reg_kernel); load_src(ur_ch_blocks, ur_w, last_ch_block_flag); apply_filter_unrolled( ur_ch_blocks, ur_w, pad_l, pad_r, last_ch_block_flag); apply_postops(ur_ch_blocks, ur_w, last_ch_block_flag); store_dst(ur_ch_blocks, ur_w, last_ch_block_flag); }; const bool masked_ch_block_tail = jcp.oc % jcp.ch_block != 0; const bool ch_loop = ur_ch_blocks > jcp.nb_ch_blocking; mov(aux_reg_ch_blocks, reg_ch_blocks); if (ch_loop) { Label ch_loop_label, ch_tail_label, skip_ch_tail_label; const int nb_ch = jcp.oc / jcp.ch_block; const int nb_ch_blocking_tail = jcp.nb_ch - utils::rnd_dn(nb_ch, jcp.nb_ch_blocking); const int ch_step = jcp.nb_ch_blocking * jcp.ch_block; push(reg_kernel); push(reg_input); push(reg_output); base_post_ops_data_offset += 3 * reg64_size; if (jcp.with_bias) { push(reg_bias); base_post_ops_data_offset += reg64_size; } if (nb_ch >= jcp.nb_ch_blocking) { if (nb_ch_blocking_tail) { cmp(aux_reg_ch_blocks, ch_step); jl(ch_tail_label, T_NEAR); } L(ch_loop_label); { compute(jcp.nb_ch_blocking); add(reg_kernel, wei_ch_stride); add(reg_input, inp_ch_stride); add(reg_output, out_ch_stride); if (jcp.with_bias) add(reg_bias, bias_stride); sub(aux_reg_ch_blocks, ch_step); cmp(aux_reg_ch_blocks, ch_step); jge(ch_loop_label, T_NEAR); } } if (nb_ch_blocking_tail) { // ch work range [1, jcp.nb_ch_blocking * ch_block) L(ch_tail_label); cmp(aux_reg_ch_blocks, 0); jle(skip_ch_tail_label, T_NEAR); compute(nb_ch_blocking_tail, masked_ch_block_tail); L(skip_ch_tail_label); } if (jcp.with_bias) { pop(reg_bias); base_post_ops_data_offset -= reg64_size; } pop(reg_output); pop(reg_input); pop(reg_kernel); base_post_ops_data_offset -= reg64_size; } else { compute(ur_ch_blocks, masked_ch_block_tail); } } void jit_avx512_dw_conv_fwd_kernel_bf16::loop_ow(int ur_ch_blocks) { int iw = jcp.iw; int ow = jcp.ow; int kw = jcp.kw; int l_pad = jcp.l_pad; int ur_w = jcp.ur_w; int ur_w_tail = jcp.ur_w_tail; int stride_w = jcp.stride_w; const auto src_layout_nxc = is_src_layout_nxc(); const auto dat_c_stride = src_layout_nxc ? jcp.ngroups : jcp.ch_block; size_t inp_shift = (size_t)jcp.typesize_in * ur_w * stride_w * dat_c_stride; size_t out_shift = (size_t)jcp.typesize_out * ur_w * dat_c_stride; int inp_shift_pad = jcp.typesize_in * (ur_w * stride_w - l_pad) * dat_c_stride; int r_pad = nstl::max(0, jcp.r_pad); int n_oi = ow / ur_w; int r_pad1 = calculate_end_padding(l_pad, ur_w * n_oi, iw, stride_w, calculate_extended_filter_size(kw, jcp.dilate_w)); assert(jcp.nb_ow <= 1); if (r_pad1 > 0) n_oi--; xor_(reg_oi, reg_oi); if (ow == ur_w) { compute_loop(ur_w, ur_ch_blocks, l_pad, r_pad); } else { if (n_oi == 0) { compute_loop(ur_w, ur_ch_blocks, l_pad, r_pad1); add(reg_input, inp_shift_pad); add(reg_output, out_shift); if (ur_w_tail != 0) { compute_loop(ur_w_tail, ur_ch_blocks, 0, r_pad); } } else { if (l_pad > 0) { compute_loop(ur_w, ur_ch_blocks, l_pad, 0); add(reg_input, inp_shift_pad); add(reg_output, out_shift); inc(reg_oi); } if ((l_pad <= 0 && n_oi > 0) || (l_pad > 0 && n_oi > 1)) { Label ow_loop_label; L(ow_loop_label); { compute_loop(ur_w, ur_ch_blocks, 0, 0); add(reg_input, inp_shift); add(reg_output, out_shift); inc(reg_oi); cmp(reg_oi, n_oi); jl(ow_loop_label, T_NEAR); } } if (r_pad1 > 0) { compute_loop(ur_w, ur_ch_blocks, 0, r_pad1); add(reg_input, inp_shift); add(reg_output, out_shift); } if (ur_w_tail != 0) { compute_loop(ur_w_tail, ur_ch_blocks, 0, r_pad); } } } } void jit_avx512_dw_conv_fwd_kernel_bf16::generate() { this->preamble(); if (postops_injector_) postops_injector_->push_post_ops_data_on_stack(this->param1, GET_OFF(post_ops_binary_rhs_arg_vec), reg_input, reg_output); assert(mayiuse(avx512_core)); if (jcp.is_fused_conv) { mov(reg_input_buffer_ptr, ptr[this->param1 + GET_OFF(src)]); /* In case of fused depthwise convolution, `param.src` is not a pointer to input, instead it points to a buffer containing pointers to consecutive rows of input in format Cwc with blocking nb_ch_blocking. Example: [ptr_to_inp_row0, ptr_to_inp_row1, ptr_to_inp_row2]. Traverse the data as mov(reg_data, ptr[reg_input_buffer_ptr]) ... process row0 ... add(reg_input_buffer_ptr, sizeof(void*)) mov(reg_data, ptr[reg_input_buffer_ptr]) ... process row1 ... add(reg_input_buffer_ptr, sizeof(void*)) mov(reg_data, ptr[reg_input_buffer_ptr]) ... process row2 ... */ xor_(reg_iw_offset, reg_iw_offset); } else { mov(reg_input, ptr[this->param1 + GET_OFF(src)]); } mov(reg_output, ptr[this->param1 + GET_OFF(dst)]); mov(reg_kernel, ptr[this->param1 + GET_OFF(filt)]); if (jcp.with_bias) mov(reg_bias, ptr[this->param1 + GET_OFF(bias)]); mov(reg_kh, ptr[this->param1 + GET_OFF(kh_padding)]); mov(reg_ch_blocks, ptr[this->param1 + GET_OFF(load_work)]); Label ch_blocks_tail_label; Label exit_label; const int ch_blocks_tail = jcp.nb_ch % jcp.nb_ch_blocking; const auto oc_tail = jcp.oc_without_padding % jcp.ch_block; if (oc_tail != 0) { // Note: is_src_layout_nxc() == true, otherwise channels are padded // Prepare masks for tailing const int oc_tail_shift = jcp.ch_block - jcp.oc_without_padding % jcp.ch_block; static constexpr auto zmm_16b_mask = ((1 << 16) - 1); // To account for special store optimization, where two oc_blocks are // combined with one single write, extend the mask for 32 bits // (i.e. 32 bfloat16 elements) const bool need_extended_mask = jcp.dst_dt == data_type::bf16 && isa_has_bf16(jcp.isa) && jcp.nb_ch_blocking > 1; if (need_extended_mask) kxnord(k_ch_tail_mask_extended, k_ch_tail_mask_extended, k_ch_tail_mask_extended); Label done; mov(reg_tail, ptr[param1 + GET_OFF(load_work)]); cmp(reg_tail, jcp.nb_ch_blocking * jcp.ch_block); je(done, T_NEAR); Reg32 reg_tail_32 = reg_tail.cvt32(); mov(reg_tail_32, zmm_16b_mask >> oc_tail_shift); kmovw(k_oc_tail_mask, reg_tail_32); if (need_extended_mask) { auto zmm_32b_mask = (1 << (oc_tail + jcp.ch_block)) - 1; mov(reg_tail_32, zmm_32b_mask); kmovd(k_ch_tail_mask_extended, reg_tail_32); } L(done); } if (is_src_layout_nxc()) { loop_ow(jcp.nb_ch); } else { cmp(reg_ch_blocks, (jcp.nb_ch_blocking - 1) * jcp.ch_block); jle(ch_blocks_tail ? ch_blocks_tail_label : exit_label, T_NEAR); loop_ow(jcp.nb_ch_blocking); // channel main loop if (ch_blocks_tail) { jmp(exit_label, T_NEAR); L(ch_blocks_tail_label); loop_ow(ch_blocks_tail); // channel tail loop } L(exit_label); } if (postops_injector_) postops_injector_->reset_stack_pointer(); postamble(); if (jcp.with_eltwise) postops_injector_->prepare_table(); } inline void jit_avx512_dw_conv_bwd_data_kernel_bf16::load_ddst( int ur_ch_blocks, int ur_str_w) { for (int ch = 0; ch < ur_ch_blocks; ch++) { for (int w = 0; w < ur_str_w; w++) { Zmm zmm_acc = get_acc_reg(ch * ur_str_w + w); uni_vpxor(zmm_acc, zmm_acc, zmm_acc); } } } inline void jit_avx512_dw_conv_bwd_data_kernel_bf16::apply_filter( int ur_ch_blocks, int ur_str_w, bool last_ch_block_flag) { int kw = jcp.kw; int kh = jcp.kh; int ow = jcp.ow; int oh = jcp.oh; int ch_blk = jcp.ch_block; int stride_h = jcp.stride_h; int stride_w = jcp.stride_w; const bool ddst_layout_nxc = is_ddst_layout_nxc(); const size_t ch_block_step = ch_blk * (ddst_layout_nxc ? 1 : oh * ow); const size_t sp_step = ddst_layout_nxc ? jcp.ngroups : ch_blk; Label iter_exit_label; cmp(reg_kh, 0); je(iter_exit_label, T_NEAR); cmp(reg_kw, 0); je(iter_exit_label, T_NEAR); mov(iter_kh, reg_kh); Label kh_label; L(kh_label); { mov(aux1_reg_ddst, aux_reg_ddst); mov(aux1_reg_kernel, aux_reg_kernel); mov(iter_kw, reg_kw); Label kw_label; L(kw_label); { for (int ch = 0; ch < ur_ch_blocks; ch++) { const bool mask_flag = last_ch_block_flag && ch == ur_ch_blocks - 1; int ker_off = ch * kh * kw * ch_blk; Zmm mm_zmm_ker // mm: maybe masked = mask_flag ? zmm_ker_reg | k_ch_tail_mask | T_z : zmm_ker_reg; vpmovzxwd(mm_zmm_ker, ptr[aux1_reg_kernel + ker_off * jcp.typesize_in]); for (int w = 0; w < ur_str_w; w++) { size_t sp_offset = w * sp_step; size_t ch_offset = ch * ch_block_step; size_t ddst_off = sp_offset + ch_offset; Zmm zmm_acc = get_acc_reg(ch * ur_str_w + w); Zmm mm_zmm_dst // mm: maybe masked = mask_flag ? zmm_dst_reg | k_ch_tail_mask | T_z : zmm_dst_reg; vpmovzxwd(mm_zmm_dst, ptr[aux1_reg_ddst + ddst_off * jcp.typesize_in]); if (isa_has_bf16(jcp.isa)) vdpbf16ps(zmm_acc, mm_zmm_ker, mm_zmm_dst); else bf16_emu_->vdpbf16ps(zmm_acc, mm_zmm_dst, mm_zmm_ker); } } add(aux1_reg_kernel, ch_blk * stride_w * jcp.typesize_in); sub(aux1_reg_ddst, sp_step * jcp.typesize_in); sub(iter_kw, stride_w); cmp(iter_kw, 0); jg(kw_label, T_NEAR); } add(aux_reg_kernel, kw * ch_blk * stride_h * jcp.typesize_in); sub(aux_reg_ddst, ow * sp_step * jcp.typesize_in); sub(iter_kh, stride_h); cmp(iter_kh, 0); jg(kh_label, T_NEAR); } L(iter_exit_label); } void jit_avx512_dw_conv_bwd_data_kernel_bf16::apply_postprocess(int ur_ch_blocks, int ur_str_) { const auto& p = attr_.post_ops_; std::size_t post_ops_data_offset = 0; int depthwise_inj_idx = 0; for (int i = 0; i < p.len(); i++) { auto& post_op = p.entry_[i]; if (post_op.is_depthwise()) { mov(reg_d_weights, ptr[this->rsp + base_post_ops_data_offset + post_ops_data_offset]); add(reg_d_weights, ptr[this->param1 + GET_OFF(ic_off)]); for (int ch = 0; ch < ur_ch_blocks; ch++) { int start_idx = get_acc_reg(ur_str_ * ch).getIdx(); int end_idx = get_acc_reg(ur_str_ * ch + ur_str_).getIdx(); depthwise_injectors[depthwise_inj_idx]->compute_vector_range( start_idx, end_idx, reg_d_weights, reg_d_weights); add(reg_d_weights, jcp.ch_block * sizeof(float)); } post_ops_data_offset += depthwise_injectors[depthwise_inj_idx]->memoryStep(); depthwise_inj_idx++; } } } inline void jit_avx512_dw_conv_bwd_data_kernel_bf16::store_dsrc( int ur_ch_blocks, int ur_str_w, bool last_ch_block_flag) { int ch_blk = jcp.ch_block; int iw = jcp.iw; int ih = jcp.ih; int stride_w = jcp.stride_w; const auto dsrc_layout_nxc = is_dsrc_layout_nxc(); const size_t ch_block_step = ch_blk * (dsrc_layout_nxc ? 1 : ih * iw); const size_t sp_step = dsrc_layout_nxc ? jcp.ngroups : ch_blk; if (jcp.dsrc_dt == data_type::bf16 && !isa_has_bf16(jcp.isa)) bf16_emu_->init_vcvtneps2bf16(); for (int ch = 0; ch < ur_ch_blocks; ch++) { const bool mask_flag = last_ch_block_flag && ch == ur_ch_blocks - 1; for (int w = 0; w < ur_str_w; w++) { size_t sp_offset = w * stride_w * sp_step; size_t ch_offset = ch * ch_block_step; int dsrc_off = sp_offset + ch_offset; auto zmm_dsrc = get_acc_reg(ch * ur_str_w + w); Zmm mm_zmm_dsrc // mm: maybe masked = mask_flag ? zmm_dsrc | k_ch_tail_mask : zmm_dsrc; if (jcp.dsrc_dt == data_type::f32) { uni_vmovups(ptr[reg_dsrc + dsrc_off * jcp.typesize_out], mm_zmm_dsrc); } else if (jcp.dsrc_dt == data_type::bf16) { auto ymm_dsrc = Ymm(zmm_dsrc.getIdx()); Ymm mm_ymm_dsrc // mm: maybe masked = mask_flag ? ymm_dsrc | k_ch_tail_mask : ymm_dsrc; if (isa_has_bf16(jcp.isa)) vcvtneps2bf16(mm_ymm_dsrc, mm_zmm_dsrc); else bf16_emu_->vcvtneps2bf16(mm_ymm_dsrc, mm_zmm_dsrc); vmovdqu16(ptr[reg_dsrc + dsrc_off * jcp.typesize_out], mm_ymm_dsrc); } } } /* Note: current 'store_dsrc' is limited to storing 'ymm' output. This is * because of the current implementation approach that calculates convolution as * a strided backward-pass. To increase store throughput by writing 'zmm' * registers, changes are needed in both JIT-kernel and Driver code. */ } inline void jit_avx512_dw_conv_bwd_data_kernel_bf16::ch_loop_body( int ur_ch_blocks, int unroll_w) { auto call_compute_body = [&](int ur_ch_blocks, int unroll_w, bool is_last_ch = false) { mov(aux_reg_ddst, reg_ddst); mov(aux_reg_kernel, reg_kernel); load_ddst(ur_ch_blocks, unroll_w); apply_filter(ur_ch_blocks, unroll_w, is_last_ch); apply_postprocess(ur_ch_blocks, unroll_w); store_dsrc(ur_ch_blocks, unroll_w, is_last_ch); }; const bool write_ch_loop = ur_ch_blocks > jcp.nb_ch_blocking; if (write_ch_loop) { assert(is_ddst_layout_nxc() && is_dsrc_layout_nxc()); Label ch_loop_label, ch_tail_label, skip_ch_tail_label; const int nb_oc = jcp.oc / jcp.ch_block; const int ch_block_tail = jcp.nb_ch - (utils::rnd_dn(nb_oc, jcp.nb_ch_blocking)); const int ch_step = jcp.nb_ch_blocking * jcp.ch_block; const size_t wei_ch_stride = (size_t)jcp.nb_ch_blocking * jcp.kh * jcp.kw * jcp.ch_block; const size_t data_ch_stride = (size_t)jcp.nb_ch_blocking * jcp.ch_block; mov(aux_reg_ch_blocks, reg_ch_blocks); base_post_ops_data_offset += 3 * reg64_size; push(reg_dsrc); push(reg_ddst); push(reg_kernel); if (nb_oc >= jcp.nb_ch_blocking) { if (ch_block_tail) { cmp(aux_reg_ch_blocks, jcp.nb_ch_blocking * jcp.ch_block); jl(ch_tail_label, T_NEAR); } L(ch_loop_label); { call_compute_body(jcp.nb_ch_blocking, unroll_w); add(reg_kernel, wei_ch_stride * jcp.typesize_in); add(reg_dsrc, data_ch_stride * jcp.typesize_out); add(reg_ddst, data_ch_stride * jcp.typesize_in); sub(aux_reg_ch_blocks, ch_step); cmp(aux_reg_ch_blocks, ch_step); jge(ch_loop_label, T_NEAR); } } if (ch_block_tail) { // ch work range [1, jcp.nb_ch_blocking * ch_block) L(ch_tail_label); cmp(aux_reg_ch_blocks, 0); jle(skip_ch_tail_label, T_NEAR); call_compute_body(ch_block_tail, unroll_w, jcp.ch_tail); L(skip_ch_tail_label); } pop(reg_kernel); pop(reg_ddst); pop(reg_dsrc); base_post_ops_data_offset -= 3 * reg64_size; } else { call_compute_body(ur_ch_blocks, unroll_w, jcp.ch_tail); } } inline void jit_avx512_dw_conv_bwd_data_kernel_bf16::unroll_width_body( int ur_ch_blocks) { auto unroll_width_loop = [&](int unroll_w) { Label unroll_w_label, skip_compute_label; L(unroll_w_label); { const size_t ch_step = unroll_w * (is_ddst_layout_nxc() ? jcp.ngroups : jcp.ch_block); cmp(reg_ur_str_w, unroll_w); jl(skip_compute_label, T_NEAR); ch_loop_body(ur_ch_blocks, unroll_w); add(reg_dsrc, jcp.typesize_out * jcp.stride_w * ch_step); add(reg_ddst, jcp.typesize_in * ch_step); sub(reg_ur_str_w, unroll_w); jmp(unroll_w_label); } L(skip_compute_label); }; unroll_width_loop(jcp.ur_w); unroll_width_loop(1); } void jit_avx512_dw_conv_bwd_data_kernel_bf16::generate() { assert(is_dsrc_layout_nxc() == is_ddst_layout_nxc()); const auto& p = attr_.post_ops_; for (int i = 0; i < p.len(); i++) { auto& post_op = p.entry_[i]; if (post_op.is_depthwise()) { depthwise_injectors.push_back(new jit_uni_depthwise_injector_f32( this, post_op )); } } preamble(); std::size_t post_ops_pointers_count = 0; for (int i = 0; i < p.len(); i++) { if (p.entry_[i].is_depthwise() || p.entry_[i].is_quantization()) { post_ops_pointers_count++; } } if (post_ops_pointers_count != 0) { sub(rsp, post_ops_pointers_count * sizeof(float *)); auto aux_reg0 = reg_dsrc; auto aux_reg1 = reg_ddst; mov(aux_reg0, ptr[this->param1 + GET_OFF(post_ops_binary_rhs_arg_vec)]); for (size_t i = 0; i < post_ops_pointers_count; i++) { mov(aux_reg1, ptr[aux_reg0 + i * sizeof(float *)]); mov(ptr[rsp + i * sizeof(float *)], aux_reg1); } } mov(reg_dsrc, ptr[this->param1 + GET_OFF(src)]); mov(reg_ddst, ptr[this->param1 + GET_OFF(dst)]); mov(reg_kernel, ptr[this->param1 + GET_OFF(filt)]); mov(reg_kh, ptr[this->param1 + GET_OFF(kh_padding)]); mov(reg_kw, ptr[this->param1 + GET_OFF(kw_padding)]); mov(reg_ch_blocks, ptr[this->param1 + GET_OFF(ch_blocks)]); mov(reg_ur_str_w, ptr[this->param1 + GET_OFF(ur_str_w)]); if (is_dsrc_layout_nxc()) { if (jcp.ch_tail) { Label masking_done; const size_t channel_step = jcp.nb_ch_blocking * jcp.ch_block; kxnorw(k_ch_tail_mask, k_ch_tail_mask, k_ch_tail_mask); // dummy mask all 1's cmp(reg_ch_blocks, channel_step); je(masking_done, T_NEAR); // Prepare masks for tail Reg32 reg_tmp_32 = reg_tmp.cvt32(); mov(reg_tmp_32, (1 << jcp.ch_tail) - 1); kmovw(k_ch_tail_mask, reg_tmp_32); L(masking_done); } unroll_width_body(jcp.nb_ch); } else { auto ch_blocks_loop = [&](int ch_blocks) { Label skip_loop_label; cmp(reg_ch_blocks, ch_blocks * jcp.ch_block); jl(skip_loop_label, T_NEAR); unroll_width_body(ch_blocks); L(skip_loop_label); }; ch_blocks_loop(jcp.nb_ch_blocking); int ch_blocks_tail = jcp.nb_ch % jcp.nb_ch_blocking; if (ch_blocks_tail) { ch_blocks_loop(ch_blocks_tail); } } if (post_ops_pointers_count != 0) { add(rsp, post_ops_pointers_count * sizeof(float *)); } postamble(); } #undef GET_OFF #define GET_OFF(field) offsetof(jit_dw_conv_call_s, field) void jit_avx512_dw_conv_bwd_weights_kernel_bf16::zero_filter() { for (int i = 0; i < jcp.kw; ++i) { Zmm zmm_acc = get_acc_reg(i); uni_vpxor(zmm_acc, zmm_acc, zmm_acc); } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::load_filter(bool is_last_ch) { for (int i = 0; i < jcp.kw; ++i) { int off_filter = i * jcp.ch_block; Zmm zmm_acc = get_acc_reg(i); Zmm m_zmm_acc = is_last_ch ? zmm_acc | k_ch_tail_mask | T_z : zmm_acc; vmovups(m_zmm_acc, vmmword[reg_tmp_filter + off_filter * jcp.typesize_out]); } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::zero_bias() { uni_vpxor(zmm_bias_reg, zmm_bias_reg, zmm_bias_reg); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::load_bias(bool is_last_ch) { Zmm m_zmm_bias_reg = is_last_ch ? zmm_bias_reg | k_ch_tail_mask | T_z : zmm_bias_reg; vmovups(m_zmm_bias_reg, vmmword[reg_bias_baddr]); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_ow_step_unroll( int unroll_w, int l_pad, int pad_offset, int ow_block, bool is_last_ch) { const size_t ch_step = is_layout_nxc() ? jcp.ngroups : jcp.ch_block; const int iw_block = ow_block * jcp.stride_w; const int right_border = jcp.iw - iw_block; const int r_pad = jcp.r_pad; const int cascade_input = nstl::min(jcp.stride_w, jcp.kw); /* preamble count for number of cascaded LOAD + FMA operation */ const int input_overlap = nstl::max(jcp.kw - l_pad, 0); const bool is_last_block = (unroll_w + ow_block == jcp.ow); /* LOAD initial input registers, then cascade LOADs and FMAs*/ for (int i_ur = 0; i_ur < unroll_w; ++i_ur) { size_t off_output = static_cast(i_ur * ch_step * jcp.typesize_in); Zmm m_zmm_out_reg = is_last_ch ? zmm_out_reg | k_ch_tail_mask | T_z : zmm_out_reg; vpmovzxwd(m_zmm_out_reg, ptr[reg_tmp_output + off_output]); if (i_ur == 0) { for (int c = 0; c < input_overlap; ++c) { int input_sp = c - pad_offset; if (input_sp < 0 && unroll_w == jcp.ow) continue; const bool over_steps_bdry = true && is_last_block && (c - pad_offset + r_pad > right_border); if (over_steps_bdry) continue; size_t input_offset = static_cast( input_sp * ch_step * jcp.typesize_in); Zmm zmm_input = get_input_reg(c); Zmm m_zmm_input = is_last_ch ? zmm_input | k_ch_tail_mask | T_z : zmm_input; vpmovzxwd(m_zmm_input, ptr[reg_tmp_input + input_offset]); } } else { for (int c = 0; c < cascade_input; ++c) { int overlap = (i_ur - 1) * jcp.stride_w + input_overlap; int input_sp = overlap + c - pad_offset; if (input_sp < 0 || overlap + c + l_pad > right_border) continue; const bool over_steps_bdry = true && is_last_block && (overlap + c - pad_offset + r_pad > right_border); if (over_steps_bdry) continue; size_t input_offset = static_cast( input_sp * ch_step * jcp.typesize_in); Zmm zmm_input = get_input_reg(overlap + c); Zmm m_zmm_input = is_last_ch ? zmm_input | k_ch_tail_mask | T_z : zmm_input; vpmovzxwd(m_zmm_input, ptr[reg_tmp_input + input_offset]); } } for (int i_kw = 0; i_kw < jcp.kw; ++i_kw) { int io_overlap = i_kw + (i_ur * jcp.stride_w); /* Don't apply FMAs that fall into the padded region */ if (io_overlap - l_pad < 0 || io_overlap - jcp.l_pad >= right_border) continue; const bool over_steps_bdry = true && is_last_block && (io_overlap - jcp.l_pad + jcp.r_pad > right_border); if (over_steps_bdry) continue; Zmm zmm_input = get_input_reg(io_overlap - l_pad); Zmm zmm_acc = get_acc_reg(i_kw); if (isa_has_bf16(jcp.isa)) vdpbf16ps(zmm_acc, zmm_input, zmm_out_reg); else bf16_emu_->vdpbf16ps(zmm_acc, zmm_input, zmm_out_reg); } } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_bias_step_unroll( const int unroll_w, bool is_last_ch) { const int ch_step = is_ddst_layout_nxc() ? jcp.ngroups : jcp.ch_block; for (int i = 0; i < unroll_w; ++i) { size_t off_output = static_cast(i * ch_step * jcp.typesize_in); /* bf16 output data requires conversion to f32 */ Zmm m_zmm_out_reg = is_last_ch ? zmm_out_reg | k_ch_tail_mask | T_z : zmm_out_reg; vpmovzxwd(m_zmm_out_reg, ptr[reg_tmp_output + off_output]); vpslld(m_zmm_out_reg, m_zmm_out_reg, 0x10); vaddps(zmm_bias_reg, zmm_bias_reg, m_zmm_out_reg); } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::store_filter(bool is_last_ch) { /* bf16: all data is stored as f32. Down-convert to bf16 happens at the * reduction phase. */ for (int i = 0; i < jcp.kw; ++i) { int off_filter = i * jcp.ch_block; Zmm zmm_acc = get_acc_reg(i); Zmm m_zmm_acc = is_last_ch ? zmm_acc | k_ch_tail_mask : zmm_acc; vmovups(vmmword[reg_tmp_filter + off_filter * jcp.typesize_out], m_zmm_acc); } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::store_bias(bool is_last_ch) { Zmm m_zmm_bias_reg = is_last_ch ? zmm_bias_reg | k_ch_tail_mask : zmm_bias_reg; vmovups(vmmword[reg_bias_baddr], m_zmm_bias_reg); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_spatial_loop_bias( bool is_last_ch) { Label oh_label; Label ow_blk_label; const int unroll_w = nstl::min(max_unroll_w_, jcp.ow); const int unroll_w_trips = jcp.ow / unroll_w; const int tail_w = jcp.ow > max_unroll_w_ ? jcp.ow % max_unroll_w_ : 0; const size_t ch_step = is_layout_nxc() ? jcp.ngroups : jcp.ch_block; const size_t ch_offset = ch_step * jcp.typesize_in; mov(reg_oh, ptr[this->param1 + GET_OFF(oh_index)]); mov(reg_oh_worksize, ptr[this->param1 + GET_OFF(oh_count)]); mov(reg_tmp_output, reg_output_baddr); L(oh_label); { mov(reg_iter_ow_blk, unroll_w_trips); L(ow_blk_label); { compute_bias_step_unroll(unroll_w, is_last_ch); add(reg_tmp_output, unroll_w * ch_offset); dec(reg_iter_ow_blk); cmp(reg_iter_ow_blk, 0); jg(ow_blk_label, T_NEAR); } if (tail_w > 0) { compute_bias_step_unroll(tail_w, is_last_ch); add(reg_tmp_output, tail_w * ch_offset); } inc(reg_oh); cmp(reg_oh, reg_oh_worksize); jl(oh_label, T_NEAR); } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16:: compute_single_ch_block_bias() { auto write_compute_bias = [&](bool masked_ch_tail) { Label skip_load_bias; mov(reg_exec_flags, ptr[this->param1 + GET_OFF(exec_flags)]); and_(reg_exec_flags, FLAG_ZERO_BIAS); test(reg_exec_flags, reg_exec_flags); jne(skip_load_bias); load_bias(masked_ch_tail); L(skip_load_bias); compute_spatial_loop_bias(masked_ch_tail); store_bias(masked_ch_tail); }; Label skip_masked_bias_label, done_bias_label; zero_bias(); bool do_bias_ch_tail = jcp.ch_tail > 0; if (do_bias_ch_tail) { // test last channel mov(reg_exec_flags, ptr[this->param1 + GET_OFF(exec_flags)]); and_(reg_exec_flags, FLAG_OC_LAST); test(reg_exec_flags, reg_exec_flags); jz(skip_masked_bias_label, T_NEAR); write_compute_bias(true); jmp(done_bias_label, T_NEAR); L(skip_masked_bias_label); } write_compute_bias(false); L(done_bias_label); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_ch_loop_bias( bool do_load_bias) { assert(is_ddst_layout_nxc()); auto write_compute_bias = [&](bool masked_ch_tail) { if (do_load_bias) load_bias(masked_ch_tail); else zero_bias(); compute_spatial_loop_bias(masked_ch_tail); store_bias(masked_ch_tail); }; bool masked_ch_tail = jcp.ch_tail > 0; if (jcp.nb_ch > 1) { Label last_ch_block_label, ch_block_done_label; if (masked_ch_tail) { mov(reg_exec_flags, ptr[this->param1 + GET_OFF(exec_flags)]); and_(reg_exec_flags, FLAG_OC_LAST); test(reg_exec_flags, reg_exec_flags); jnz(last_ch_block_label, T_NEAR); } write_compute_bias(false); if (masked_ch_tail) { jmp(ch_block_done_label, T_NEAR); L(last_ch_block_label); write_compute_bias(true); L(ch_block_done_label); } } else { write_compute_bias(masked_ch_tail); } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::deploy_ch_loop_bias() { Label ch_loop_label, zero_bias_label, load_bias_done_label; mov(reg_exec_flags, ptr[this->param1 + GET_OFF(exec_flags)]); and_(reg_exec_flags, FLAG_ZERO_BIAS); test(reg_exec_flags, reg_exec_flags); jne(zero_bias_label, T_NEAR); compute_ch_loop_bias(true); // load_bias jmp(load_bias_done_label, T_NEAR); L(zero_bias_label); compute_ch_loop_bias(false); // zero_bias L(load_bias_done_label); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_bias() { mov(reg_bias_baddr, ptr[this->param1 + GET_OFF(bias)]); if (is_ddst_layout_nxc()) deploy_ch_loop_bias(); else compute_single_ch_block_bias(); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::zero_filter_kh_loop() { const size_t filter_offset_kw = jcp.kw * jcp.ch_block * jcp.typesize_out; const size_t filter_offset_kh = jcp.kh * filter_offset_kw; Label kh_loop_label; mov(reg_kh_aux, jcp.kh); L(kh_loop_label); { store_filter(); add(reg_tmp_filter, filter_offset_kw); dec(reg_kh_aux); cmp(reg_kh_aux, 0); jg(kh_loop_label, T_NEAR); } /* Comeback pointers */ sub(reg_tmp_filter, filter_offset_kh); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::deploy_zero_filter() { Label skip_zeroing_label; mov(reg_exec_flags, ptr[this->param1 + GET_OFF(exec_flags)]); and_(reg_exec_flags, FLAG_ZERO_FILTER); test(reg_exec_flags, reg_exec_flags); je(skip_zeroing_label, T_NEAR); zero_filter(); mov(reg_tmp_filter, reg_filter_baddr); zero_filter_kh_loop(); L(skip_zeroing_label); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_kh_step(int unroll_w, int l_pad, int pad_offset, int ow_block, bool is_last_ch) { const size_t ch_step = is_layout_nxc() ? jcp.ngroups : jcp.ch_block; const size_t input_offset = jcp.iw * ch_step * jcp.typesize_in; const size_t filter_offset = jcp.kw * jcp.ch_block * jcp.typesize_out; Label kh_loop_label, skip_loop_label; cmp(reg_kh, 0); je(skip_loop_label, T_NEAR); mov(reg_kh_aux, reg_kh); L(kh_loop_label); { load_filter(); compute_ow_step_unroll( unroll_w, l_pad, pad_offset, ow_block, is_last_ch); store_filter(); add(reg_tmp_filter, filter_offset); add(reg_tmp_input, input_offset); dec(reg_kh_aux); cmp(reg_kh_aux, 0); jg(kh_loop_label, T_NEAR); } /* Comeback pointers */ Label kh_comeback_label; mov(reg_kh_aux, reg_kh); L(kh_comeback_label); { sub(reg_tmp_input, input_offset); sub(reg_tmp_filter, filter_offset); dec(reg_kh_aux); cmp(reg_kh_aux, 0); jg(kh_comeback_label, T_NEAR); } L(skip_loop_label); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_ch_loop( int unroll_w, int l_pad, int pad_offset, int ow_block) { const bool masked_ch_tail = is_layout_nxc() && jcp.ch_tail > 0; bool write_channel_loop = is_layout_nxc() && jcp.nb_ch > 1; if (write_channel_loop) { Label last_ch_block_label, ch_block_done_label; if (masked_ch_tail) { mov(reg_exec_flags, ptr[this->param1 + GET_OFF(exec_flags)]); and_(reg_exec_flags, FLAG_OC_LAST); test(reg_exec_flags, reg_exec_flags); jnz(last_ch_block_label, T_NEAR); } compute_kh_step(unroll_w, l_pad, pad_offset, ow_block, false); if (masked_ch_tail) { jmp(ch_block_done_label, T_NEAR); L(last_ch_block_label); compute_kh_step(unroll_w, l_pad, pad_offset, ow_block, true); L(ch_block_done_label); } } else { compute_kh_step(unroll_w, l_pad, pad_offset, ow_block, masked_ch_tail); } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_h_loop( int unroll_w, int l_pad, int pad_offset, int ow_block) { mov(reg_tmp_output, reg_output_baddr); mov(reg_tmp_input, reg_input_baddr); mov(reg_tmp_filter, reg_filter_baddr); const int input_bottom_padding_overlap = div_up(jcp.ih + jcp.t_pad - (jcp.kh - 1), jcp.stride_h); const size_t ch_step = is_layout_nxc() ? jcp.ngroups : jcp.ch_block; const size_t input_shift = jcp.typesize_in * jcp.iw * ch_step; const size_t output_shift = jcp.typesize_in * jcp.ow * ch_step; const size_t filter_shift = jcp.typesize_out * jcp.kw * jcp.ch_block; Label loop_begin_label, loop_end_label, common_block_label, top_padding_end_label, bottom_padding_end_label, bottom_padding_label; mov(reg_oh, ptr[this->param1 + GET_OFF(oh_index)]); mov(reg_kh, ptr[this->param1 + GET_OFF(kh_count)]); // replacement for 'os_index_end' mov(reg_oh_worksize, ptr[this->param1 + GET_OFF(oh_count)]); cmp(reg_kh, 0); jle(loop_end_label, T_NEAR); // no iterations along kh cmp(reg_oh, reg_oh_worksize); jge(loop_end_label, T_NEAR); // no iterations along height dimension L(loop_begin_label); compute_ch_loop(unroll_w, l_pad, pad_offset, ow_block); /* Compute 'top' edge */ if (jcp.t_pad > 0) { /* Check if within top padding region */ cmp(reg_oh, div_up(jcp.t_pad, jcp.stride_h)); jge(top_padding_end_label, T_NEAR); /* Increment step counter and adjust filter position */ sub(reg_tmp_filter, filter_shift * jcp.stride_h); add(reg_kh, jcp.stride_h); /* Final number of kernel elements that overlap with input */ const int inp_ker_overlap = nstl::min(jcp.kh, jcp.ih); cmp(reg_kh, inp_ker_overlap); jle(common_block_label, T_NEAR); /* Correct any excess shifts to kernel and input */ if (jcp.t_pad <= jcp.oh * jcp.stride_h) { /* Filter has moved beyond padding (adjust for stride effects) */ if (jcp.t_pad % jcp.stride_h != 0) { int inp_corr = jcp.stride_h - jcp.t_pad % jcp.stride_h; add(reg_tmp_filter, filter_shift * inp_corr); add(reg_tmp_input, input_shift * inp_corr); } } else { /* Filter still overlaps padding (complete reset) */ sub(reg_tmp_filter, (jcp.t_pad - jcp.oh * jcp.stride_h) * filter_shift); } /* Apply correction: reset value of 'reg_kh' to scenario outside of * special cases due to top_padding (i.e. 'min(jcp.kh, jcp.ih)')*/ mov(reg_kh, inp_ker_overlap); jmp(common_block_label); L(top_padding_end_label); } /* Compute 'bottom' edge */ if (jcp.b_pad > 0) { /* Check if within bottom padding region */ cmp(reg_oh, input_bottom_padding_overlap - 1); jl(bottom_padding_end_label, T_NEAR); jg(bottom_padding_label, T_NEAR); /* Execute overlap correction between the filter and the initial * bottom padding region. */ mov(reg_kh, jcp.ih + jcp.t_pad - input_bottom_padding_overlap * jcp.stride_h); jmp(bottom_padding_end_label, T_NEAR); L(bottom_padding_label); sub(reg_kh, jcp.stride_h); cmp(reg_kh, 0); jle(loop_end_label, T_NEAR); L(bottom_padding_end_label); } /* Compute middle block */ add(reg_tmp_input, input_shift * jcp.stride_h); /* Execute common block and loop */ L(common_block_label); add(reg_tmp_output, output_shift); inc(reg_oh); cmp(reg_oh, reg_oh_worksize); jl(loop_begin_label, T_NEAR); L(loop_end_label); } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::calculate_w_unrolling( int &unroll_trips, int &unroll_w, int &unroll_w_tail) { const bool do_unroll_w = jcp.ow > max_unroll_w_; if (do_unroll_w) { unroll_w = nstl::min(block_size_, jcp.ow); unroll_trips = jcp.ow / unroll_w; /* calculate tail */ unroll_w_tail = jcp.ow % unroll_w; /* Perform some rebalancing if tail too small*/ if ((unroll_w_tail == 0 && jcp.r_pad != 0) || (jcp.r_pad > 0 && jcp.r_pad >= unroll_w_tail)) { if (unroll_trips > 1) { unroll_w_tail += unroll_w; unroll_trips--; } else { /* Idealy, this case shouldn't happen */ unroll_w_tail += (unroll_w - unroll_w / 2); unroll_w = unroll_w / 2; } } } else { unroll_w_tail = jcp.ow; } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::compute_ow_block_unroll() { Label ow_blk_label; // for compute middle block int pad_offset = 0; int l_pad = jcp.l_pad; int unroll_w_tail = 0; int unroll_w = 0; int unroll_trips = 0; calculate_w_unrolling(unroll_trips, unroll_w, unroll_w_tail); const size_t ch_offset = is_layout_nxc() ? jcp.ngroups : jcp.ch_block; const size_t data_offset = static_cast(unroll_w * ch_offset * jcp.typesize_in); if (jcp.with_bias) compute_bias(); /* Pass filter address, then offset for h_padding. */ deploy_zero_filter(); mov(reg_kh_offset, ptr[this->param1 + GET_OFF(filter_pad_off)]); add(reg_filter_baddr, reg_kh_offset); /* compute left padded block */ const bool do_unroll_w = jcp.ow > max_unroll_w_; if (l_pad && do_unroll_w) { compute_h_loop(unroll_w, l_pad, 0, 0); add(reg_output_baddr, data_offset); add(reg_input_baddr, data_offset * jcp.stride_w); unroll_trips--; pad_offset = l_pad; l_pad = 0; } /* Insert loop for 'ow' block when middle block needs to execute more * than once */ bool do_ow_blk_loop = unroll_trips > 1; if (do_ow_blk_loop) { mov(reg_iter_ow_blk, unroll_trips); L(ow_blk_label); } if (unroll_trips > 0) { compute_h_loop(unroll_w, l_pad, pad_offset, 0); add(reg_output_baddr, data_offset); add(reg_input_baddr, data_offset * jcp.stride_w); } if (do_ow_blk_loop) { dec(reg_iter_ow_blk); cmp(reg_iter_ow_blk, 0); jg(ow_blk_label, T_NEAR); } /* compute right padded block */ if (unroll_w_tail) { compute_h_loop( unroll_w_tail, l_pad, pad_offset, jcp.ow - unroll_w_tail); } } void jit_avx512_dw_conv_bwd_weights_kernel_bf16::generate() { assert(is_src_layout_nxc() == is_ddst_layout_nxc()); preamble(); mov(reg_input_baddr, ptr[this->param1 + GET_OFF(input)]); mov(reg_output_baddr, ptr[this->param1 + GET_OFF(output)]); mov(reg_filter_baddr, ptr[this->param1 + GET_OFF(filter)]); bool set_kmask = jcp.ch_tail > 0 && (jcp.with_bias || is_layout_nxc()); if (set_kmask) { // Prepare masks for tail Reg32 reg_tmp_32 = reg_tmp.cvt32(); mov(reg_tmp_32, (1 << jcp.ch_tail) - 1); kmovw(k_ch_tail_mask, reg_tmp_32); } compute_ow_block_unroll(); postamble(); } #undef GET_OFF } // namespace x64 } // namespace cpu } // namespace impl } // namespace dnnl ",16136,True,3162.520726731673,median " [[springSpringBoot]] === Spring Boot Spring Boot is an application framework which, according to link:$$http://projects.spring.io/spring-boot/$$[its website], _makes it easy to create stand-alone, production-grade Spring based Applications that you can ""just run"". It takes an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration_. For more information on Spring Boot, see link:$$http://projects.spring.io/spring-boot/$$[http://projects.spring.io/spring-boot/] The Spring Boot - Flowable integration has been developed together with Spring committers. ==== Compatibility Flowable supports both Spring Boot 2.0 and 1.5 with the same starters. The base support is for Spring Boot 2.0, which means that the actuator endpoints are only supported on 2.0. The Flowable starters are also puling spring boot starter transitively, which means that users will have to define the 1.5 version of the spring boot starters in their own build files. [[springSpringBootGettingStarted]] ==== Getting started Spring Boot is all about convention over configuration. To get started, you would need to create a Spring Boot project. The easiest way to do this would be to create a project via link:$$https://start.spring.io/$$[start.spring.io]. For example create a project with web and h2 dependencies. Then in the created project simply add the _flowable-spring-boot-starter_ or _flowable-spring-boot-starter-rest_ dependency. In case you don't need all the engines see the other <>. For example for Maven: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter ${flowable.version} ---- That's all that's needed. This dependency will transitively add the correct Flowable dependencies to the classpath. You can now run your Spring Boot application: [source,java,,linenums] ---- import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(proxyBeanMethods = false) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ---- You will see an output like this: ---- . ____ _ __ _ _ /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\ ( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\ \\\\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.0.RELEASE) MyApplication : Starting MyApplication on ... MyApplication : No active profile set, falling back to default profiles: default ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4fdfa676: startup date [Wed Mar 28 12:04:00 CEST 2018]; root of context hierarchy o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) o.apache.catalina.core.StandardService : Starting service [Tomcat] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28 o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3085 ms o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable IDM Rest API mapped to [/idm-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable Form Rest API mapped to [/form-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable DMN Rest API mapped to [/dmn-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable Content Rest API mapped to [/content-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable CMMN Rest API mapped to [/cmmn-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable BPMN Rest API mapped to [/process-api/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] uration$$EnhancerBySpringCGLIB$$3d0c70ac : No deployment resources were found for autodeployment uration$$EnhancerBySpringCGLIB$$8131eb1a : No deployment resources were found for autodeployment o.f.e.i.c.ProcessEngineConfigurationImpl : Found 5 Engine Configurators in total: o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) .d.AbstractSqlScriptBasedDbSchemaManager : performing create on identity with resource org/flowable/idm/db/create/flowable.h2.create.identity.sql o.f.idm.engine.impl.IdmEngineImpl : IdmEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.dmn.engine.impl.DmnEngineImpl : DmnEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.form.engine.impl.FormEngineImpl : FormEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.c.engine.ContentEngineConfiguration : Content file system root : ... o.f.c.engine.impl.ContentEngineImpl : ContentEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) o.f.cmmn.engine.CmmnEngineConfiguration : Found 1 Engine Configurators in total: o.f.cmmn.engine.CmmnEngineConfiguration : class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.cmmn.engine.CmmnEngineConfiguration : Executing beforeInit() of class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.cmmn.engine.CmmnEngineConfiguration : Executing configure() of class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.idm.engine.impl.IdmEngineImpl : IdmEngine default created o.f.cmmn.engine.impl.CmmnEngineImpl : CmmnEngine default created o.f.engine.impl.ProcessEngineImpl : ProcessEngine default created o.f.j.s.i.a.AbstractAsyncExecutor : Starting up the async job executor [org.flowable.spring.job.service.SpringAsyncExecutor]. o.f.j.s.i.a.AcquireAsyncJobsDueRunnable : starting to acquire async jobs due o.f.j.s.i.a.AcquireTimerJobsRunnable : starting to acquire async jobs due o.f.j.s.i.a.ResetExpiredJobsRunnable : starting to reset expired jobs o.f.e.impl.cmd.ValidateV5EntitiesCmd : Total of v5 deployments found: 0 s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4fdfa676: startup date [Wed Mar 28 12:04:00 CEST 2018]; root of context hierarchy s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped ""{[/error]}"" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped ""{[/error],produces=[text/html]}"" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -20 o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 20 o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' flowable.Application : Started Application in 18.235 seconds (JVM running for 19.661) ---- So, by just adding the dependency to the classpath and using the _@SpringBootAplication_ annotation a lot has happened behind the scenes: * An in-memory datasource is created automatically (because the H2 driver is on the classpath) and passed to the Flowable process engine configuration * A Flowable ProcessEngine, CmmnEngine, DmnEngine, FormEngine, ContentEngine and IdmEngine beans have been created and exposed * All the Flowable services are exposed as Spring beans * The Spring Job Executor is created Also: * Any BPMN 2.0 process definitions in the _processes_ folder will be automatically deployed. Create a folder _processes_ and add a dummy process definition (named _one-task-process.bpmn20.xml_) to this folder. The content of this file is shown below. * Any CMMN 1.1 case definitions in the _cases_ folder will be automatically deployed. * Any DMN 1.1 dmn definitions in the _dmn_ folder will be automatically deployed. * Any Form definitions in the _forms_ folder will be automatically deployed. The XML content of the process definition is shown below. Notice that, for the moment, we are hard-coding an assignee called ""kermit"" to the user task. We'll come back to this later. [source,xml,linenums] ---- ---- Also, add following code lines to test if the deployment actually worked. The _CommandLineRunner_ is a special kind of Spring bean that is executed when the application boots: [source,java,linenums] ---- @SpringBootApplication(proxyBeanMethods = false) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public CommandLineRunner init(final RepositoryService repositoryService, final RuntimeService runtimeService, final TaskService taskService) { return new CommandLineRunner() { @Override public void run(String... strings) throws Exception { System.out.println(""Number of process definitions : "" + repositoryService.createProcessDefinitionQuery().count()); System.out.println(""Number of tasks : "" + taskService.createTaskQuery().count()); runtimeService.startProcessInstanceByKey(""oneTaskProcess""); System.out.println(""Number of tasks after process start: "" + taskService.createTaskQuery().count()); } }; } } ---- The output expected will be: ---- Number of process definitions : 1 Number of tasks : 0 Number of tasks after process start : 1 ---- ==== Changing the database and connection pool As stated above, Spring Boot is about convention over configuration. By default, by having only H2 on the classpath, it created an in-memory datasource and passed that to the Flowable process engine configuration. To change the datasource, simply add the database driver dependencies and provide the URL to the database. For example, to switch to a MySQL database: [source,linenums] ---- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable-spring-boot?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- Remove H2 from the Maven dependencies and add the MySQL driver to the classpath: [source,xml,linenums] ---- mysql mysql-connector-java 5.1.45 ---- When the app is now booted up, you'll see it uses MySQL as database (and the HikariCP connection pooling framework): ---- org.flowable.engine.impl.db.DbSqlSession : performing create on engine with resource org/flowable/db/create/flowable.mysql.create.engine.sql org.flowable.engine.impl.db.DbSqlSession : performing create on history with resource org/flowable/db/create/flowable.mysql.create.history.sql org.flowable.engine.impl.db.DbSqlSession : performing create on identity with resource org/flowable/db/create/flowable.mysql.create.identity.sql ---- When you reboot the application multiple times, you'll see the number of tasks go up (the H2 in-memory database does not survive a shutdown, MySQL does). For more information about how to configure the datasource have a look in link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-configure-datasource$$[Configure a DataSource] in the Spring Boot reference guide. ==== REST support Often, a REST API is used on top of the embedded Flowable engine (interacting with the different services in a company). Spring Boot makes this really easy. Add following dependency to the classpath: [source,xml,linenums] ---- org.springframework.boot spring-boot-starter-web ${spring.boot.version} ---- Create a new class, a Spring service and create two methods: one to start our process and one to get a task list for a given assignee. We simply wrap Flowable calls here, but in real-life scenarios this will be more complex. [source,java,linenums] ---- @Service public class MyService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Transactional public void startProcess() { runtimeService.startProcessInstanceByKey(""oneTaskProcess""); } @Transactional public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } } ---- We can now create a REST endpoint by annotating a class with _@RestController_. Here, we simply delegate to the service defined above. [source,java,linenums] ---- @RestController public class MyRestController { @Autowired private MyService myService; @PostMapping(value=""/process"") public void startProcessInstance() { myService.startProcess(); } @RequestMapping(value=""/tasks"", method= RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) public List getTasks(@RequestParam String assignee) { List tasks = myService.getTasks(assignee); List dtos = new ArrayList(); for (Task task : tasks) { dtos.add(new TaskRepresentation(task.getId(), task.getName())); } return dtos; } static class TaskRepresentation { private String id; private String name; public TaskRepresentation(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ---- Both the _@Service_ and the _@RestController_ will be found by the automatic component scan for a Spring Boot application. Run the application class again. We can now interact with the REST API, for example, by using cURL: ---- curl http://localhost:8080/tasks?assignee=kermit [] curl -X POST http://localhost:8080/process curl http://localhost:8080/tasks?assignee=kermit [{""id"":""10004"",""name"":""my task""}] ---- As can be seen, we are referring to the assignee, ""kermit"", which was hard-coded into the process definition XML earlier. We'll change this later on to allow the assignee to be set when the workflow instance is started. ==== JPA support To add JPA support for Flowable in Spring Boot, add following dependency: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter ${flowable.version} org.springframework.boot spring-boot-starter-data-jpa ${spring-boot.version ---- This will add in the Spring configuration and beans for using JPA. By default, the JPA provider will be Hibernate. Let's create a simple Entity class: [source,java,linenums] ---- @Entity class Person { @Id @GeneratedValue private Long id; private String username; private String firstName; private String lastName; private Date birthDate; public Person() { } public Person(String username, String firstName, String lastName, Date birthDate) { this.username = username; this.firstName = firstName; this.lastName = lastName; this.birthDate = birthDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } } ---- By default, when not using an in-memory database, the tables won't be created automatically. Create a file _application.properties_ on the classpath and add following property: ---- spring.jpa.hibernate.ddl-auto=update ---- Add following class: [source,java,linenums] ---- @Repository public interface PersonRepository extends JpaRepository { Person findByUsername(String username); } ---- This is a Spring repository, which offers CRUD out of the box. We add the method to find a Person by username. Spring will automatically implement this based on conventions (typically, the property names used). We now enhance our service further: * by adding _@Transactional_ to the class. Note that by adding the JPA dependency above, the DataSourceTransactionManager which we were using before is now automatically swapped out by a JpaTransactionManager. * The _startProcess_ now gets an assignee username passed in, which is used to look up the Person, and put the Person JPA object as a process variable in the process instance. * A method to create Dummy users is added. This is used in the CommandLineRunner to populate the database. [source,java,linenums] ---- @Service @Transactional public class MyService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private PersonRepository personRepository; public void startProcess(String assignee) { Person person = personRepository.findByUsername(assignee); Map variables = new HashMap(); variables.put(""person"", person); runtimeService.startProcessInstanceByKey(""oneTaskProcess"", variables); } public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } public void createDemoUsers() { if (personRepository.findAll().size() == 0) { personRepository.save(new Person(""jbarrez"", ""Joram"", ""Barrez"", new Date())); personRepository.save(new Person(""trademakers"", ""Tijs"", ""Rademakers"", new Date())); } } } ---- The CommandLineRunner now looks like: [source,java,linenums] ---- @Bean public CommandLineRunner init(final MyService myService) { return new CommandLineRunner() { public void run(String... strings) throws Exception { myService.createDemoUsers(); } }; } ---- The RestController is also modified slightly to incorporate the changes above (only showing new methods) and the HTTP POST now has a body that contains the assignee username: ---- @RestController public class MyRestController { @Autowired private MyService myService; @PostMapping(value=""/process"") public void startProcessInstance(@RequestBody StartProcessRepresentation startProcessRepresentation) { myService.startProcess(startProcessRepresentation.getAssignee()); } ... static class StartProcessRepresentation { private String assignee; public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } } ---- And finally, to try out the Spring-JPA-Flowable integration, we assign the task using the ID of the Person JPA object in the process definition: [source,xml,linenums] ---- ---- This replaces the hard-coded recipient, ""kermit"", which we had initially set. We can now start a new process instance, providing the user name in the POST body: ---- curl -H ""Content-Type: application/json"" -d '{""assignee"" : ""jbarrez""}' http://localhost:8080/process ---- And the task list is now fetched using the person ID: ---- curl http://localhost:8080/tasks?assignee=1 [{""id"":""12505"",""name"":""my task""}] ---- [[springBootActuatorEndpoint]] ==== Flowable Actuator Endpoints Flowable provides a Spring Boot Actuator Endpoint that exposes information for the Processes that are running. By default the `flowable` endpoint is mapped to `/actuator/flowable`. Spring Boot by default only exposes the `info` and `health` endpoints. In order to enable the `flowable` endpoint you need to add `management.endpoint.flowable.enabled=true` to your `application.properties`. In order to make enable Actuator endpoints you need to add a dependency on Actuator, e.g. by using {sc-flowable-starter}/flowable-spring-boot-starter-actuator/pom.xml[flowable-spring-boot-starter-actuator]. `curl http://localhost:8080/actuator/flowable` [source,json] ---- { ""completedTaskCountToday"": 0, ""deployedProcessDefinitions"": [ ""oneTaskProcess (v1)"" ], ""processDefinitionCount"": 1, ""cachedProcessDefinitionCount"": 0, ""runningProcessInstanceCount"": { ""oneTaskProcess (v1)"": 0 }, ""completedTaskCount"": 2, ""completedActivities"": 3, ""completedProcessInstanceCount"": { ""oneTaskProcess (v1)"": 0 }, ""openTaskCount"": 0 } ---- For more information about Spring Boot Actuator see link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html$$[Production Ready Endpoint] in the Spring Boot reference documentation. [[springBootInfoContributor]] ==== Flowable Info Contributor Flowable also provides a Spring Boot `InfoContributor` which looks like: `curl http://localhost:8080/actuator/info` [source,json] ---- { ""flowable"": { ""version"": ""6.5.0-SNAPSHOT"" } } ---- [[springBootFlowableProperties]] ==== Flowable Application Properties The Flowable auto configuration is leveraging the Spring Boot properties and configuration mechanism. See link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html$$[Properties and Configuration] in the Spring Boot reference guide. Here is a list of configuration properties that the Flowable Spring Boot support consumes. [source,properties,indent=0,subs=""verbatim,attributes,macros""] ---- # =================================================================== # Common Flowable Spring Boot Properties # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # =================================================================== # Core (Process) {sc-flowable-boot}/FlowableProperties.java[FlowableProperties] flowable.check-process-definitions=true # Whether process definitions need to be auto deployed. flowable.custom-mybatis-mappers= # The FQN of custom Mybatis mappers that need to be added to the engine. flowable.custom-mybatis-x-m-l-mappers= # The location of the custom Mybatis XML Mappers that need to be added to the engine. flowable.database-schema= # In some situations you want to set the schema to use for table checks / generation if the database metadata doesn't return that correctly. flowable.database-schema-update=true # The strategy that should be used for the database schema. flowable.db-history-used=true # Whether db history should be used. flowable.deployment-name=SpringBootAutoDeployment # The name of the auto deployment. flowable.history-level=audit # The history level that needs to be used. flowable.process-definition-location-prefix=classpath*:/processes/ # The folder in which processes need to be searched for auto deployment. flowable.process-definition-location-suffixes=**.bpmn20.xml,**.bpmn # The suffixes (extensions) of the files that needs to be deployed from the 'processDefinitionLocationPrefix' location. # Process {sc-flowable-boot}/process/FlowableProcessProperties.java[FlowableProcessProperties] flowable.process.definition-cache-limit=-1 # The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions). flowable.process.enable-safe-xml=true # Enables extra checks on the BPMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.process.servlet.load-on-startup=-1 # Load on startup of the Process dispatcher servlet. flowable.process.servlet.name=Flowable BPMN Rest API # The name of the Process servlet. flowable.process.servlet.path=/process-api # The context path for the Process rest servlet. # Process Async Executor flowable.process.async-executor-activate=true # Whether the async executor should be activated. flowable.process.async.executor.async-job-lock-time-in-millis=300000 # The amount of time (in milliseconds) an async job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. flowable.process.async.executor.default-async-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the async job acquisition thread will wait to execute the next acquirement query. This happens when no new async jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.process.async.executor.default-queue-size-full-wait-time-in-millis=0 # The time (in milliseconds) the async job (both timer and async continuations) acquisition thread will wait when the queue is full to execute the next query. By default set to 0 (for backwards compatibility) flowable.process.async.executor.default-timer-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the timer job acquisition thread will wait to execute the next acquirement query. This happens when no new timer jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.process.async.executor.max-async-jobs-due-per-acquisition=1 # ??? flowable.process.async.executor.retry-wait-time-in-millis=500 # ??? flowable.process.async.executor.timer-lock-time-in-millis=300000 # The amount of time (in milliseconds) a timer job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. # CMMN {sc-flowable-boot}/cmmn/FlowableCmmnProperties.java[FlowableCmmnProperties] flowable.cmmn.deploy-resources=true # Whether to perform deployment of resources, default is 'true'. flowable.cmmn.deployment-name=SpringBootAutoDeployment # The name of the deployment for the CMMN resources. flowable.cmmn.enable-safe-xml=true # Enables extra checks on the DMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.cmmn.enabled=true # Whether the CMMN engine needs to be started. flowable.cmmn.resource-location=classpath*:/cases/ # The location where the CMMN resources are located. flowable.cmmn.resource-suffixes=**.cmmn,**.cmmn11,**.cmmn.xml,**.cmmn11.xml # The suffixes for the resources that need to be scanned. flowable.cmmn.servlet.load-on-startup=-1 # Load on startup of the CMMN dispatcher servlet. flowable.cmmn.servlet.name=Flowable CMMN Rest API # The name of the CMMN servlet. flowable.cmmn.servlet.path=/cmmn-api # The context path for the CMMN rest servlet. # CMMN Async Executor flowable.cmmn.async-executor-activate=true # Whether the async executor should be activated. flowable.cmmn.async.executor.async-job-lock-time-in-millis=300000 # The amount of time (in milliseconds) an async job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. flowable.cmmn.async.executor.default-async-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the async job acquisition thread will wait to execute the next acquirement query. This happens when no new async jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.cmmn.async.executor.default-queue-size-full-wait-time-in-millis=0 # The time (in milliseconds) the async job (both timer and async continuations) acquisition thread will wait when the queue is full to execute the next query. By default set to 0 (for backwards compatibility) flowable.cmmn.async.executor.default-timer-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the timer job acquisition thread will wait to execute the next acquirement query. This happens when no new timer jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.cmmn.async.executor.max-async-jobs-due-per-acquisition=1 # ??? flowable.cmmn.async.executor.retry-wait-time-in-millis=500 # ??? flowable.cmmn.async.executor.timer-lock-time-in-millis=300000 # The amount of time (in milliseconds) a timer job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. # Content {sc-flowable-boot}/content/FlowableContentProperties.java[FlowableContentProperties] flowable.content.enabled=true # Whether the content engine needs to be started. flowable.content.servlet.load-on-startup=-1 # Load on startup of the Content dispatcher servlet. flowable.content.servlet.name=Flowable Content Rest API # The name of the Content servlet. flowable.content.servlet.path=/content-api # The context path for the Content rest servlet. flowable.content.storage.create-root=true # If the root folder doesn't exist, should it be created? flowable.content.storage.root-folder= # Root folder location where content files will be stored, for example, task attachments or form file uploads. # DMN {sc-flowable-boot}/dmn/FlowableDmnProperties.java[FlowableDmnProperties] flowable.dmn.deploy-resources=true # Whether to perform deployment of resources, default is 'true'. flowable.dmn.deployment-name=SpringBootAutoDeployment # The name of the deployment for the dmn resources. flowable.dmn.enable-safe-xml=true # Enables extra checks on the DMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.dmn.enabled=true # Whether the dmn engine needs to be started. flowable.dmn.history-enabled=true # Whether the history for the DMN engine should be enabled. flowable.dmn.resource-location=classpath*:/dmn/ # The location where the dmn resources are located. flowable.dmn.resource-suffixes=**.dmn,**.dmn.xml,**.dmn11,**.dmn11.xml # The suffixes for the resources that need to be scanned. flowable.dmn.servlet.load-on-startup=-1 # Load on startup of the DMN dispatcher servlet. flowable.dmn.servlet.name=Flowable DMN Rest API # The name of the DMN servlet. flowable.dmn.servlet.path=/dmn-api # The context path for the DMN rest servlet. flowable.dmn.strict-mode=true # Set this to false if you want to ignore the decision table hit policy validity checks to result in an failed decision table state. A result is that intermediate results created up to the point the validation error occurs are returned. # Form {sc-flowable-boot}/form/FlowableFormProperties.java[FlowableFormProperties] flowable.form.deploy-resources=true # Whether to perform deployment of resources, default is true. flowable.form.deployment-name=SpringBootAutoDeployment # The name of the deployment for the form resources. flowable.form.enabled=true # Whether the form engine needs to be started. flowable.form.resource-location=classpath*:/forms/ # The location where the form resources are located. flowable.form.resource-suffixes=**.form # The suffixes for the resources that need to be scanned. flowable.form.servlet.load-on-startup=-1 # Load on startup of the Form dispatcher servlet. flowable.form.servlet.name=Flowable Form Rest API # The name of the Form servlet. flowable.form.servlet.path=/form-api # The context path for the Form rest servlet. # IDM {sc-flowable-boot}/idm/FlowableIdmProperties.java[FlowableIdmProperties] flowable.idm.enabled=true # Whether the idm engine needs to be started. flowable.idm.password-encoder= # The type of the password encoder that needs to be used. flowable.idm.servlet.load-on-startup=-1 # Load on startup of the IDM dispatcher servlet. flowable.idm.servlet.name=Flowable IDM Rest API # The name of the IDM servlet. flowable.idm.servlet.path=/idm-api # The context path for the IDM rest servlet. # IDM Ldap {sc-flowable-boot}/ldap/FlowableLdapProperties.java[FlowableLdapProperties] flowable.idm.ldap.attribute.email= # Name of the attribute that matches the user email. flowable.idm.ldap.attribute.first-name= # Name of the attribute that matches the user first name. flowable.idm.ldap.attribute.group-id= # Name of the attribute that matches the group id. flowable.idm.ldap.attribute.group-name= # Name of the attribute that matches the group name. flowable.idm.ldap.attribute.group-type= # Name of the attribute that matches the group type. flowable.idm.ldap.attribute.last-name= # Name of the attribute that matches the user last name. flowable.idm.ldap.attribute.user-id= # Name of the attribute that matches the user id. flowable.idm.ldap.base-dn= # The base 'distinguished name' (DN) from which the searches for users and groups are started. flowable.idm.ldap.cache.group-size=-1 # Allows to set the size of the {@link org.flowable.ldap.LDAPGroupCache}. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. flowable.idm.ldap.custom-connection-parameters= # Allows to set all LDAP connection parameters which do not have a dedicated setter. See for example http://docs.oracle.com/javase/tutorial/jndi/ldap/jndi.html for custom properties. Such properties are for example to configure connection pooling, specific security settings, etc. flowable.idm.ldap.enabled=false # Whether to enable LDAP IDM Service. flowable.idm.ldap.group-base-dn= # The base 'distinguished name' (DN) from which the searches for groups are started. flowable.idm.ldap.initial-context-factory=com.sun.jndi.ldap.LdapCtxFactory # The class name for the initial context factory. flowable.idm.ldap.password= # The password that is used to connect to the LDAP system. flowable.idm.ldap.port=-1 # The port on which the LDAP system is running. flowable.idm.ldap.query.all-groups= # The query that is executed when searching for all groups. flowable.idm.ldap.query.all-users= # The query that is executed when searching for all users. flowable.idm.ldap.query.groups-for-user= # The query that is executed when searching for the groups of a specific user. flowable.idm.ldap.query.user-by-full-name-like= # The query that is executed when searching for a user by full name. flowable.idm.ldap.query.user-by-id= # The query that is executed when searching for a user by userId. flowable.idm.ldap.query.group-by-id= # The query that is executed when searching for a specific group by groupId. flowable.idm.ldap.search-time-limit=0 # The timeout (in milliseconds) that is used when doing a search in LDAP. By default set to '0', which means 'wait forever'. flowable.idm.ldap.security-authentication=simple # The value that is used for the 'java.naming.security.authentication' property used to connect to the LDAP system. flowable.idm.ldap.server= # The server host on which the LDAP system can be reached. For example 'ldap://localhost'. flowable.idm.ldap.user= # The user id that is used to connect to the LDAP system. flowable.idm.ldap.user-base-dn= # The base 'distinguished name' (DN) from which the searches for users are started. # Flowable Mail {sc-flowable-boot}/FlowableMailProperties.java[FlowableMailProperties] flowable.mail.server.default-from=flowable@localhost # The default from address that needs to be used when sending emails. flowable.mail.server.force-to= # The force to address(es) that would be used when sending out emails. IMPORTANT: If this is set then all emails will be send to defined address(es) instead of the address configured in the MailActivity. flowable.mail.server.host=localhost # The host of the mail server. flowable.mail.server.password= # The password for the mail server authentication. flowable.mail.server.port=1025 # The port of the mail server. flowable.mail.server.use-ssl=false # Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). flowable.mail.server.use-tls=false # Set or disable the STARTTLS encryption. flowable.mail.server.username= # The username that needs to be used for the mail server authentication. If empty no authentication would be used. # Flowable Http {sc-flowable-boot}/FlowableHttpProperties.java[FlowableHttpProperties] flowable.http.user-system-properties=false # Whether to use system properties (e.g. http.proxyPort). flowable.http.connect-timeout=5s # Connect timeout for the http client flowable.http.socket-timeout=5s # Socket timeout for the http client flowable.http.connection-request-timeout=5s # Connection Request Timeout for the http client flowable.http.request-retry-limit=3 # Request retry limit for the http client flowable.http.disable-cert-verify=false # Whether to disable certificate validation for the http client # Flowable REST flowable.rest.app.cors.enabled=true # Whether to enable CORS requests at all. If false, the other properties have no effect flowable.rest.app.cors.allow-credentials=true # Whether to include credentials in a CORS request flowable.rest.app.cors.allowed-origins=* # Comma-separated URLs to accept CORS requests from flowable.rest.app.cors.allowed-headers=* # Comma-separated HTTP headers to allow in a CORS request flowable.rest.app.cors.allowed-methods=DELETE,GET,PATCH,POST,PUT # Comma-separated HTTP verbs to allow in a CORS request flowable.rest.app.cors.exposed-headers=* # Comma-separated list of headers to expose in CORS response # Actuator management.endpoint.flowable.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.flowable.enabled=true # Whether to enable the flowable endpoint. ---- .Deprecated properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.mail.server.host |flowable.mail-server-host |localhost |The host of the mail server. |flowable.mail.server.password |flowable.mail-server-password |- |The password for the mail server authentication. |flowable.mail.server.port |flowable.mail-server-port |1025 |The port of the mail server. |flowable.mail.server.use-ssl |flowable.mail-server-use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |flowable.mail-server-use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |flowable.mail-server-user-name |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions) |=============== [[springBootFlowableAutoConfiguration]] ==== Flowable Auto-configuration classes Here is a list of all auto-configuration classes provided by Flowable, with links to documentation and source code. Remember to also look at the conditions report in your application for more details of which features are switched on. (To do so, start the app with --debug or -Ddebug or, in an Actuator application, use the conditions endpoint). [cols=*,options=""header""] |=== |Configuration Class |{sc-flowable-boot}/content/ContentEngineAutoConfiguration.java[ContentEngineAutoConfiguration] |{sc-flowable-boot}/content/ContentEngineServicesAutoConfiguration.java[ContentEngineServicesAutoConfiguration] |{sc-flowable-boot}/cmmn/CmmnEngineAutoConfiguration.java[CmmnEngineAutoConfiguration] |{sc-flowable-boot}/cmmn/CmmnEngineServicesAutoConfiguration.java[CmmnEngineServicesAutoConfiguration] |{sc-flowable-boot}/dmn/DmnEngineAutoConfiguration.java[DmnEngineAutoConfiguration] |{sc-flowable-boot}/dmn/DmnEngineServicesAutoConfiguration.java[DmnEngineServicesAutoConfiguration] |{sc-flowable-boot}/EndpointAutoConfiguration.java[EndpointAutoConfiguration] |{sc-flowable-boot}/actuate/info/FlowableInfoAutoConfiguration.java[FlowableInfoAutoConfiguration] |{sc-flowable-boot}/ldap/FlowableLdapAutoConfiguration.java[FlowableLdapAutoConfiguration] |{sc-flowable-boot}/FlowableTransactionAutoConfiguration.java[FlowableTransactionAutoConfiguration] |{sc-flowable-boot}/form/FormEngineAutoConfiguration.java[FormEngineAutoConfiguration] |{sc-flowable-boot}/form/FormEngineServicesAutoConfiguration.java[FormEngineServicesAutoConfiguration] |{sc-flowable-boot}/idm/IdmEngineAutoConfiguration.java[IdmEngineAutoConfiguration] |{sc-flowable-boot}/idm/IdmEngineServicesAutoConfiguration.java[IdmEngineServicesAutoConfiguration] |{sc-flowable-boot}/ProcessEngineAutoConfiguration.java[ProcessEngineAutoConfiguration] |{sc-flowable-boot}/RestApiAutoConfiguration.java[RestApiAutoConfiguration] |{sc-flowable-boot}/SecurityAutoConfiguration.java[SecurityAutoConfiguration] |=== [[springBootFlowableStarter]] ==== Flowable Starters Here is a list of the flowable spring boot starters. [cols=2*,options=""header""] |=== |Starter |Description |{sc-flowable-starter}/flowable-spring-boot-starter-cmmn/pom.xml[flowable-spring-boot-starter-cmmn] |Contains the dependencies for booting the CMMN Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-cmmn-rest/pom.xml[flowable-spring-boot-starter-cmmn-rest] |Contains the dependencies for booting the CMMN Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter-dmn/pom.xml[flowable-spring-boot-starter-dmn] |Contains the dependencies for booting the DMN Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-dmn-rest/pom.xml[flowable-spring-boot-starter-dmn-rest] |Contains the dependencies for booting the DMN Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter-process/pom.xml[flowable-spring-boot-starter-process] |Contains the dependencies for booting the Process Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-process-rest/pom.xml[flowable-spring-boot-starter-process-rest] |Contains the dependencies for booting the Process Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter/pom.xml[flowable-spring-boot-starter] |Contains the dependencies for booting all Flowable Engines (Process, CMMN, DMN, Form, Content and IDM) |{sc-flowable-starter}/flowable-spring-boot-starter-rest/pom.xml[flowable-spring-boot-starter-rest] |Contains the dependencies for booting all Flowable Engines and their respective REST API |{sc-flowable-starter}/flowable-spring-boot-starter-actuator/pom.xml[flowable-spring-boot-starter-actuator] |Contains the required dependencies for Spring Boot |=== ==== Using Liquibase The Flowable engines are using Liquibase to manage the versioning of it's tables. This means that the `LiquibaseAutoConfiguration` from Spring Boot would automatically kick in. However, if you are not using Liquibase then the application will not start and would throw an exception. For this reason Flowable is setting `spring.liquibase.enabled` to `false`, which means that if you need to use Liquibase you have to explicitly enable it. ==== Further Reading Obviously, there is a lot about Spring Boot that hasn't been touched upon yet, like very easy JTA integration or building a WAR file that can be run on major application servers. And there is a lot more to the Spring Boot integration: * Actuator support * Spring Integration support * Rest API integration: boot up the Flowable Rest API embedded within the Spring application * Spring Security support ==== Advanced Configuration ===== Customizing Engine Configuration It's possible to get a hold of the engine configuration by implementing the _org.flowable.spring.boot.EngineConfigurationConfigurer_ interface. Where _T_ is the Spring Type of the particular Engine Configuration. This can be useful for advanced configuration settings or simply because a property has not been exposed (yet). For example: [source, java, linenums] ---- public class MyConfigurer implements EngineConfigurationConfigurer { public void configure(SpringProcessEngineConfiguration processEngineConfiguration) { // advanced configuration } } ---- By exposing an instance of this class as an _@Bean_ in the Spring Boot configuration, the instance will be called before the process engine is fully created. [TIP] ==== You can provide a custom implementation of a Flowable Service by using this. See {sc-flowable-boot}/ldap/FlowableLdapAutoConfiguration.java[FlowableLdapAutoConfiguration] ==== ===== Combining starters In case you need only a combination of the engines then you can add only the required dependencies. For example to use the Process, CMMN, Form and IDM engine and use LDAP you need to add the following dependencies: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter-process ${flowable.version} org.flowable flowable-spring-boot-starter-cmmn ${flowable.version} org.flowable flowable-content-spring-configurator ${flowable.version} org.flowable flowable-form-spring-configurator ${flowable.version} org.flowable flowable-ldap ${flowable.version} ---- ===== Configuring Async Executors The Process and CMMN engines have dedicated `AsyncExecutor`(s) and they can be configured with the `flowable.{engine}.async.executor` property group. Where `engine` is either `process` or `cmmn`. The `AsyncExecutor`(s) per default share the same Spring `TaskExecutor` and `SpringRejectedJobsHandler`. In case you want to provide a dedicated executor for each of the engines you need define a qualified bean with `@Process` and `@Cmmn`. You can configure custom executors in the following way: [source,java,linenums] ---- @Configuration public class MyConfiguration { @Process <1> @Bean public TaskExecutor processTaskExecutor() { return new SimpleAsyncTaskExecutor(); } @Cmmn <2> @Bean public TaskExecutor cmmnTaskExecutor() { return new SyncTaskExecutor(); } } ---- <1> The Async Executor for the Process Engine would use a `SimpleAsyncTaskExecutor` <2> The Async Executor for the CMMN Engine would use a `SyncTaskExecutor` [IMPORTANT] ====== If you define a custom `TaskExecutor` bean the Flowable creation of the bean is not triggered. Which means that if you define a bean qualified with `@Process` you have to define one with `@Cmmn` or `@Primary`, otherwise the Cmmn Async Executor will use the one for the Process ====== ",12202,False,1842.3113590734806,median "CLASS zcl_excel_drawing DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. *""* public components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! *""* protected components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! *""* protected components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! *""* protected components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! TYPE-POOLS abap . CONSTANTS c_graph_pie TYPE zexcel_graph_type VALUE 1. ""#EC NOTEXT CONSTANTS c_graph_line TYPE zexcel_graph_type VALUE 2. ""#EC NOTEXT CONSTANTS c_graph_bars TYPE zexcel_graph_type VALUE 0. ""#EC NOTEXT DATA graph_type TYPE zexcel_graph_type . DATA title TYPE string VALUE 'image1.jpg'. ""#EC NOTEXT DATA x_references TYPE char1 . DATA y_references TYPE char1 . CONSTANTS type_image TYPE zexcel_drawing_type VALUE 'image'. ""#EC NOTEXT CONSTANTS type_chart TYPE zexcel_drawing_type VALUE 'chart'. ""#EC NOTEXT CONSTANTS anchor_absolute TYPE zexcel_drawing_anchor VALUE 'ABS'. ""#EC NOTEXT CONSTANTS anchor_one_cell TYPE zexcel_drawing_anchor VALUE 'ONE'. ""#EC NOTEXT CONSTANTS anchor_two_cell TYPE zexcel_drawing_anchor VALUE 'TWO'. ""#EC NOTEXT DATA graph TYPE REF TO zcl_excel_graph . CONSTANTS c_media_type_bmp TYPE string VALUE 'bmp'. ""#EC NOTEXT CONSTANTS c_media_type_xml TYPE string VALUE 'xml'. ""#EC NOTEXT CONSTANTS c_media_type_jpg TYPE string VALUE 'jpg'. ""#EC NOTEXT CONSTANTS type_image_header_footer TYPE zexcel_drawing_type VALUE 'hd_ft'. ""#EC NOTEXT METHODS constructor IMPORTING !ip_type TYPE zexcel_drawing_type DEFAULT zcl_excel_drawing=>type_image !ip_title TYPE clike OPTIONAL . METHODS create_media_name IMPORTING !ip_index TYPE i . METHODS get_from_col RETURNING VALUE(r_from_col) TYPE zexcel_cell_column . METHODS get_from_row RETURNING VALUE(r_from_row) TYPE zexcel_cell_row . METHODS get_guid RETURNING VALUE(ep_guid) TYPE guid_16 . METHODS get_height_emu_str RETURNING VALUE(r_height) TYPE string . METHODS get_media RETURNING VALUE(r_media) TYPE xstring . METHODS get_media_name RETURNING VALUE(r_name) TYPE string . METHODS get_media_type RETURNING VALUE(r_type) TYPE string . METHODS get_name RETURNING VALUE(r_name) TYPE string . METHODS get_to_col RETURNING VALUE(r_to_col) TYPE zexcel_cell_column . METHODS get_to_row RETURNING VALUE(r_to_row) TYPE zexcel_cell_row . METHODS get_width_emu_str RETURNING VALUE(r_width) TYPE string . CLASS-METHODS pixel2emu IMPORTING !ip_pixel TYPE int4 !ip_dpi TYPE int2 OPTIONAL RETURNING VALUE(r_emu) TYPE string . CLASS-METHODS emu2pixel IMPORTING !ip_emu TYPE int4 !ip_dpi TYPE int2 OPTIONAL RETURNING VALUE(r_pixel) TYPE int4 . METHODS set_media IMPORTING !ip_media TYPE xstring OPTIONAL !ip_media_type TYPE string !ip_width TYPE int4 DEFAULT 0 !ip_height TYPE int4 DEFAULT 0 . METHODS set_media_mime IMPORTING !ip_io TYPE skwf_io !ip_width TYPE int4 !ip_height TYPE int4 . METHODS set_media_www IMPORTING !ip_key TYPE wwwdatatab !ip_width TYPE int4 !ip_height TYPE int4 . METHODS set_position IMPORTING !ip_from_row TYPE zexcel_cell_row !ip_from_col TYPE zexcel_cell_column_alpha !ip_rowoff TYPE int4 OPTIONAL !ip_coloff TYPE int4 OPTIONAL RAISING zcx_excel . METHODS set_position2 IMPORTING !ip_from TYPE zexcel_drawing_location !ip_to TYPE zexcel_drawing_location !ip_anchor TYPE zexcel_drawing_anchor OPTIONAL . METHODS get_position RETURNING VALUE(rp_position) TYPE zexcel_drawing_position . METHODS get_type RETURNING VALUE(rp_type) TYPE zexcel_drawing_type . METHODS get_index RETURNING VALUE(rp_index) TYPE string . METHODS load_chart_attributes IMPORTING VALUE(ip_chart) TYPE REF TO if_ixml_document . PROTECTED SECTION. PRIVATE SECTION. *""* private components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! DATA type TYPE zexcel_drawing_type VALUE type_image. ""#EC NOTEXT . . . . . . . . . . . "" . DATA index TYPE string . DATA anchor TYPE zexcel_drawing_anchor VALUE anchor_one_cell. ""#EC NOTEXT . . . . . . . . . . . "" . CONSTANTS c_media_source_www TYPE char1 VALUE 1. ""#EC NOTEXT CONSTANTS c_media_source_xstring TYPE char1 VALUE 0. ""#EC NOTEXT CONSTANTS c_media_source_mime TYPE char1 VALUE 2. ""#EC NOTEXT DATA guid TYPE guid_16 . DATA media TYPE xstring . DATA media_key_www TYPE wwwdatatab . DATA media_name TYPE string . DATA media_source TYPE char1 . DATA media_type TYPE string . DATA io TYPE skwf_io . DATA from_loc TYPE zexcel_drawing_location . DATA to_loc TYPE zexcel_drawing_location . DATA size TYPE zexcel_drawing_size . ENDCLASS. CLASS zcl_excel_drawing IMPLEMENTATION. METHOD constructor. * CALL FUNCTION 'GUID_CREATE' "" del issue #379 - function is outdated in newer releases * IMPORTING * ev_guid_16 = me->guid. me->guid = zcl_excel_obsolete_func_wrap=>guid_create( ). "" ins issue #379 - replacement for outdated function call IF ip_title IS NOT INITIAL. title = ip_title. ELSE. title = me->guid. ENDIF. me->type = ip_type. * inizialize dimension range anchor = anchor_one_cell. from_loc-col = 1. from_loc-row = 1. ENDMETHOD. METHOD create_media_name. * if media name is initial, create unique name CHECK media_name IS INITIAL. index = ip_index. CONCATENATE me->type index INTO media_name. CONDENSE media_name NO-GAPS. ENDMETHOD. METHOD emu2pixel. * suppose 96 DPI IF ip_dpi IS SUPPLIED. * r_emu = ip_pixel * 914400 / ip_dpi. r_pixel = ip_emu * ip_dpi / 914400. ELSE. * suppose 96 DPI * r_emu = ip_pixel * 914400 / 96. r_pixel = ip_emu * 96 / 914400. ENDIF. ENDMETHOD. METHOD get_from_col. r_from_col = me->from_loc-col. ENDMETHOD. METHOD get_from_row. r_from_row = me->from_loc-row. ENDMETHOD. METHOD get_guid. ep_guid = me->guid. ENDMETHOD. METHOD get_height_emu_str. r_height = pixel2emu( size-height ). CONDENSE r_height NO-GAPS. ENDMETHOD. METHOD get_index. rp_index = me->index. ENDMETHOD. METHOD get_media. DATA: lv_language TYPE sylangu. DATA: lt_bin_mime TYPE sdokcntbins. DATA: lt_mime TYPE tsfmime, lv_filesize TYPE i, lv_filesizec(10). CASE media_source. WHEN c_media_source_xstring. r_media = media. WHEN c_media_source_www. CALL FUNCTION 'WWWDATA_IMPORT' EXPORTING key = media_key_www TABLES mime = lt_mime EXCEPTIONS OTHERS = 1. CALL FUNCTION 'WWWPARAMS_READ' EXPORTING relid = media_key_www-relid objid = media_key_www-objid name = 'filesize' IMPORTING value = lv_filesizec. lv_filesize = lv_filesizec. CALL FUNCTION 'SCMS_BINARY_TO_XSTRING' EXPORTING input_length = lv_filesize IMPORTING buffer = r_media TABLES binary_tab = lt_mime EXCEPTIONS failed = 1 OTHERS = 2. WHEN c_media_source_mime. lv_language = sy-langu. cl_wb_mime_repository=>load_mime( EXPORTING io = me->io IMPORTING filesize = lv_filesize bin_data = lt_bin_mime CHANGING language = lv_language ). CALL FUNCTION 'SCMS_BINARY_TO_XSTRING' EXPORTING input_length = lv_filesize IMPORTING buffer = r_media TABLES binary_tab = lt_bin_mime EXCEPTIONS failed = 1 OTHERS = 2. ENDCASE. ENDMETHOD. METHOD get_media_name. CONCATENATE media_name `.` media_type INTO r_name. ENDMETHOD. METHOD get_media_type. r_type = media_type. ENDMETHOD. METHOD get_name. r_name = title. ENDMETHOD. METHOD get_position. rp_position-anchor = anchor. rp_position-from = from_loc. rp_position-to = to_loc. rp_position-size = size. ENDMETHOD. METHOD get_to_col. r_to_col = me->to_loc-col. ENDMETHOD. METHOD get_to_row. r_to_row = me->to_loc-row. ENDMETHOD. METHOD get_type. rp_type = me->type. ENDMETHOD. METHOD get_width_emu_str. r_width = pixel2emu( size-width ). CONDENSE r_width NO-GAPS. ENDMETHOD. METHOD load_chart_attributes. DATA: node TYPE REF TO if_ixml_element. DATA: node2 TYPE REF TO if_ixml_element. DATA: node3 TYPE REF TO if_ixml_element. DATA: node4 TYPE REF TO if_ixml_element. DATA lo_barchart TYPE REF TO zcl_excel_graph_bars. DATA lo_piechart TYPE REF TO zcl_excel_graph_pie. DATA lo_linechart TYPE REF TO zcl_excel_graph_line. TYPES: BEGIN OF t_prop, val TYPE string, rtl TYPE string, lang TYPE string, formatcode TYPE string, sourcelinked TYPE string, END OF t_prop. TYPES: BEGIN OF t_pagemargins, b TYPE string, l TYPE string, r TYPE string, t TYPE string, header TYPE string, footer TYPE string, END OF t_pagemargins. DATA ls_prop TYPE t_prop. DATA ls_pagemargins TYPE t_pagemargins. DATA lo_collection TYPE REF TO if_ixml_node_collection. DATA lo_node TYPE REF TO if_ixml_node. DATA lo_iterator TYPE REF TO if_ixml_node_iterator. DATA lv_idx TYPE i. DATA lv_order TYPE i. DATA lv_invertifnegative TYPE string. DATA lv_symbol TYPE string. DATA lv_smooth TYPE c. DATA lv_sername TYPE string. DATA lv_label TYPE string. DATA lv_value TYPE string. DATA lv_axid TYPE string. DATA lv_orientation TYPE string. DATA lv_delete TYPE string. DATA lv_axpos TYPE string. DATA lv_formatcode TYPE string. DATA lv_sourcelinked TYPE string. DATA lv_majortickmark TYPE string. DATA lv_minortickmark TYPE string. DATA lv_ticklblpos TYPE string. DATA lv_crossax TYPE string. DATA lv_crosses TYPE string. DATA lv_auto TYPE string. DATA lv_lblalgn TYPE string. DATA lv_lbloffset TYPE string. DATA lv_nomultilvllbl TYPE string. DATA lv_crossbetween TYPE string. node ?= ip_chart->if_ixml_node~get_first_child( ). CHECK node IS NOT INITIAL. CASE me->graph_type. WHEN c_graph_bars. CREATE OBJECT lo_barchart. me->graph = lo_barchart. WHEN c_graph_pie. CREATE OBJECT lo_piechart. me->graph = lo_piechart. WHEN c_graph_line. CREATE OBJECT lo_linechart. me->graph = lo_linechart. WHEN OTHERS. ENDCASE. ""Fill properties node2 ?= node->find_from_name( name = 'date1904' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_1904val = ls_prop-val. node2 ?= node->find_from_name( name = 'lang' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_langval = ls_prop-val. node2 ?= node->find_from_name( name = 'roundedCorners' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_roundedcornersval = ls_prop-val. ""style node2 ?= node->find_from_name( name = 'style' namespace = 'c14' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_c14styleval = ls_prop-val. node2 ?= node->find_from_name( name = 'style' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_styleval = ls_prop-val. ""---------------------------Read graph properties ""ADDED CLEAR node2. node2 ?= node->find_from_name( name = 'title' namespace = 'c' ). IF node2 IS BOUND AND node2 IS NOT INITIAL. node3 ?= node2->find_from_name( name = 't' namespace = 'a' ). me->graph->title = node3->get_value( ). ENDIF. ""END node2 ?= node->find_from_name( name = 'autoTitleDeleted' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_autotitledeletedval = ls_prop-val. ""plotArea CASE me->graph_type. WHEN c_graph_bars. node2 ?= node->find_from_name( name = 'barDir' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_bardirval = ls_prop-val. node2 ?= node->find_from_name( name = 'grouping' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_groupingval = ls_prop-val. node2 ?= node->find_from_name( name = 'varyColors' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_varycolorsval = ls_prop-val. ""Load series CALL METHOD node->get_elements_by_tag_name EXPORTING * depth = 0 name = 'ser' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. node3 ?= node2->find_from_name( name = 'idx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_idx = ls_prop-val. node3 ?= node2->find_from_name( name = 'order' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_order = ls_prop-val. node3 ?= node2->find_from_name( name = 'invertIfNegative' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_invertifnegative = ls_prop-val. node3 ?= node2->find_from_name( name = 'v' namespace = 'c' ). IF node3 IS BOUND. lv_sername = node3->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'strRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_label = node4->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'numRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_value = node4->get_value( ). ENDIF. CALL METHOD lo_barchart->create_serie EXPORTING ip_idx = lv_idx ip_order = lv_order ip_invertifnegative = lv_invertifnegative ip_lbl = lv_label ip_ref = lv_value ip_sername = lv_sername. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. ""note: numCache avoided node2 ?= node->find_from_name( name = 'showLegendKey' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showlegendkeyval = ls_prop-val. node2 ?= node->find_from_name( name = 'showVal' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showvalval = ls_prop-val. node2 ?= node->find_from_name( name = 'showCatName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showcatnameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showSerName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showsernameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showPercent' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showpercentval = ls_prop-val. node2 ?= node->find_from_name( name = 'showBubbleSize' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showbubblesizeval = ls_prop-val. node2 ?= node->find_from_name( name = 'gapWidth' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_gapwidthval = ls_prop-val. ""Load axes node2 ?= node->find_from_name( name = 'barChart' namespace = 'c' ). CALL METHOD node2->get_elements_by_tag_name EXPORTING * depth = 0 name = 'axId' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lv_axid = ls_prop-val. IF sy-index EQ 1. ""catAx node2 ?= node->find_from_name( name = 'catAx' namespace = 'c' ). node3 ?= node2->find_from_name( name = 'orientation' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_orientation = ls_prop-val. node3 ?= node2->find_from_name( name = 'delete' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_delete = ls_prop-val. node3 ?= node2->find_from_name( name = 'axPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_axpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'numFmt' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_formatcode = ls_prop-formatcode. lv_sourcelinked = ls_prop-sourcelinked. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_majortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_minortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'tickLblPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_ticklblpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossAx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossax = ls_prop-val. node3 ?= node2->find_from_name( name = 'crosses' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crosses = ls_prop-val. node3 ?= node2->find_from_name( name = 'auto' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_auto = ls_prop-val. node3 ?= node2->find_from_name( name = 'lblAlgn' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_lblalgn = ls_prop-val. node3 ?= node2->find_from_name( name = 'lblOffset' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_lbloffset = ls_prop-val. node3 ?= node2->find_from_name( name = 'noMultiLvlLbl' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_nomultilvllbl = ls_prop-val. CALL METHOD lo_barchart->create_ax EXPORTING ip_axid = lv_axid ip_type = zcl_excel_graph_bars=>c_catax ip_orientation = lv_orientation ip_delete = lv_delete ip_axpos = lv_axpos ip_formatcode = lv_formatcode ip_sourcelinked = lv_sourcelinked ip_majortickmark = lv_majortickmark ip_minortickmark = lv_minortickmark ip_ticklblpos = lv_ticklblpos ip_crossax = lv_crossax ip_crosses = lv_crosses ip_auto = lv_auto ip_lblalgn = lv_lblalgn ip_lbloffset = lv_lbloffset ip_nomultilvllbl = lv_nomultilvllbl. ELSEIF sy-index EQ 2. ""valAx node2 ?= node->find_from_name( name = 'valAx' namespace = 'c' ). node3 ?= node2->find_from_name( name = 'orientation' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_orientation = ls_prop-val. node3 ?= node2->find_from_name( name = 'delete' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_delete = ls_prop-val. node3 ?= node2->find_from_name( name = 'axPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_axpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'numFmt' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_formatcode = ls_prop-formatcode. lv_sourcelinked = ls_prop-sourcelinked. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_majortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_minortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'tickLblPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_ticklblpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossAx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossax = ls_prop-val. node3 ?= node2->find_from_name( name = 'crosses' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crosses = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossBetween' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossbetween = ls_prop-val. CALL METHOD lo_barchart->create_ax EXPORTING ip_axid = lv_axid ip_type = zcl_excel_graph_bars=>c_valax ip_orientation = lv_orientation ip_delete = lv_delete ip_axpos = lv_axpos ip_formatcode = lv_formatcode ip_sourcelinked = lv_sourcelinked ip_majortickmark = lv_majortickmark ip_minortickmark = lv_minortickmark ip_ticklblpos = lv_ticklblpos ip_crossax = lv_crossax ip_crosses = lv_crosses ip_crossbetween = lv_crossbetween. ENDIF. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. WHEN c_graph_pie. node2 ?= node->find_from_name( name = 'varyColors' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_varycolorsval = ls_prop-val. ""Load series CALL METHOD node->get_elements_by_tag_name EXPORTING * depth = 0 name = 'ser' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. node3 ?= node2->find_from_name( name = 'idx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_idx = ls_prop-val. node3 ?= node2->find_from_name( name = 'order' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_order = ls_prop-val. node3 ?= node2->find_from_name( name = 'v' namespace = 'c' ). IF node3 IS BOUND. lv_sername = node3->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'strRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_label = node4->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'numRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_value = node4->get_value( ). ENDIF. CALL METHOD lo_piechart->create_serie EXPORTING ip_idx = lv_idx ip_order = lv_order ip_lbl = lv_label ip_ref = lv_value ip_sername = lv_sername. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. ""note: numCache avoided node2 ?= node->find_from_name( name = 'showLegendKey' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showlegendkeyval = ls_prop-val. node2 ?= node->find_from_name( name = 'showVal' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showvalval = ls_prop-val. node2 ?= node->find_from_name( name = 'showCatName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showcatnameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showSerName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showsernameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showPercent' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showpercentval = ls_prop-val. node2 ?= node->find_from_name( name = 'showBubbleSize' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showbubblesizeval = ls_prop-val. node2 ?= node->find_from_name( name = 'showLeaderLines' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showleaderlinesval = ls_prop-val. node2 ?= node->find_from_name( name = 'firstSliceAng' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_firstsliceangval = ls_prop-val. WHEN c_graph_line. node2 ?= node->find_from_name( name = 'grouping' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_groupingval = ls_prop-val. node2 ?= node->find_from_name( name = 'varyColors' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_varycolorsval = ls_prop-val. ""Load series CALL METHOD node->get_elements_by_tag_name EXPORTING * depth = 0 name = 'ser' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. node3 ?= node2->find_from_name( name = 'idx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_idx = ls_prop-val. node3 ?= node2->find_from_name( name = 'order' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_order = ls_prop-val. node3 ?= node2->find_from_name( name = 'symbol' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_symbol = ls_prop-val. node3 ?= node2->find_from_name( name = 'smooth' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_smooth = ls_prop-val. node3 ?= node2->find_from_name( name = 'v' namespace = 'c' ). IF node3 IS BOUND. lv_sername = node3->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'strRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_label = node4->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'numRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_value = node4->get_value( ). ENDIF. CALL METHOD lo_linechart->create_serie EXPORTING ip_idx = lv_idx ip_order = lv_order ip_symbol = lv_symbol ip_smooth = lv_smooth ip_lbl = lv_label ip_ref = lv_value ip_sername = lv_sername. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. ""note: numCache avoided node2 ?= node->find_from_name( name = 'showLegendKey' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showlegendkeyval = ls_prop-val. node2 ?= node->find_from_name( name = 'showVal' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showvalval = ls_prop-val. node2 ?= node->find_from_name( name = 'showCatName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showcatnameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showSerName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showsernameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showPercent' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showpercentval = ls_prop-val. node2 ?= node->find_from_name( name = 'showBubbleSize' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showbubblesizeval = ls_prop-val. node ?= node->find_from_name( name = 'lineChart' namespace = 'c' ). node2 ?= node->find_from_name( name = 'marker' namespace = 'c' depth = '1' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_markerval = ls_prop-val. node2 ?= node->find_from_name( name = 'smooth' namespace = 'c' depth = '1' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_smoothval = ls_prop-val. node ?= ip_chart->if_ixml_node~get_first_child( ). CHECK node IS NOT INITIAL. ""Load axes node2 ?= node->find_from_name( name = 'lineChart' namespace = 'c' ). CALL METHOD node2->get_elements_by_tag_name EXPORTING * depth = 0 name = 'axId' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lv_axid = ls_prop-val. IF sy-index EQ 1. ""catAx node2 ?= node->find_from_name( name = 'catAx' namespace = 'c' ). node3 ?= node2->find_from_name( name = 'orientation' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_orientation = ls_prop-val. node3 ?= node2->find_from_name( name = 'delete' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_delete = ls_prop-val. node3 ?= node2->find_from_name( name = 'axPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_axpos = ls_prop-val. * node3 ?= node2->find_from_name( name = 'numFmt' namespace = 'c' ). * zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). * lv_formatcode = ls_prop-formatcode. * lv_sourcelinked = ls_prop-sourcelinked. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_majortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_minortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'tickLblPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_ticklblpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossAx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossax = ls_prop-val. node3 ?= node2->find_from_name( name = 'crosses' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crosses = ls_prop-val. node3 ?= node2->find_from_name( name = 'auto' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_auto = ls_prop-val. node3 ?= node2->find_from_name( name = 'lblAlgn' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_lblalgn = ls_prop-val. node3 ?= node2->find_from_name( name = 'lblOffset' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_lbloffset = ls_prop-val. node3 ?= node2->find_from_name( name = 'noMultiLvlLbl' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_nomultilvllbl = ls_prop-val. CALL METHOD lo_linechart->create_ax EXPORTING ip_axid = lv_axid ip_type = zcl_excel_graph_line=>c_catax ip_orientation = lv_orientation ip_delete = lv_delete ip_axpos = lv_axpos ip_formatcode = lv_formatcode ip_sourcelinked = lv_sourcelinked ip_majortickmark = lv_majortickmark ip_minortickmark = lv_minortickmark ip_ticklblpos = lv_ticklblpos ip_crossax = lv_crossax ip_crosses = lv_crosses ip_auto = lv_auto ip_lblalgn = lv_lblalgn ip_lbloffset = lv_lbloffset ip_nomultilvllbl = lv_nomultilvllbl. ELSEIF sy-index EQ 2. ""valAx node2 ?= node->find_from_name( name = 'valAx' namespace = 'c' ). node3 ?= node2->find_from_name( name = 'orientation' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_orientation = ls_prop-val. node3 ?= node2->find_from_name( name = 'delete' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_delete = ls_prop-val. node3 ?= node2->find_from_name( name = 'axPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_axpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'numFmt' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_formatcode = ls_prop-formatcode. lv_sourcelinked = ls_prop-sourcelinked. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_majortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_minortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'tickLblPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_ticklblpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossAx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossax = ls_prop-val. node3 ?= node2->find_from_name( name = 'crosses' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crosses = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossBetween' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossbetween = ls_prop-val. CALL METHOD lo_linechart->create_ax EXPORTING ip_axid = lv_axid ip_type = zcl_excel_graph_line=>c_valax ip_orientation = lv_orientation ip_delete = lv_delete ip_axpos = lv_axpos ip_formatcode = lv_formatcode ip_sourcelinked = lv_sourcelinked ip_majortickmark = lv_majortickmark ip_minortickmark = lv_minortickmark ip_ticklblpos = lv_ticklblpos ip_crossax = lv_crossax ip_crosses = lv_crosses ip_crossbetween = lv_crossbetween. ENDIF. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. WHEN OTHERS. ENDCASE. ""legend CASE me->graph_type. WHEN c_graph_bars. node2 ?= node->find_from_name( name = 'legendPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_legendposval = ls_prop-val. node2 ?= node->find_from_name( name = 'overlay' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_overlayval = ls_prop-val. WHEN c_graph_line. node2 ?= node->find_from_name( name = 'legendPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_legendposval = ls_prop-val. node2 ?= node->find_from_name( name = 'overlay' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_overlayval = ls_prop-val. WHEN c_graph_pie. node2 ?= node->find_from_name( name = 'legendPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_legendposval = ls_prop-val. node2 ?= node->find_from_name( name = 'overlay' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_overlayval = ls_prop-val. node2 ?= node->find_from_name( name = 'pPr' namespace = 'a' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_pprrtl = ls_prop-rtl. node2 ?= node->find_from_name( name = 'endParaRPr' namespace = 'a' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_endpararprlang = ls_prop-lang. WHEN OTHERS. ENDCASE. node2 ?= node->find_from_name( name = 'plotVisOnly' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_plotvisonlyval = ls_prop-val. node2 ?= node->find_from_name( name = 'dispBlanksAs' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_dispblanksasval = ls_prop-val. node2 ?= node->find_from_name( name = 'showDLblsOverMax' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_showdlblsovermaxval = ls_prop-val. ""--------------------- node2 ?= node->find_from_name( name = 'pageMargins' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_pagemargins ). me->graph->pagemargins = ls_pagemargins. ENDMETHOD. METHOD pixel2emu. * suppose 96 DPI IF ip_dpi IS SUPPLIED. r_emu = ip_pixel * 914400 / ip_dpi. ELSE. * suppose 96 DPI r_emu = ip_pixel * 914400 / 96. ENDIF. ENDMETHOD. METHOD set_media. IF ip_media IS SUPPLIED. media = ip_media. ENDIF. media_type = ip_media_type. media_source = c_media_source_xstring. IF ip_width IS SUPPLIED. size-width = ip_width. ENDIF. IF ip_height IS SUPPLIED. size-height = ip_height. ENDIF. ENDMETHOD. METHOD set_media_mime. DATA: lv_language TYPE sylangu. io = ip_io. media_source = c_media_source_mime. size-width = ip_width. size-height = ip_height. lv_language = sy-langu. cl_wb_mime_repository=>load_mime( EXPORTING io = ip_io IMPORTING filename = media_name ""mimetype = media_type CHANGING language = lv_language ). SPLIT media_name AT '.' INTO media_name media_type. ENDMETHOD. METHOD set_media_www. DATA: lv_value(20). media_key_www = ip_key. media_source = c_media_source_www. CALL FUNCTION 'WWWPARAMS_READ' EXPORTING relid = media_key_www-relid objid = media_key_www-objid name = 'fileextension' IMPORTING value = lv_value. media_type = lv_value. SHIFT media_type LEFT DELETING LEADING '.'. size-width = ip_width. size-height = ip_height. ENDMETHOD. METHOD set_position. from_loc-col = zcl_excel_common=>convert_column2int( ip_from_col ) - 1. IF ip_coloff IS SUPPLIED. from_loc-col_offset = ip_coloff. ENDIF. from_loc-row = ip_from_row - 1. IF ip_rowoff IS SUPPLIED. from_loc-row_offset = ip_rowoff. ENDIF. anchor = anchor_one_cell. ENDMETHOD. METHOD set_position2. DATA: lv_anchor TYPE zexcel_drawing_anchor. lv_anchor = ip_anchor. IF lv_anchor IS INITIAL. IF ip_to IS NOT INITIAL. lv_anchor = anchor_two_cell. ELSE. lv_anchor = anchor_one_cell. ENDIF. ENDIF. CASE lv_anchor. WHEN anchor_absolute OR anchor_one_cell. CLEAR: me->to_loc. WHEN anchor_two_cell. CLEAR: me->size. ENDCASE. me->from_loc = ip_from. me->to_loc = ip_to. me->anchor = lv_anchor. ENDMETHOD. ENDCLASS. ",13497,True,3684.4637256164447,median "// RUN: %clang_cc1 -triple i686-windows-msvc -emit-llvm -std=c++1y -fno-threadsafe-statics -fms-extensions -O1 -mconstructor-aliases -disable-llvm-passes -o - %s -w -fms-compatibility-version=19.00 | FileCheck --check-prefix=MSC --check-prefix=M32 -check-prefix=MSVC2015 -check-prefix=M32MSVC2015 %s // RUN: %clang_cc1 -triple i686-windows-msvc -emit-llvm -std=c++1y -fno-threadsafe-statics -fms-extensions -O1 -mconstructor-aliases -disable-llvm-passes -o - %s -w -fms-compatibility-version=18.00 | FileCheck --check-prefix=MSC --check-prefix=M32 -check-prefix=MSVC2013 -check-prefix=M32MSVC2013 %s // RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm -std=c++1y -fno-threadsafe-statics -fms-extensions -O0 -o - %s -w -fms-compatibility-version=19.00 | FileCheck --check-prefix=MSC --check-prefix=M64 -check-prefix=MSVC2015 -check-prefix=M64MSVC2015 %s // RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm -std=c++1y -fno-threadsafe-statics -fms-extensions -O0 -o - %s -w -fms-compatibility-version=18.00 | FileCheck --check-prefix=MSC --check-prefix=M64 -check-prefix=MSVC2013 -check-prefix=M64MSVC2013 %s // RUN: %clang_cc1 -triple i686-windows-gnu -emit-llvm -std=c++1y -fno-threadsafe-statics -fms-extensions -O0 -o - %s -w | FileCheck --check-prefix=GNU --check-prefix=G32 %s // RUN: %clang_cc1 -triple x86_64-windows-gnu -emit-llvm -std=c++1y -fno-threadsafe-statics -fms-extensions -O0 -o - %s -w | FileCheck --check-prefix=GNU --check-prefix=G64 %s // Helper structs to make templates more expressive. struct ImplicitInst_Exported {}; struct ExplicitDecl_Exported {}; struct ExplicitInst_Exported {}; struct ExplicitSpec_Exported {}; struct ExplicitSpec_Def_Exported {}; struct ExplicitSpec_InlineDef_Exported {}; struct ExplicitSpec_NotExported {}; struct External { int v; }; #define JOIN2(x, y) x##y #define JOIN(x, y) JOIN2(x, y) #define UNIQ(name) JOIN(name, __LINE__) #define USEVAR(var) int UNIQ(use)() { return var; } #define USE(func) void UNIQ(use)() { func(); } #define USEMEMFUNC(class, func) void (class::*UNIQ(use)())() { return &class::func; } #define INSTVAR(var) template int var; #define INST(func) template void func(); // The vftable for struct W is comdat largest because we have RTTI. // M32-DAG: $""\\01??_7W@@6B@"" = comdat largest //===----------------------------------------------------------------------===// // Globals //===----------------------------------------------------------------------===// // Declarations are not exported. // MSC-NOT: @""\\01?ExternGlobalDecl@@3HA"" // GNU-NOT: @ExternGlobalDecl __declspec(dllexport) extern int ExternGlobalDecl; // dllexport implies a definition. // MSC-DAG: @""\\01?GlobalDef@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @GlobalDef = dllexport global i32 0, align 4 __declspec(dllexport) int GlobalDef; // Export definition. // MSC-DAG: @""\\01?GlobalInit1@@3HA"" = dllexport global i32 1, align 4 // GNU-DAG: @GlobalInit1 = dllexport global i32 1, align 4 __declspec(dllexport) int GlobalInit1 = 1; // MSC-DAG: @""\\01?GlobalInit2@@3HA"" = dllexport global i32 1, align 4 // GNU-DAG: @GlobalInit2 = dllexport global i32 1, align 4 int __declspec(dllexport) GlobalInit2 = 1; // Declare, then export definition. // MSC-DAG: @""\\01?GlobalDeclInit@@3HA"" = dllexport global i32 1, align 4 // GNU-DAG: @GlobalDeclInit = dllexport global i32 1, align 4 __declspec(dllexport) extern int GlobalDeclInit; int GlobalDeclInit = 1; // Redeclarations // MSC-DAG: @""\\01?GlobalRedecl1@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @GlobalRedecl1 = dllexport global i32 0, align 4 __declspec(dllexport) extern int GlobalRedecl1; __declspec(dllexport) int GlobalRedecl1; // MSC-DAG: @""\\01?GlobalRedecl2@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @GlobalRedecl2 = dllexport global i32 0, align 4 __declspec(dllexport) extern int GlobalRedecl2; int GlobalRedecl2; // MSC-DAG: @""\\01?ExternalGlobal@ns@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @_ZN2ns14ExternalGlobalE = dllexport global i32 0, align 4 namespace ns { __declspec(dllexport) int ExternalGlobal; } // MSC-DAG: @""\\01?ExternalAutoTypeGlobal@@3UExternal@@A"" = dllexport global %struct.External zeroinitializer, align 4 // GNU-DAG: @ExternalAutoTypeGlobal = dllexport global %struct.External zeroinitializer, align 4 __declspec(dllexport) auto ExternalAutoTypeGlobal = External(); int f(); // MSC-DAG: @""\\01?x@?1??nonInlineStaticLocalsFunc@@YAHXZ@4HA"" = internal {{(unnamed_addr )*}}global i32 0 // MSC-DAG: @""\\01?$S1@?1??nonInlineStaticLocalsFunc@@YAHXZ@4IA"" = internal {{(unnamed_addr )*}}global i32 0 int __declspec(dllexport) nonInlineStaticLocalsFunc() { static int x = f(); return x++; }; // MSC-DAG: @""\\01?x@?1??inlineStaticLocalsFunc@@YAHXZ@4HA"" = weak_odr dllexport global i32 0, comdat // MSC-DAG: @""\\01??_B?1??inlineStaticLocalsFunc@@YAHXZ@51"" = weak_odr dllexport global i32 0, comdat // Note: MinGW doesn't seem to export the static local here. inline int __declspec(dllexport) inlineStaticLocalsFunc() { static int x = f(); return x++; } //===----------------------------------------------------------------------===// // Variable templates //===----------------------------------------------------------------------===// // Declarations are not exported. // dllexport implies a definition. // MSC-NOT: @""\\01??$VarTmplDef@UExplicitInst_Exported@@@@3HA"" // GNU-NOT: @_Z10VarTmplDefI21ExplicitInst_ExportedE template __declspec(dllexport) int VarTmplDef; INSTVAR(VarTmplDef) // MSC-DAG: @""\\01??$VarTmplImplicitDef@UImplicitInst_Exported@@@@3HA"" = external dllexport global // GNU-DAG: @_Z18VarTmplImplicitDefI21ImplicitInst_ExportedE = external dllexport global template __declspec(dllexport) int VarTmplImplicitDef; USEVAR(VarTmplImplicitDef) // Export definition. // MSC-DAG: @""\\01??$VarTmplInit1@UExplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z12VarTmplInit1I21ExplicitInst_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 template __declspec(dllexport) int VarTmplInit1 = 1; INSTVAR(VarTmplInit1) // MSC-DAG: @""\\01??$VarTmplInit2@UExplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z12VarTmplInit2I21ExplicitInst_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 template int __declspec(dllexport) VarTmplInit2 = 1; INSTVAR(VarTmplInit2) // Declare, then export definition. // MSC-DAG: @""\\01??$VarTmplDeclInit@UExplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z15VarTmplDeclInitI21ExplicitInst_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 template __declspec(dllexport) extern int VarTmplDeclInit; template int VarTmplDeclInit = 1; INSTVAR(VarTmplDeclInit) // Redeclarations // MSC-DAG: @""\\01??$VarTmplRedecl1@UExplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z14VarTmplRedecl1I21ExplicitInst_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 template __declspec(dllexport) extern int VarTmplRedecl1; template __declspec(dllexport) int VarTmplRedecl1 = 1; INSTVAR(VarTmplRedecl1) // MSC-DAG: @""\\01??$VarTmplRedecl2@UExplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z14VarTmplRedecl2I21ExplicitInst_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 template __declspec(dllexport) extern int VarTmplRedecl2; template int VarTmplRedecl2 = 1; INSTVAR(VarTmplRedecl2) // MSC-DAG: @""\\01??$ExternalVarTmpl@UExplicitInst_Exported@@@ns@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_ZN2ns15ExternalVarTmplI21ExplicitInst_ExportedEE = weak_odr dllexport global i32 1, comdat, align 4 namespace ns { template __declspec(dllexport) int ExternalVarTmpl = 1; } INSTVAR(ns::ExternalVarTmpl) // MSC-DAG: @""\\01??$ExternalAutoTypeVarTmpl@UExplicitInst_Exported@@@@3UExternal@@A"" = weak_odr dllexport global %struct.External zeroinitializer, comdat, align 4 // GNU-DAG: @_Z23ExternalAutoTypeVarTmplI21ExplicitInst_ExportedE = weak_odr dllexport global %struct.External zeroinitializer, comdat, align 4 template __declspec(dllexport) auto ExternalAutoTypeVarTmpl = External(); template External ExternalAutoTypeVarTmpl; template int VarTmpl = 1; template __declspec(dllexport) int ExportedVarTmpl = 1; // Export implicit instantiation of an exported variable template. // MSC-DAG: @""\\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z15ExportedVarTmplI21ImplicitInst_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 USEVAR(ExportedVarTmpl) // Export explicit instantiation declaration of an exported variable template. // MSC-DAG: @""\\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z15ExportedVarTmplI21ExplicitDecl_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 extern template int ExportedVarTmpl; template int ExportedVarTmpl; // Export explicit instantiation definition of an exported variable template. // MSC-DAG: @""\\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z15ExportedVarTmplI21ExplicitInst_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 template __declspec(dllexport) int ExportedVarTmpl; // Export specialization of an exported variable template. // MSC-DAG: @""\\01??$ExportedVarTmpl@UExplicitSpec_Exported@@@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @_Z15ExportedVarTmplI21ExplicitSpec_ExportedE = dllexport global i32 0, align 4 template<> __declspec(dllexport) int ExportedVarTmpl; // MSC-DAG: @""\\01??$ExportedVarTmpl@UExplicitSpec_Def_Exported@@@@3HA"" = dllexport global i32 1, align 4 // GNU-DAG: @_Z15ExportedVarTmplI25ExplicitSpec_Def_ExportedE = dllexport global i32 1, align 4 template<> __declspec(dllexport) int ExportedVarTmpl = 1; // Not exporting specialization of an exported variable template without // explicit dllexport. // MSC-DAG: @""\\01??$ExportedVarTmpl@UExplicitSpec_NotExported@@@@3HA"" = global i32 0, align 4 // GNU-DAG: @_Z15ExportedVarTmplI24ExplicitSpec_NotExportedE = global i32 0, align 4 template<> int ExportedVarTmpl; // Export explicit instantiation declaration of a non-exported variable template. // MSC-DAG: @""\\01??$VarTmpl@UExplicitDecl_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z7VarTmplI21ExplicitDecl_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 extern template __declspec(dllexport) int VarTmpl; template __declspec(dllexport) int VarTmpl; // Export explicit instantiation definition of a non-exported variable template. // MSC-DAG: @""\\01??$VarTmpl@UExplicitInst_Exported@@@@3HA"" = weak_odr dllexport global i32 1, comdat, align 4 // GNU-DAG: @_Z7VarTmplI21ExplicitInst_ExportedE = weak_odr dllexport global i32 1, comdat, align 4 template __declspec(dllexport) int VarTmpl; // Export specialization of a non-exported variable template. // MSC-DAG: @""\\01??$VarTmpl@UExplicitSpec_Exported@@@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @_Z7VarTmplI21ExplicitSpec_ExportedE = dllexport global i32 0, align 4 template<> __declspec(dllexport) int VarTmpl; // MSC-DAG: @""\\01??$VarTmpl@UExplicitSpec_Def_Exported@@@@3HA"" = dllexport global i32 1, align 4 // GNU-DAG: @_Z7VarTmplI25ExplicitSpec_Def_ExportedE = dllexport global i32 1, align 4 template<> __declspec(dllexport) int VarTmpl = 1; //===----------------------------------------------------------------------===// // Functions //===----------------------------------------------------------------------===// // Declarations are not exported. // Export function definition. // MSC-DAG: define dllexport void @""\\01?def@@YAXXZ""() // GNU-DAG: define dllexport void @_Z3defv() __declspec(dllexport) void def() {} // extern ""C"" // MSC-DAG: define dllexport void @externC() // GNU-DAG: define dllexport void @externC() extern ""C"" __declspec(dllexport) void externC() {} // Export inline function. // MSC-DAG: define weak_odr dllexport void @""\\01?inlineFunc@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z10inlineFuncv() __declspec(dllexport) inline void inlineFunc() {} // MSC-DAG: define weak_odr dllexport void @""\\01?inlineDecl@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z10inlineDeclv() __declspec(dllexport) inline void inlineDecl(); void inlineDecl() {} // MSC-DAG: define weak_odr dllexport void @""\\01?inlineDef@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z9inlineDefv() __declspec(dllexport) void inlineDef(); inline void inlineDef() {} // Redeclarations // MSC-DAG: define dllexport void @""\\01?redecl1@@YAXXZ""() // GNU-DAG: define dllexport void @_Z7redecl1v() __declspec(dllexport) void redecl1(); __declspec(dllexport) void redecl1() {} // MSC-DAG: define dllexport void @""\\01?redecl2@@YAXXZ""() // GNU-DAG: define dllexport void @_Z7redecl2v() __declspec(dllexport) void redecl2(); void redecl2() {} // Friend functions // MSC-DAG: define dllexport void @""\\01?friend1@@YAXXZ""() // GNU-DAG: define dllexport void @_Z7friend1v() // MSC-DAG: define dllexport void @""\\01?friend2@@YAXXZ""() // GNU-DAG: define dllexport void @_Z7friend2v() struct FuncFriend { friend __declspec(dllexport) void friend1(); friend __declspec(dllexport) void friend2(); }; __declspec(dllexport) void friend1() {} void friend2() {} // Implicit declarations can be redeclared with dllexport. // MSC-DAG: define dllexport noalias i8* @""\\01??2@{{YAPAXI|YAPEAX_K}}@Z""( // GNU-DAG: define dllexport noalias i8* @_Znw{{[yj]}}( void* alloc(__SIZE_TYPE__ n); __declspec(dllexport) void* operator new(__SIZE_TYPE__ n) { return alloc(n); } // MSC-DAG: define dllexport void @""\\01?externalFunc@ns@@YAXXZ""() // GNU-DAG: define dllexport void @_ZN2ns12externalFuncEv() namespace ns { __declspec(dllexport) void externalFunc() {} } //===----------------------------------------------------------------------===// // Function templates //===----------------------------------------------------------------------===// // Export function template definition. // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmplDef@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z11funcTmplDefI21ExplicitInst_ExportedEvv() template __declspec(dllexport) void funcTmplDef() {} INST(funcTmplDef) // Export inline function template. // MSC-DAG: define weak_odr dllexport void @""\\01??$inlineFuncTmpl1@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z15inlineFuncTmpl1I21ExplicitInst_ExportedEvv() template __declspec(dllexport) inline void inlineFuncTmpl1() {} INST(inlineFuncTmpl1) // MSC-DAG: define weak_odr dllexport void @""\\01??$inlineFuncTmpl2@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z15inlineFuncTmpl2I21ExplicitInst_ExportedEvv() template inline void __attribute__((dllexport)) inlineFuncTmpl2() {} INST(inlineFuncTmpl2) // MSC-DAG: define weak_odr dllexport void @""\\01??$inlineFuncTmplDecl@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z18inlineFuncTmplDeclI21ExplicitInst_ExportedEvv() template __declspec(dllexport) inline void inlineFuncTmplDecl(); template void inlineFuncTmplDecl() {} INST(inlineFuncTmplDecl) // MSC-DAG: define weak_odr dllexport void @""\\01??$inlineFuncTmplDef@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z17inlineFuncTmplDefI21ExplicitInst_ExportedEvv() template __declspec(dllexport) void inlineFuncTmplDef(); template inline void inlineFuncTmplDef() {} INST(inlineFuncTmplDef) // Redeclarations // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmplRedecl1@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z15funcTmplRedecl1I21ExplicitInst_ExportedEvv() template __declspec(dllexport) void funcTmplRedecl1(); template __declspec(dllexport) void funcTmplRedecl1() {} INST(funcTmplRedecl1) // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmplRedecl2@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z15funcTmplRedecl2I21ExplicitInst_ExportedEvv() template __declspec(dllexport) void funcTmplRedecl2(); template void funcTmplRedecl2() {} INST(funcTmplRedecl2) // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmplRedecl3@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z15funcTmplRedecl3I21ExplicitInst_ExportedEvv() template __declspec(dllexport) void funcTmplRedecl3(); template void funcTmplRedecl3() {} INST(funcTmplRedecl3) // Function template friends // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmplFriend1@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z15funcTmplFriend1I21ExplicitInst_ExportedEvv() // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmplFriend2@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z15funcTmplFriend2I21ExplicitInst_ExportedEvv() struct FuncTmplFriend { template friend __declspec(dllexport) void funcTmplFriend1(); template friend __declspec(dllexport) void funcTmplFriend2(); }; template __declspec(dllexport) void funcTmplFriend1() {} template void funcTmplFriend2() {} INST(funcTmplFriend1) INST(funcTmplFriend2) // MSC-DAG: define weak_odr dllexport void @""\\01??$externalFuncTmpl@UExplicitInst_Exported@@@ns@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_ZN2ns16externalFuncTmplI21ExplicitInst_ExportedEEvv() namespace ns { template __declspec(dllexport) void externalFuncTmpl() {} } INST(ns::externalFuncTmpl) template void funcTmpl() {} template __declspec(dllexport) void exportedFuncTmpl() {} // Export implicit instantiation of an exported function template. // MSC-DAG: define weak_odr dllexport void @""\\01??$exportedFuncTmpl@UImplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z16exportedFuncTmplI21ImplicitInst_ExportedEvv() USE(exportedFuncTmpl) // Export explicit instantiation declaration of an exported function template. // MSC-DAG: define weak_odr dllexport void @""\\01??$exportedFuncTmpl@UExplicitDecl_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z16exportedFuncTmplI21ExplicitDecl_ExportedEvv() extern template void exportedFuncTmpl(); template void exportedFuncTmpl(); // Export explicit instantiation definition of an exported function template. // MSC-DAG: define weak_odr dllexport void @""\\01??$exportedFuncTmpl@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z16exportedFuncTmplI21ExplicitInst_ExportedEvv() template void exportedFuncTmpl(); // Export specialization of an exported function template. // MSC-DAG: define dllexport void @""\\01??$exportedFuncTmpl@UExplicitSpec_Def_Exported@@@@YAXXZ""() // GNU-DAG: define dllexport void @_Z16exportedFuncTmplI25ExplicitSpec_Def_ExportedEvv() template<> __declspec(dllexport) void exportedFuncTmpl() {} // MSC-DAG: define weak_odr dllexport void @""\\01??$exportedFuncTmpl@UExplicitSpec_InlineDef_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z16exportedFuncTmplI31ExplicitSpec_InlineDef_ExportedEvv() template<> __declspec(dllexport) inline void exportedFuncTmpl() {} // Not exporting specialization of an exported function template without // explicit dllexport. // MSC-DAG: define void @""\\01??$exportedFuncTmpl@UExplicitSpec_NotExported@@@@YAXXZ""() // GNU-DAG: define void @_Z16exportedFuncTmplI24ExplicitSpec_NotExportedEvv() template<> void exportedFuncTmpl() {} // Export explicit instantiation declaration of a non-exported function template. // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmpl@UExplicitDecl_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z8funcTmplI21ExplicitDecl_ExportedEvv() extern template __declspec(dllexport) void funcTmpl(); template __declspec(dllexport) void funcTmpl(); // Export explicit instantiation definition of a non-exported function template. // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmpl@UExplicitInst_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z8funcTmplI21ExplicitInst_ExportedEvv() template __declspec(dllexport) void funcTmpl(); // Export specialization of a non-exported function template. // MSC-DAG: define dllexport void @""\\01??$funcTmpl@UExplicitSpec_Def_Exported@@@@YAXXZ""() // GNU-DAG: define dllexport void @_Z8funcTmplI25ExplicitSpec_Def_ExportedEvv() template<> __declspec(dllexport) void funcTmpl() {} // MSC-DAG: define weak_odr dllexport void @""\\01??$funcTmpl@UExplicitSpec_InlineDef_Exported@@@@YAXXZ""() // GNU-DAG: define weak_odr dllexport void @_Z8funcTmplI31ExplicitSpec_InlineDef_ExportedEvv() template<> __declspec(dllexport) inline void funcTmpl() {} //===----------------------------------------------------------------------===// // Precedence //===----------------------------------------------------------------------===// // dllexport takes precedence over the dllimport if both are specified. // MSC-DAG: @""\\01?PrecedenceGlobal1A@@3HA"" = dllexport global i32 0, align 4 // MSC-DAG: @""\\01?PrecedenceGlobal1B@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @PrecedenceGlobal1A = dllexport global i32 0, align 4 // GNU-DAG: @PrecedenceGlobal1B = dllexport global i32 0, align 4 __attribute__((dllimport, dllexport)) int PrecedenceGlobal1A; // dllimport ignored __declspec(dllimport) __declspec(dllexport) int PrecedenceGlobal1B; // dllimport ignored // MSC-DAG: @""\\01?PrecedenceGlobal2A@@3HA"" = dllexport global i32 0, align 4 // MSC-DAG: @""\\01?PrecedenceGlobal2B@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @PrecedenceGlobal2A = dllexport global i32 0, align 4 // GNU-DAG: @PrecedenceGlobal2B = dllexport global i32 0, align 4 __attribute__((dllexport, dllimport)) int PrecedenceGlobal2A; // dllimport ignored __declspec(dllexport) __declspec(dllimport) int PrecedenceGlobal2B; // dllimport ignored // MSC-DAG: @""\\01?PrecedenceGlobalRedecl1@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @PrecedenceGlobalRedecl1 = dllexport global i32 0, align 4 __declspec(dllexport) extern int PrecedenceGlobalRedecl1; __declspec(dllimport) int PrecedenceGlobalRedecl1 = 0; // MSC-DAG: @""\\01?PrecedenceGlobalRedecl2@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @PrecedenceGlobalRedecl2 = dllexport global i32 0, align 4 __declspec(dllimport) extern int PrecedenceGlobalRedecl2; __declspec(dllexport) int PrecedenceGlobalRedecl2; // MSC-DAG: @""\\01?PrecedenceGlobalMixed1@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @PrecedenceGlobalMixed1 = dllexport global i32 0, align 4 __attribute__((dllexport)) extern int PrecedenceGlobalMixed1; __declspec(dllimport) int PrecedenceGlobalMixed1 = 0; // MSC-DAG: @""\\01?PrecedenceGlobalMixed2@@3HA"" = dllexport global i32 0, align 4 // GNU-DAG: @PrecedenceGlobalMixed2 = dllexport global i32 0, align 4 __attribute__((dllimport)) extern int PrecedenceGlobalMixed2; __declspec(dllexport) int PrecedenceGlobalMixed2; // MSC-DAG: define dllexport void @""\\01?precedence1A@@YAXXZ"" // MSC-DAG: define dllexport void @""\\01?precedence1B@@YAXXZ"" // GNU-DAG: define dllexport void @_Z12precedence1Av() // GNU-DAG: define dllexport void @_Z12precedence1Bv() void __attribute__((dllimport, dllexport)) precedence1A() {} void __declspec(dllimport) __declspec(dllexport) precedence1B() {} // MSC-DAG: define dllexport void @""\\01?precedence2A@@YAXXZ"" // MSC-DAG: define dllexport void @""\\01?precedence2B@@YAXXZ"" // GNU-DAG: define dllexport void @_Z12precedence2Av() // GNU-DAG: define dllexport void @_Z12precedence2Bv() void __attribute__((dllexport, dllimport)) precedence2A() {} void __declspec(dllexport) __declspec(dllimport) precedence2B() {} // MSC-DAG: define dllexport void @""\\01?precedenceRedecl1@@YAXXZ"" // GNU-DAG: define dllexport void @_Z17precedenceRedecl1v() void __declspec(dllimport) precedenceRedecl1(); void __declspec(dllexport) precedenceRedecl1() {} // MSC-DAG: define dllexport void @""\\01?precedenceRedecl2@@YAXXZ"" // GNU-DAG: define dllexport void @_Z17precedenceRedecl2v() void __declspec(dllexport) precedenceRedecl2(); void __declspec(dllimport) precedenceRedecl2() {} //===----------------------------------------------------------------------===// // Classes //===----------------------------------------------------------------------===// struct S { void __declspec(dllexport) a() {} // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?a@S@@QAEXXZ"" struct T { void __declspec(dllexport) a() {} // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?a@T@S@@QAEXXZ"" }; }; template struct SomeTemplate { SomeTemplate(T o = T()) : o(o) {} T o; }; // MSVC2015-DAG: define weak_odr dllexport {{.+}} @""\\01??4?$SomeTemplate@H@@Q{{.+}}@$$Q{{.+}}@@Z"" // MSVC2013-DAG: define weak_odr dllexport {{.+}} @""\\01??4?$SomeTemplate@H@@Q{{.+}}0@A{{.+}}0@@Z"" struct __declspec(dllexport) InheritFromTemplate : SomeTemplate {}; // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01??_F?$SomeTemplate@H@@QAEXXZ""({{.*}}) {{#[0-9]+}} comdat namespace PR23801 { template struct S { ~S() {} }; struct A { A(int); S s; }; struct __declspec(dllexport) B { B(A = 0) {} }; } // // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01??_FB@PR23801@@QAEXXZ""({{.*}}) {{#[0-9]+}} comdat struct __declspec(dllexport) T { // Copy assignment operator: // M32-DAG: define weak_odr dllexport x86_thiscallcc dereferenceable({{[0-9]+}}) %struct.T* @""\\01??4T@@QAEAAU0@ABU0@@Z"" // Explicitly defaulted copy constructur: T(const T&) = default; // M32MSVC2013-DAG: define weak_odr dllexport x86_thiscallcc %struct.T* @""\\01??0T@@QAE@ABU0@@Z"" void a() {} // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?a@T@@QAEXXZ"" static int b; // M32-DAG: @""\\01?b@T@@2HA"" = external dllexport global i32 static int c; // M32-DAG: @""\\01?c@T@@2HA"" = dllexport global i32 0, align 4 }; USEVAR(T::b) int T::c; // Export template class with static member variable // MSC-DAG: @""\\01?StaticClassVarExpTmplClass@?$TmplClass@H@@2HA"" = weak_odr dllexport global i32 0, comdat, align 4 // GNU-DAG: @_ZN9TmplClassIiE26StaticClassVarExpTmplClassE = weak_odr dllexport global i32 0, comdat, align 4 template struct __declspec(dllexport) TmplClass { static T StaticClassVarExpTmplClass; }; template T TmplClass::StaticClassVarExpTmplClass; // Export a definition of a template function. // MSC-DAG: define weak_odr dllexport i32 @""\\01??$TypeFunTmpl@H@@YAHH@Z"" // GNU-DAG: define weak_odr dllexport i32 @_Z11TypeFunTmplIiET_S0_ template T __declspec(dllexport) TypeFunTmpl(T t) { return t + t; } // Instantiate the exported template class and the exported template function. int useExportedTmplStaticAndFun() { return TmplClass::StaticClassVarExpTmplClass + TypeFunTmpl(10); } template struct __declspec(dllexport) U { void foo() {} }; struct __declspec(dllexport) V : public U { }; // U's assignment operator is emitted. // M32-DAG: define weak_odr dllexport x86_thiscallcc dereferenceable({{[0-9]+}}) %struct.U* @""\\01??4?$U@H@@QAEAAU0@ABU0@@Z"" struct __declspec(dllexport) W { virtual void foo(); }; void W::foo() {} // Default ctor: // M32-DAG: define weak_odr dllexport x86_thiscallcc %struct.W* @""\\01??0W@@QAE@XZ"" // Copy ctor: // M32-DAG: define weak_odr dllexport x86_thiscallcc %struct.W* @""\\01??0W@@QAE@ABU0@@Z"" // vftable: // M32-DAG: [[W_VTABLE:@.*]] = private unnamed_addr constant { [2 x i8*] } { [2 x i8*] [i8* bitcast (%rtti.CompleteObjectLocator* @""\\01??_R4W@@6B@"" to i8*), i8* bitcast (void (%struct.W*)* @""\\01?foo@W@@UAEXXZ"" to i8*)] }, comdat($""\\01??_7W@@6B@"") // M32-DAG: @""\\01??_7W@@6B@"" = dllexport unnamed_addr alias i8*, getelementptr inbounds ({ [2 x i8*] }, { [2 x i8*] }* [[W_VTABLE]], i32 0, i32 0, i32 1) // G32-DAG: @_ZTV1W = dllexport unnamed_addr constant { [3 x i8*] } { [3 x i8*] [i8* null, i8* bitcast ({ i8*, i8* }* @_ZTI1W to i8*), i8* bitcast (void (%struct.W*)* @_ZN1W3fooEv to i8*)] } struct __declspec(dllexport) X : public virtual W {}; // vbtable: // M32-DAG: @""\\01??_8X@@7B@"" = weak_odr dllexport unnamed_addr constant [2 x i32] [i32 0, i32 4] struct __declspec(dllexport) Y { // Move assignment operator: // MSVC2015-DAG: define weak_odr dllexport {{.+}} @""\\01??4Y@@Q{{.+}}@$$Q{{.+}}@@Z"" // MSVC2013-DAG: define weak_odr dllexport {{.+}} @""\\01??4Y@@Q{{.+}}0@A{{.+}}0@@Z"" int x; }; struct __declspec(dllexport) Z { virtual ~Z() {} }; // The scalar deleting dtor does not get exported: // M32-DAG: define linkonce_odr x86_thiscallcc i8* @""\\01??_GZ@@UAEPAXI@Z"" // The user-defined dtor does get exported: // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01??1Z@@UAE@XZ"" namespace UseDtorAlias { struct __declspec(dllexport) A { ~A(); }; struct __declspec(dllexport) B : A { ~B(); }; A::~A() { } B::~B() { } // Emit a alias definition of B's constructor. // M32-DAG: @""\\01??1B@UseDtorAlias@@QAE@XZ"" = dllexport alias {{.*}} @""\\01??1A@UseDtorAlias@@QAE@XZ"" } struct __declspec(dllexport) DefaultedCtorsDtors { DefaultedCtorsDtors() = default; // M32MSVC2013-DAG: define weak_odr dllexport x86_thiscallcc %struct.DefaultedCtorsDtors* @""\\01??0DefaultedCtorsDtors@@QAE@XZ"" ~DefaultedCtorsDtors() = default; // M32MSVC2013-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01??1DefaultedCtorsDtors@@QAE@XZ"" }; // Export defaulted member function definitions declared inside class. struct __declspec(dllexport) ExportDefaultedInclassDefs { ExportDefaultedInclassDefs() = default; // M32VS2013-DAG: define weak_odr dllexport x86_thiscallcc %struct.ExportDefaultedInclassDefs* @""\\01??0ExportDefaultedInclassDefs@@QAE@XZ""(%struct.ExportDefaultedInclassDefs* returned %this) // M64VS2013-DAG: define weak_odr dllexport %struct.ExportDefaultedInclassDefs* @""\\01??0ExportDefaultedInclassDefs@@QEAA@XZ""(%struct.ExportDefaultedInclassDefs* returned %this) // M32VS2015-NOT: define weak_odr dllexport x86_thiscallcc %struct.ExportDefaultedInclassDefs* @""\\01??0ExportDefaultedInclassDefs@@QAE@XZ""(%struct.ExportDefaultedInclassDefs* returned %this) // M64VS2015-NOT: define weak_odr dllexport %struct.ExportDefaultedInclassDefs* @""\\01??0ExportDefaultedInclassDefs@@QEAA@XZ""(%struct.ExportDefaultedInclassDefs* returned %this) ~ExportDefaultedInclassDefs() = default; // M32VS2013-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01??1ExportDefaultedInclassDefs@@QAE@XZ""(%struct.ExportDefaultedInclassDefs* %this) // M64VS2013-DAG: define weak_odr dllexport void @""\\01??1ExportDefaultedInclassDefs@@QEAA@XZ""(%struct.ExportDefaultedInclassDefs* %this) // M32VS2015-NOT: define weak_odr dllexport x86_thiscallcc void @""\\01??1ExportDefaultedInclassDefs@@QAE@XZ""(%struct.ExportDefaultedInclassDefs* %this) // M64VS2015-NOT: define weak_odr dllexport void @""\\01??1ExportDefaultedInclassDefs@@QEAA@XZ""(%struct.ExportDefaultedInclassDefs* %this) ExportDefaultedInclassDefs(const ExportDefaultedInclassDefs&) = default; // M32VS2013-DAG: define weak_odr dllexport x86_thiscallcc %struct.ExportDefaultedInclassDefs* @""\\01??0ExportDefaultedInclassDefs@@QAE@ABU0@@Z""(%struct.ExportDefaultedInclassDefs* returned %this, %struct.ExportDefaultedInclassDefs* dereferenceable({{[0-9]+}})) // M64VS2013-DAG: define weak_odr dllexport %struct.ExportDefaultedInclassDefs* @""\\01??0ExportDefaultedInclassDefs@@QEAA@AEBU0@@Z""(%struct.ExportDefaultedInclassDefs* returned %this, %struct.ExportDefaultedInclassDefs* dereferenceable({{[0-9]+}})) // M32VS2015-NOT: define weak_odr dllexport x86_thiscallcc %struct.ExportDefaultedInclassDefs* @""\\01??0ExportDefaultedInclassDefs@@QAE@ABU0@@Z""(%struct.ExportDefaultedInclassDefs* returned %this, %struct.ExportDefaultedInclassDefs* dereferenceable({{[0-9]+}})) // M64VS2015-NOT: define weak_odr dllexport %struct.ExportDefaultedInclassDefs* @""\\01??0ExportDefaultedInclassDefs@@QEAA@AEBU0@@Z""(%struct.ExportDefaultedInclassDefs* returned %this, %struct.ExportDefaultedInclassDefs* dereferenceable({{[0-9]+}})) ExportDefaultedInclassDefs& operator=(const ExportDefaultedInclassDefs&) = default; // M32-DAG: define weak_odr dllexport x86_thiscallcc dereferenceable({{[0-9]+}}) %struct.ExportDefaultedInclassDefs* @""\\01??4ExportDefaultedInclassDefs@@QAEAAU0@ABU0@@Z""(%struct.ExportDefaultedInclassDefs* %this, %struct.ExportDefaultedInclassDefs* dereferenceable({{[0-9]+}})) // M64-DAG: define weak_odr dllexport dereferenceable({{[0-9]+}}) %struct.ExportDefaultedInclassDefs* @""\\01??4ExportDefaultedInclassDefs@@QEAAAEAU0@AEBU0@@Z""(%struct.ExportDefaultedInclassDefs* %this, %struct.ExportDefaultedInclassDefs* dereferenceable({{[0-9]+}})) }; namespace ReferencedInlineMethodInNestedClass { struct __declspec(dllexport) S { void foo() { t->bar(); } struct T { void bar() {} }; T *t; }; // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?foo@S@ReferencedInlineMethodInNestedClass@@QAEXXZ"" // M32-DAG: define linkonce_odr x86_thiscallcc void @""\\01?bar@T@S@ReferencedInlineMethodInNestedClass@@QAEXXZ"" } // MS ignores DLL attributes on partial specializations. template struct PartiallySpecializedClassTemplate {}; template struct __declspec(dllexport) PartiallySpecializedClassTemplate { void f(); }; template void PartiallySpecializedClassTemplate::f() {} USEMEMFUNC(PartiallySpecializedClassTemplate, f); // M32-DAG: define linkonce_odr x86_thiscallcc void @""\\01?f@?$PartiallySpecializedClassTemplate@PAX@@QAEXXZ"" // G32-DAG: define weak_odr dllexport x86_thiscallcc void @_ZN33PartiallySpecializedClassTemplateIPvE1fEv // Attributes on explicit specializations are honored. template struct ExplicitlySpecializedClassTemplate {}; template <> struct __declspec(dllexport) ExplicitlySpecializedClassTemplate { void f(); }; void ExplicitlySpecializedClassTemplate::f() {} USEMEMFUNC(ExplicitlySpecializedClassTemplate, f); // M32-DAG: define dllexport x86_thiscallcc void @""\\01?f@?$ExplicitlySpecializedClassTemplate@PAX@@QAEXXZ"" // G32-DAG: define dllexport x86_thiscallcc void @_ZN34ExplicitlySpecializedClassTemplateIPvE1fEv // MS inherits DLL attributes to partial specializations. template struct __declspec(dllexport) PartiallySpecializedExportedClassTemplate {}; template struct PartiallySpecializedExportedClassTemplate { void f() {} }; USEMEMFUNC(PartiallySpecializedExportedClassTemplate, f); // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$PartiallySpecializedExportedClassTemplate@PAX@@QAEXXZ"" // G32-DAG: define linkonce_odr x86_thiscallcc void @_ZN41PartiallySpecializedExportedClassTemplateIPvE1fEv // MS ignores DLL attributes on partial specializations; inheritance still works though. template struct __declspec(dllexport) PartiallySpecializedExportedClassTemplate2 {}; template struct __declspec(dllimport) PartiallySpecializedExportedClassTemplate2 { void f(); }; template void PartiallySpecializedExportedClassTemplate2::f() {} USEMEMFUNC(PartiallySpecializedExportedClassTemplate2, f); // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$PartiallySpecializedExportedClassTemplate2@PAX@@QAEXXZ"" // G32-DAG: declare dllimport x86_thiscallcc void @_ZN42PartiallySpecializedExportedClassTemplate2IPvE1fEv // Attributes on the instantiation take precedence over attributes on the template. template struct __declspec(dllimport) ExplicitlyInstantiatedWithDifferentAttr { void f() {} }; template struct __declspec(dllexport) ExplicitlyInstantiatedWithDifferentAttr; USEMEMFUNC(ExplicitlyInstantiatedWithDifferentAttr, f); // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$ExplicitlyInstantiatedWithDifferentAttr@H@@QAEXXZ"" // Don't create weak dllexport aliases. (PR21373) struct NonExportedBaseClass { virtual ~NonExportedBaseClass(); }; NonExportedBaseClass::~NonExportedBaseClass() {} struct __declspec(dllexport) ExportedDerivedClass : NonExportedBaseClass {}; // M32-DAG: weak_odr dllexport x86_thiscallcc void @""\\01??1ExportedDerivedClass@@UAE@XZ"" // Do not assert about generating code for constexpr functions twice during explicit instantiation (PR21718). template struct ExplicitInstConstexprMembers { // Copy assignment operator // M32-DAG: define weak_odr dllexport x86_thiscallcc dereferenceable(1) %struct.ExplicitInstConstexprMembers* @""\\01??4?$ExplicitInstConstexprMembers@X@@QAEAAU0@ABU0@@Z"" constexpr ExplicitInstConstexprMembers() {} // M32-DAG: define weak_odr dllexport x86_thiscallcc %struct.ExplicitInstConstexprMembers* @""\\01??0?$ExplicitInstConstexprMembers@X@@QAE@XZ"" ExplicitInstConstexprMembers(const ExplicitInstConstexprMembers&) = default; // M32MSVC2013-DAG: define weak_odr dllexport x86_thiscallcc %struct.ExplicitInstConstexprMembers* @""\\01??0?$ExplicitInstConstexprMembers@X@@QAE@ABU0@@Z"" constexpr int f() const { return 42; } // M32-DAG: define weak_odr dllexport x86_thiscallcc i32 @""\\01?f@?$ExplicitInstConstexprMembers@X@@QBEHXZ"" }; template struct __declspec(dllexport) ExplicitInstConstexprMembers; template struct ExplicitInstantiationDeclTemplate { void f() {} }; extern template struct __declspec(dllexport) ExplicitInstantiationDeclTemplate; USEMEMFUNC(ExplicitInstantiationDeclTemplate, f); // M32-DAG: {{declare|define available_externally}} x86_thiscallcc void @""\\01?f@?$ExplicitInstantiationDeclTemplate@H@@QAEXXZ"" template struct __declspec(dllexport) ExplicitInstantiationDeclExportedTemplate { void f() {} }; extern template struct ExplicitInstantiationDeclExportedTemplate; USEMEMFUNC(ExplicitInstantiationDeclExportedTemplate, f); // M32-DAG: {{declare|define available_externally}} x86_thiscallcc void @""\\01?f@?$ExplicitInstantiationDeclExportedTemplate@H@@QAEXXZ"" template struct ExplicitInstantiationDeclExportedDefTemplate { void f() {} ExplicitInstantiationDeclExportedDefTemplate() {} }; extern template struct ExplicitInstantiationDeclExportedDefTemplate; template struct __declspec(dllexport) ExplicitInstantiationDeclExportedDefTemplate; USEMEMFUNC(ExplicitInstantiationDeclExportedDefTemplate, f); // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$ExplicitInstantiationDeclExportedDefTemplate@H@@QAEXXZ"" // M32-DAG: define weak_odr dllexport x86_thiscallcc %struct.ExplicitInstantiationDeclExportedDefTemplate* @""\\01??0?$ExplicitInstantiationDeclExportedDefTemplate@H@@QAE@XZ"" // G32-DAG: define weak_odr x86_thiscallcc void @_ZN44ExplicitInstantiationDeclExportedDefTemplateIiE1fEv template struct ImplicitInstantiationExportedExplicitInstantiationDefTemplate { virtual void f() {} }; ImplicitInstantiationExportedExplicitInstantiationDefTemplate ImplicitInstantiationExportedExplicitInstantiationDefTemplateInstance; template struct __declspec(dllexport) ImplicitInstantiationExportedExplicitInstantiationDefTemplate; USEMEMFUNC(ImplicitInstantiationExportedExplicitInstantiationDefTemplate, f); // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$ImplicitInstantiationExportedExplicitInstantiationDefTemplate@H@@UAEXXZ"" // G32-DAG: define weak_odr x86_thiscallcc void @_ZN61ImplicitInstantiationExportedExplicitInstantiationDefTemplateIiE1fEv template struct __declspec(dllexport) ImplicitInstantiationExplicitInstantiationDefExportedTemplate { virtual void f() {} }; ImplicitInstantiationExplicitInstantiationDefExportedTemplate ImplicitInstantiationExplicitInstantiationDefExportedTemplateInstance; template struct ImplicitInstantiationExplicitInstantiationDefExportedTemplate; USEMEMFUNC(ImplicitInstantiationExplicitInstantiationDefExportedTemplate, f); // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$ImplicitInstantiationExplicitInstantiationDefExportedTemplate@H@@UAEXXZ"" // G32-DAG: define weak_odr x86_thiscallcc void @_ZN61ImplicitInstantiationExplicitInstantiationDefExportedTemplateIiE1fEv template struct __declspec(dllexport) ImplicitInstantiationExportedExplicitInstantiationDefExportedTemplate { virtual void f() {} }; ImplicitInstantiationExportedExplicitInstantiationDefExportedTemplate ImplicitInstantiationExportedExplicitInstantiationDefExportedTemplateInstance; template struct __declspec(dllexport) ImplicitInstantiationExportedExplicitInstantiationDefExportedTemplate; USEMEMFUNC(ImplicitInstantiationExportedExplicitInstantiationDefExportedTemplate, f); // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$ImplicitInstantiationExportedExplicitInstantiationDefExportedTemplate@H@@UAEXXZ"" // G32-DAG: define weak_odr x86_thiscallcc void @_ZN69ImplicitInstantiationExportedExplicitInstantiationDefExportedTemplateIiE1fEv namespace { struct InternalLinkageType {}; } struct __declspec(dllexport) PR23308 { void f(InternalLinkageType*); }; void PR23308::f(InternalLinkageType*) {} long use(PR23308* p) { p->f(nullptr); } // M32-DAG: define internal x86_thiscallcc void @""\\01?f@PR23308@@QAEXPAUInternalLinkageType@?A@@@Z"" template struct PR23770BaseTemplate { void f() {} }; template struct PR23770DerivedTemplate : PR23770BaseTemplate {}; extern template struct PR23770DerivedTemplate; template struct __declspec(dllexport) PR23770DerivedTemplate; // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$PR23770BaseTemplate@H@@QAEXXZ"" namespace InClassInits { struct __declspec(dllexport) S { int x = 42; }; // M32-DAG: define weak_odr dllexport x86_thiscallcc %""struct.InClassInits::S""* @""\\01??0S@InClassInits@@QAE@XZ"" // dllexport an already instantiated class template. template struct Base { int x = 42; }; Base base; struct __declspec(dllexport) T : Base { }; // M32-DAG: define weak_odr dllexport x86_thiscallcc %""struct.InClassInits::Base""* @""\\01??0?$Base@H@InClassInits@@QAE@XZ"" struct A { A(int); }; struct __declspec(dllexport) U { // Class with both default constructor closure and in-class initializer. U(A = 0) {} int x = 0; }; // M32-DAG: define weak_odr dllexport x86_thiscallcc %""struct.InClassInits::U""* @""\\01??0U@InClassInits@@QAE@UA@1@@Z"" struct Evil { template struct Base { int x = 0; }; struct S : Base {}; // The already instantiated Base becomes dllexported below, but the // in-class initializer for Base<>::x still hasn't been parsed, so emitting // the default ctor must still be delayed. struct __declspec(dllexport) T : Base {}; }; // M32-DAG: define weak_odr dllexport x86_thiscallcc %""struct.InClassInits::Evil::Base""* @""\\01??0?$Base@H@Evil@InClassInits@@QAE@XZ"" template struct Foo {}; template struct Bar { Bar &operator=(Foo) {} }; struct __declspec(dllexport) Baz { Bar n; }; // After parsing Baz, in ActOnFinishCXXNonNestedClass we would synthesize // Baz's operator=, causing instantiation of Foo after which // ActOnFinishCXXNonNestedClass is called, and we would bite our own tail. // M32-DAG: define weak_odr dllexport x86_thiscallcc dereferenceable(1) %""struct.InClassInits::Baz""* @""\\01??4Baz@InClassInits@@QAEAAU01@ABU01@@Z"" } // We had an issue where instantiating A would force emission of B's delayed // exported methods. namespace pr26490 { template struct A { }; struct __declspec(dllexport) B { B(int = 0) {} A m_fn1() {} }; // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01??_FB@pr26490@@QAEXXZ"" } // dllexport trumps dllexport on an explicit instantiation. template struct ExplicitInstantiationTwoAttributes { void f() {} }; template struct __declspec(dllexport) __declspec(dllimport) ExplicitInstantiationTwoAttributes; // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?f@?$ExplicitInstantiationTwoAttributes@H@@QAEXXZ"" //===----------------------------------------------------------------------===// // Classes with template base classes //===----------------------------------------------------------------------===// template struct ClassTemplate { void func(); }; template void ClassTemplate::func() {} template struct __declspec(dllexport) ExportedClassTemplate { void func(); }; template void ExportedClassTemplate::func() {} template struct __declspec(dllimport) ImportedClassTemplate { void func(); }; template void ImportedClassTemplate::func() {} template struct ExplicitlySpecializedTemplate { void func() {} }; template <> struct ExplicitlySpecializedTemplate { void func(); }; void ExplicitlySpecializedTemplate::func() {} template struct ExplicitlyExportSpecializedTemplate { void func() {} }; template <> struct __declspec(dllexport) ExplicitlyExportSpecializedTemplate { void func(); }; void ExplicitlyExportSpecializedTemplate::func() {} template struct ExplicitlyImportSpecializedTemplate { void func(); }; template <> struct __declspec(dllimport) ExplicitlyImportSpecializedTemplate { void func(); }; template struct ExplicitlyInstantiatedTemplate { void func(); }; template void ExplicitlyInstantiatedTemplate::func() {} template struct ExplicitlyInstantiatedTemplate; template struct ExplicitlyExportInstantiatedTemplate { void func(); }; template void ExplicitlyExportInstantiatedTemplate::func() {} template struct __declspec(dllexport) ExplicitlyExportInstantiatedTemplate; template struct ExplicitlyImportInstantiatedTemplate { void func(); }; template struct __declspec(dllimport) ExplicitlyImportInstantiatedTemplate; // MS: ClassTemplate gets exported. struct __declspec(dllexport) DerivedFromTemplate : public ClassTemplate {}; USEMEMFUNC(DerivedFromTemplate, func) // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?func@?$ClassTemplate@H@@QAEXXZ"" // G32-DAG: define linkonce_odr x86_thiscallcc void @_ZN13ClassTemplateIiE4funcEv // ExportedTemplate is explicitly exported. struct __declspec(dllexport) DerivedFromExportedTemplate : public ExportedClassTemplate {}; USEMEMFUNC(DerivedFromExportedTemplate, func) // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?func@?$ExportedClassTemplate@H@@QAEXXZ"" // G32-DAG: define weak_odr dllexport x86_thiscallcc void @_ZN21ExportedClassTemplateIiE4funcEv // ImportedClassTemplate is explicitly imported. struct __declspec(dllexport) DerivedFromImportedTemplate : public ImportedClassTemplate {}; USEMEMFUNC(DerivedFromImportedTemplate, func) // M32-DAG: {{declare|define available_externally}} dllimport x86_thiscallcc void @""\\01?func@?$ImportedClassTemplate@H@@QAEXXZ"" // G32-DAG: declare dllimport x86_thiscallcc void @_ZN21ImportedClassTemplateIiE4funcEv // Base class already implicitly instantiated without dll attribute. struct DerivedFromTemplateD : public ClassTemplate {}; struct __declspec(dllexport) DerivedFromTemplateD2 : public ClassTemplate {}; USEMEMFUNC(DerivedFromTemplateD2, func) // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?func@?$ClassTemplate@N@@QAEXXZ"" // G32-DAG: define linkonce_odr x86_thiscallcc void @_ZN13ClassTemplateIdE4funcEv // MS: Base class already instantiated with different dll attribute. struct __declspec(dllimport) DerivedFromTemplateB : public ClassTemplate {}; struct __declspec(dllexport) DerivedFromTemplateB2 : public ClassTemplate {}; USEMEMFUNC(DerivedFromTemplateB2, func) // M32-DAG: {{declare|define available_externally}} dllimport x86_thiscallcc void @""\\01?func@?$ClassTemplate@_N@@QAEXXZ"" // G32-DAG: define linkonce_odr x86_thiscallcc void @_ZN13ClassTemplateIbE4funcEv // Base class already specialized without dll attribute. struct __declspec(dllexport) DerivedFromExplicitlySpecializedTemplate : public ExplicitlySpecializedTemplate {}; USEMEMFUNC(DerivedFromExplicitlySpecializedTemplate, func) // M32-DAG: define x86_thiscallcc void @""\\01?func@?$ExplicitlySpecializedTemplate@H@@QAEXXZ"" // G32-DAG: define x86_thiscallcc void @_ZN29ExplicitlySpecializedTemplateIiE4funcEv // Base class alredy specialized with export attribute. struct __declspec(dllexport) DerivedFromExplicitlyExportSpecializedTemplate : public ExplicitlyExportSpecializedTemplate {}; USEMEMFUNC(DerivedFromExplicitlyExportSpecializedTemplate, func) // M32-DAG: define dllexport x86_thiscallcc void @""\\01?func@?$ExplicitlyExportSpecializedTemplate@H@@QAEXXZ"" // G32-DAG: define dllexport x86_thiscallcc void @_ZN35ExplicitlyExportSpecializedTemplateIiE4funcEv // Base class already specialized with import attribute. struct __declspec(dllexport) DerivedFromExplicitlyImportSpecializedTemplate : public ExplicitlyImportSpecializedTemplate {}; USEMEMFUNC(DerivedFromExplicitlyImportSpecializedTemplate, func) // M32-DAG: declare dllimport x86_thiscallcc void @""\\01?func@?$ExplicitlyImportSpecializedTemplate@H@@QAEXXZ"" // G32-DAG: declare dllimport x86_thiscallcc void @_ZN35ExplicitlyImportSpecializedTemplateIiE4funcEv // Base class already instantiated without dll attribute. struct __declspec(dllexport) DerivedFromExplicitlyInstantiatedTemplate : public ExplicitlyInstantiatedTemplate {}; USEMEMFUNC(DerivedFromExplicitlyInstantiatedTemplate, func) // M32-DAG: define weak_odr x86_thiscallcc void @""\\01?func@?$ExplicitlyInstantiatedTemplate@H@@QAEXXZ"" // G32-DAG: define weak_odr x86_thiscallcc void @_ZN30ExplicitlyInstantiatedTemplateIiE4funcEv // Base class already instantiated with export attribute. struct __declspec(dllexport) DerivedFromExplicitlyExportInstantiatedTemplate : public ExplicitlyExportInstantiatedTemplate {}; USEMEMFUNC(DerivedFromExplicitlyExportInstantiatedTemplate, func) // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?func@?$ExplicitlyExportInstantiatedTemplate@H@@QAEXXZ"" // G32-DAG: define weak_odr dllexport x86_thiscallcc void @_ZN36ExplicitlyExportInstantiatedTemplateIiE4funcEv // Base class already instantiated with import attribute. struct __declspec(dllexport) DerivedFromExplicitlyImportInstantiatedTemplate : public ExplicitlyImportInstantiatedTemplate {}; USEMEMFUNC(DerivedFromExplicitlyImportInstantiatedTemplate, func) // M32-DAG: declare dllimport x86_thiscallcc void @""\\01?func@?$ExplicitlyImportInstantiatedTemplate@H@@QAEXXZ"" // G32-DAG: declare dllimport x86_thiscallcc void @_ZN36ExplicitlyImportInstantiatedTemplateIiE4funcEv // MS: A dll attribute propagates through multiple levels of instantiation. template struct TopClass { void func() {} }; template struct MiddleClass : public TopClass { }; struct __declspec(dllexport) BottomClass : public MiddleClass { }; USEMEMFUNC(BottomClass, func) // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?func@?$TopClass@H@@QAEXXZ"" // G32-DAG: define linkonce_odr x86_thiscallcc void @_ZN8TopClassIiE4funcEv template struct ExplicitInstantiationDeclTemplateBase { void func() {} }; extern template struct ExplicitInstantiationDeclTemplateBase; struct __declspec(dllexport) DerivedFromExplicitInstantiationDeclTemplateBase : public ExplicitInstantiationDeclTemplateBase {}; template struct ExplicitInstantiationDeclTemplateBase; // M32-DAG: define weak_odr dllexport x86_thiscallcc void @""\\01?func@?$ExplicitInstantiationDeclTemplateBase@H@@QAEXXZ"" // G32-DAG: define weak_odr x86_thiscallcc void @_ZN37ExplicitInstantiationDeclTemplateBaseIiE4funcEv // PR26076 struct LayerSelectionBound; template struct Selection {}; typedef Selection LayerSelection; struct LayerImpl; struct __declspec(dllexport) LayerTreeImpl { struct __declspec(dllexport) ElementLayers { LayerImpl *main = nullptr; }; LayerSelection foo; }; // M32-DAG: define weak_odr dllexport x86_thiscallcc %""struct.LayerTreeImpl::ElementLayers""* @""\\01??0ElementLayers@LayerTreeImpl@@QAE@XZ"" // M64-DAG: define weak_odr dllexport %""struct.LayerTreeImpl::ElementLayers""* @""\\01??0ElementLayers@LayerTreeImpl@@QEAA@XZ"" class __declspec(dllexport) ACE_Shared_Object { public: virtual ~ACE_Shared_Object(); }; class __declspec(dllexport) ACE_Service_Object : public ACE_Shared_Object {}; // Implicit move constructor declaration. // MSVC2015-DAG: define weak_odr dllexport {{.+}}ACE_Service_Object@@Q{{.+}}@$$Q // The declarations should not be exported. // MSVC2013-NOT: define weak_odr dllexport {{.+}}ACE_Service_Object@@Q{{.+}}@$$Q ",16383,True,3016.66011718479,median "#include #include #include #include #define SensorPin A2 //pH meter Analog output to Arduino Analog Input 0 #define Offset 0.00 //deviation compensate unsigned long int avgValue; //Store the average value of the sensor feedback #define TRIGGER_PIN 23 // Arduino pin tied to trigger pin on ping sensor. #define ECHO_PIN 22 // Arduino pin tied to echo pin on ping sensor. #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. unsigned int pingSpeed = 50; // How frequently are we going to send out a ping (in milliseconds). 50ms would be 20 times a second. unsigned long pingTimer; // Holds the next ping time. // Data wire is plugged into pin 2 on the Arduino #define ONE_WIRE_BUS 6 SoftwareSerial mySerial(7, 8); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); // Pass our oneWire reference to Dallas Temperature. DallasTemperature sensors(&oneWire); #include LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //const int pingPin =22; int sensorPin = A0; int blueled = 13; int redled = 24; int greenled = 25; int tempblueled = 32; int tempredled = 33; int tempgreenled = 34; int levblueled = 35; int levredled = 36; int levgreenled = 37; int turbblueled = 38; int turbredled = 39; int turbgreenled = 40; int buzzer = 31; float phValue; float temperatureC; long duration, cm; void setup(void) { // start serial port Serial.begin(9600); pingTimer = millis(); // Start now. // Start up the library sensors.begin(); // IC Default 9 bit. If you have troubles consider upping it 12. Ups the delay giving the IC more time to process the temperature measurement lcd.begin(16, 2); //initilise lcd with num of coloums 16 ,by row 2. lcd.clear(); //clears lcd just incase there is anytin been displayed pinMode(blueled, OUTPUT); pinMode(redled, OUTPUT); pinMode(greenled, OUTPUT); pinMode(tempblueled, OUTPUT); pinMode(tempredled, OUTPUT); pinMode(tempgreenled, OUTPUT); pinMode(levblueled, OUTPUT); pinMode(levredled, OUTPUT); pinMode(levgreenled, OUTPUT); pinMode(turbblueled, OUTPUT); pinMode(turbredled, OUTPUT); pinMode(turbgreenled, OUTPUT); pinMode(buzzer, OUTPUT); digitalWrite(buzzer, LOW); //initialization(); } void loop() { sensors.requestTemperatures(); // Send the command to get temperature Serial.println(sensors.getTempCByIndex(0)); int reading = analogRead(sensorPin); // converting that reading to voltage, float voltage = reading * 5.0; voltage /= 1024.0; // now print out the temperature float temperatureC = (voltage - 0.5) * 100 ; PH(); digitalWrite(blueled, LOW); digitalWrite(redled, LOW); digitalWrite(greenled, LOW); temperature (); digitalWrite(tempblueled, LOW); digitalWrite(tempredled, LOW); digitalWrite(tempgreenled, LOW); Water_level(); digitalWrite(levblueled, LOW); digitalWrite(levredled, LOW); digitalWrite(levgreenled, LOW); turbidity(); digitalWrite(turbblueled, LOW); digitalWrite(turbredled, LOW); digitalWrite(turbgreenled, LOW); send_sms(); delay(4000); send_sms1(); digitalWrite(greenled, LOW); digitalWrite(tempgreenled, LOW); digitalWrite(levgreenled, LOW); digitalWrite(turbgreenled, LOW); delay(8000); } //////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////////// void PH(){ Serial.println("" ""); lcd.clear( ); digitalWrite(blueled, LOW); digitalWrite(greenled, LOW); digitalWrite(redled, LOW); digitalWrite(buzzer, LOW); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""TAKING READINGS""); lcd.setCursor(1,1); lcd.print(""FROM PH SENSOR""); Serial.println(""Taking Readings from PH Sensor""); PHblink(); int buf[10]; //buffer for read analog for(int i=0;i<10;i++) //Get 10 sample value from the sensor for smooth the value { buf[i]=analogRead(SensorPin); delay(10); } for(int i=0;i<9;i++) //sort the analog from small to large { for(int j=i+1;j<10;j++) { if(buf[i]>buf[j]) { int temp=buf[i]; buf[i]=buf[j]; buf[j]=temp; } } } avgValue=0; for(int i=2;i<8;i++) //take the average value of 6 center sample avgValue+=buf[i]; float phValue=(float)avgValue*3.8/1030/6; //convert the analog into millivolt phValue=3.3*phValue+Offset; //convert the millivolt into pH value Serial.print(""pH:""); Serial.print(phValue,2); Serial.println("" ""); if(phValue >= 7.30){ lcd.clear(); digitalWrite(blueled, LOW); digitalWrite(greenled, LOW); digitalWrite(redled, HIGH); digitalWrite(buzzer, HIGH); lcd.setCursor(1,0);//set cursor (colum by row) indexing from 0 lcd.print(""PH VALUE:""); lcd.setCursor(10,0); lcd.print(phValue); lcd.setCursor(0,1); Serial.print(""PH VALUE: ""); Serial.println(phValue); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""ALKALINITY HIGH""); Serial.println(""Water Alkalinity high""); delay(3000); } if(phValue >= 6.90 && phValue <= 7.19){ digitalWrite(blueled, HIGH); digitalWrite(greenled,LOW); digitalWrite(redled, LOW); digitalWrite(buzzer, LOW); lcd.clear(); lcd.setCursor(1,0);//set cursor (colum by row) indexing from 0 lcd.print(""PH VALUE:""); lcd.setCursor(10,0); lcd.print(phValue); lcd.setCursor(0,1); Serial.print(""PH VALUE: ""); Serial.println(phValue); lcd.setCursor(1,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER IS SAFE""); Serial.println(""Water Is neutral (safe)""); } if(phValue < 6.89){ lcd.clear(); digitalWrite(blueled, LOW); digitalWrite(greenled, LOW); digitalWrite(redled, HIGH); digitalWrite(buzzer, HIGH); lcd.setCursor(1,0);//set cursor (colum by row) indexing from 0 lcd.print(""PH VALUE:""); lcd.setCursor(10,0); lcd.print(phValue); lcd.setCursor(0,1); Serial.print(""PH VALUE: ""); Serial.println(phValue); lcd.setCursor(2,1);//set cursor (colum by row) indexing from 0 lcd.print(""ACIDITY HIGH""); Serial.println(""Water Acidity High""); delay(3000); } delay(8000); } void temperature (){ Serial.println("" ""); lcd.clear( ); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""TAKING READINGS""); lcd.setCursor(0,1); lcd.print(""FROM TEMP SENSOR""); Serial.println(""Taking Readings from Temperature Sensor""); TEMPblink(); temp_check_surr(); delay(4000); temp_check_water(); } void temp_check_surr(){ digitalWrite(tempblueled, LOW); digitalWrite(tempgreenled, LOW); digitalWrite(tempredled, LOW); digitalWrite(buzzer, LOW); int reading = analogRead(sensorPin); // converting that reading to voltage, float voltage = reading * 5.0; voltage /= 1024.0; // now print out the temperature float temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree wit 500 mV offset //to degrees ((voltage - 500mV) times 100) lcd.clear(); Serial.print(""Surrounding Temperature: ""); Serial.println(temperatureC); if(temperatureC > 50){ digitalWrite(tempblueled, LOW); digitalWrite(tempgreenled, LOW); digitalWrite(tempredled, HIGH); digitalWrite(buzzer, HIGH); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""SUR TEMP:""); lcd.setCursor(9,0); lcd.print(temperatureC); lcd.setCursor(14,0); lcd.print(""*C""); lcd.setCursor(0,1); Serial.print(""Surrounding Temperature: ""); Serial.print(temperatureC); Serial.println("" degree C""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""SURR TEMP HIGH""); Serial.println(""Surrounding Temperature high""); delay(3000); } if(temperatureC >= 10 && temperatureC <= 50){ digitalWrite(tempblueled, HIGH); digitalWrite(tempgreenled,LOW); digitalWrite(tempredled, LOW); digitalWrite(buzzer, LOW); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""SUR TEMP:""); lcd.setCursor(9,0); lcd.print(temperatureC); lcd.setCursor(14,0); lcd.print(""*C""); lcd.setCursor(0,1); Serial.print(""Surrounding Temperature: ""); Serial.print(temperatureC); Serial.println("" degree C""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""SURR TEMP NORMAL""); Serial.println(""Surrounding Temperature normal""); } if(temperatureC < 10){ digitalWrite(tempblueled, LOW); digitalWrite(tempgreenled, LOW); digitalWrite(tempredled, HIGH); digitalWrite(buzzer, HIGH); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""SUR TEMP:""); lcd.setCursor(9,0); lcd.print(temperatureC); lcd.setCursor(14,0); lcd.print(""*C""); lcd.setCursor(0,1); Serial.print(""Surrounding Temperature: ""); Serial.print(temperatureC); Serial.println("" degree C""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""SURR TEMP LOW""); Serial.println(""Surrounding Temperature low""); delay(3000); } delay(8000); } void temp_check_water(){ lcd.clear(); digitalWrite(tempblueled, LOW); digitalWrite(tempgreenled, LOW); digitalWrite(tempredled, LOW); digitalWrite(buzzer, LOW); sensors.requestTemperatures(); // Send the command to get temperature Serial.print(""Water Temperature: ""); Serial.println(sensors.getTempCByIndex(0)); if(sensors.getTempCByIndex(0) > 40){ digitalWrite(tempblueled, LOW); digitalWrite(tempgreenled, LOW); digitalWrite(tempredled, HIGH); digitalWrite(buzzer, HIGH); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""WAT TEMP:""); lcd.setCursor(9,0); lcd.print(sensors.getTempCByIndex(0)); lcd.setCursor(14,0); lcd.print(""*C""); lcd.setCursor(0,1); Serial.print(""Water Temperature: ""); Serial.print(sensors.getTempCByIndex(0)); Serial.println("" degree C""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER TEMP HIGH""); Serial.println(""Water Temperature high""); delay(3000); } if(sensors.getTempCByIndex(0) >= 15 && sensors.getTempCByIndex(0) <= 40){ digitalWrite(tempblueled, HIGH); digitalWrite(tempgreenled,LOW); digitalWrite(tempredled, LOW); digitalWrite(buzzer, LOW); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""WAT TEMP:""); lcd.setCursor(9,0); lcd.print(sensors.getTempCByIndex(0)); lcd.setCursor(14,0); lcd.print(""*C""); lcd.setCursor(0,1); Serial.print(""Water Temperature: ""); Serial.print(sensors.getTempCByIndex(0)); Serial.println("" degree C""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER TEMP NORMAL""); Serial.println(""Water Temperature normal""); } if(sensors.getTempCByIndex(0) < 15){ digitalWrite(tempblueled, LOW); digitalWrite(tempgreenled, LOW); digitalWrite(tempredled, HIGH); digitalWrite(buzzer, HIGH); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""WAT TEMP:""); lcd.setCursor(9,0); lcd.print(sensors.getTempCByIndex(0)); lcd.setCursor(14,0); lcd.print(""*C""); lcd.setCursor(0,1); Serial.print(""Water Temperature: ""); Serial.print(sensors.getTempCByIndex(0)); Serial.println("" degree C""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER TEMP LOW""); Serial.println(""Water Temperature low""); delay(3000); } delay(8000); } void Water_level() { Serial.println("" ""); digitalWrite(levblueled, LOW); digitalWrite(levgreenled, LOW); digitalWrite(levredled, LOW); digitalWrite(buzzer, LOW); lcd.clear( ); lcd.setCursor(2,0);//set cursor (colum by row) indexing from 0 lcd.print(""READINGS FROM""); lcd.setCursor(0,1); lcd.print(""WATER LEVEL SENS""); Serial.println(""Taking Readings from Water Level Sensor""); LEVblink(); level_check(); delay(8000); } void level_check(){ digitalWrite(levblueled, LOW); digitalWrite(levgreenled, LOW); digitalWrite(levredled, LOW); digitalWrite(buzzer, LOW); // Notice how there's no delays in this sketch to allow you to do other processing in-line while doing distance pings. if (millis() >= pingTimer) { // pingSpeed milliseconds since last ping, do another ping. pingTimer += pingSpeed; // Set the next ping time. sonar.ping_timer(echoCheck); // Send out the ping, calls ""echoCheck"" function every 24uS where you can check the ping status. //delay(1000); } } void echoCheck() { // Timer2 interrupt calls this function every 24uS where you can check the ping status. // Don't do anything here! if (sonar.check_timer()) { // This is how you check to see if the ping was received. if(sonar.ping_result / US_ROUNDTRIP_CM > 7){ digitalWrite(levblueled, LOW); digitalWrite(levgreenled, LOW); digitalWrite(levredled, HIGH); digitalWrite(buzzer, HIGH); lcd.clear( ); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""WATER LEVEL:""); lcd.setCursor(12,0); lcd.print(sonar.ping_result / US_ROUNDTRIP_CM); lcd.setCursor(14,0); lcd.print(""cm""); lcd.setCursor(0,1); Serial.print(""Water Level: ""); Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); Serial.println(""cm""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER LEVEL LOW""); Serial.println(""Water Level low""); delay(3000); } if(sonar.ping_result / US_ROUNDTRIP_CM >= 5 && sonar.ping_result / US_ROUNDTRIP_CM <= 7){ digitalWrite(levblueled, HIGH); digitalWrite(levgreenled, LOW); digitalWrite(levredled, LOW); digitalWrite(buzzer, LOW); lcd.clear( ); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""WATER LEVEL:""); lcd.setCursor(12,0); lcd.print(sonar.ping_result / US_ROUNDTRIP_CM); lcd.setCursor(14,0); lcd.print(""cm""); lcd.setCursor(0,1); Serial.print(""Water Level: ""); Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); Serial.println(""cm""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER LEVEL NORMAL""); Serial.println(""Water Level normal""); } if(sonar.ping_result / US_ROUNDTRIP_CM < 5){ digitalWrite(levblueled, LOW); digitalWrite(levgreenled, LOW); digitalWrite(levredled, HIGH); digitalWrite(buzzer, HIGH); lcd.clear( ); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""WATER LEVEL:""); lcd.setCursor(12,0); lcd.print(sonar.ping_result / US_ROUNDTRIP_CM); lcd.setCursor(14,0); lcd.print(""cm""); lcd.setCursor(0,1); Serial.print(""Water Level: ""); Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); Serial.println(""cm""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER LEVEL HIGH""); Serial.println(""Water Level high""); delay(2000); } } } /*long microsecondsToCentimeters(long microseconds) { return microseconds / 29 / 2; } */ void turbidity() { Serial.println("" ""); digitalWrite(turbblueled, LOW); digitalWrite(turbgreenled, LOW); digitalWrite(turbredled, LOW); digitalWrite(buzzer, LOW); lcd.clear( ); lcd.setCursor(1,0);//set cursor (colum by row) indexing from 0 lcd.print(""READINGS FROM""); lcd.setCursor(0,1); lcd.print(""TURBIDITY SENSOR""); Serial.println(""Taking Readings from turbidity Sensor""); TURBblink(); int turbidityValue = analogRead(A1); float turbidityV = turbidityValue/100; Serial.print(""Turbidity level: ""); Serial.println(turbidityV); if( turbidityV > 9){ digitalWrite(turbblueled, LOW); digitalWrite(turbgreenled, LOW); digitalWrite(turbredled, HIGH); digitalWrite(buzzer, HIGH); lcd.clear( ); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""TURBI LEV:""); lcd.setCursor(11,0); lcd.print(turbidityV); lcd.setCursor(14,0); lcd.print(""NTU""); lcd.setCursor(0,1); Serial.print(""Turbidity Level: ""); Serial.print(turbidityV); Serial.println(""NTU""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER VERY CLEAN""); Serial.println(""Water Very Clean ""); delay(3000); } if( turbidityV >= 6 && turbidityValue/100 <= 9 ){ digitalWrite(turbblueled, HIGH); digitalWrite(turbgreenled, LOW); digitalWrite(turbredled, LOW); digitalWrite(buzzer, LOW); lcd.clear( ); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""TURBI LEV:""); lcd.setCursor(10,0); lcd.print(turbidityV); lcd.setCursor(13,0); lcd.print(""NTU""); lcd.setCursor(0,1); Serial.print(""Turbidity Level: ""); Serial.print(turbidityV); Serial.println(""NTU""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER NORM CLEAN""); Serial.println(""Water Clean ""); } if( turbidityV < 6){ digitalWrite(turbblueled, LOW); digitalWrite(turbgreenled, LOW); digitalWrite(turbredled, HIGH); digitalWrite(buzzer, HIGH); lcd.clear( ); lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""TURBI LEV:""); lcd.setCursor(11,0); lcd.print(turbidityV); lcd.setCursor(14,0); lcd.print(""NTU""); lcd.setCursor(0,1); Serial.print(""Turbidity Level: ""); Serial.print(turbidityV); Serial.println(""NTU""); lcd.setCursor(0,1);//set cursor (colum by row) indexing from 0 lcd.print(""WATER VERY DIRTY""); Serial.println(""Water Very Dirty ""); delay(3000); } delay (8000); } void initialization(){ lcd.setCursor(0,0);//set cursor (colum by row) indexing from 0 lcd.print(""INITIALIZING ALL""); lcd.setCursor(0,1); lcd.print(""PARAMETERS""); delay(3000); lcd.setCursor(0,1); lcd.print(""PARAMETERS.""); delay(3000); lcd.setCursor(0,1); lcd.print(""PARAMETERS..""); delay(3000); lcd.setCursor(0,1); lcd.print(""PARAMETERS...""); delay(3000); lcd.setCursor(0,1); lcd.print(""PARAMETERS....""); delay(3000); lcd.setCursor(0,1); lcd.print(""PARAMETERS.....""); delay(3000); lcd.setCursor(0,1); lcd.print(""PARAMETERS......""); Serial.println(""Initializing All Parameters........""); delay(8000); Serial.println(""Initializing Done.""); lcd.clear(); lcd.setCursor(1,0); lcd.print(""INITIALIZATION""); lcd.setCursor(6,1); lcd.print(""DONE ""); delay(2000); } //////////////////////////////////////////////////////// SMS FUNCTION ///////////////////////////////////////////////////////////////////// void send_sms(){ lcd.clear(); lcd.setCursor(2,0);//set cursor (colum by row) indexing from 0 lcd.print(""ATTENTION!!! ""); lcd.setCursor(2,1); lcd.print(""SENDING SMS ""); String temp; String lev; String phm; String turb; int turbidityValue = analogRead(A1); float turbidityV = turbidityValue/100; int buf[10]; //buffer for read analog for(int i=0;i<10;i++) //Get 10 sample value from the sensor for smooth the value { buf[i]=analogRead(SensorPin); delay(10); } for(int i=0;i<9;i++) //sort the analog from small to large { for(int j=i+1;j<10;j++) { if(buf[i]>buf[j]) { int temp=buf[i]; buf[i]=buf[j]; buf[j]=temp; } } } avgValue=0; for(int i=2;i<8;i++) //take the average value of 6 center sample avgValue+=buf[i]; float phValue=(float)avgValue*3.8/1030/6; //convert the analog into millivolt phValue=3.3*phValue+Offset; if(sensors.getTempCByIndex(0) > 40){ temp = String(""HIGH""); } if(sensors.getTempCByIndex(0) >= 10 && sensors.getTempCByIndex(0) <= 40){ temp = String(""NORMAL""); } if(sensors.getTempCByIndex(0) < 10){ temp = String(""LOW""); } if(sonar.ping_result / US_ROUNDTRIP_CM > 8){ lev = String(""LOW""); } if(sonar.ping_result / US_ROUNDTRIP_CM >= 5 && sonar.ping_result / US_ROUNDTRIP_CM <= 8){ lev = String(""NORMAL""); } if(sonar.ping_result / US_ROUNDTRIP_CM < 5){ lev = String(""HIGH""); } if(phValue >= 7.30){ phm = String(""ALKALINE""); } if(phValue >= 6.90 && phValue <= 7.19){ phm = String(""NORMAL""); } if(phValue < 6.89){ phm = String(""ACIDIC""); } if(turbidityV >= 6 && turbidityValue/100 <= 9){ turb = String(""CLEAN""); } if(turbidityV < 6){ turb = String(""DIRTY""); } mySerial.begin(19200); //Default serial port setting for the GPRS modem is 19200bps 8-N-1 mySerial.print(""\\r""); digitalWrite(buzzer, LOW); digitalWrite(blueled, LOW); digitalWrite(greenled, LOW); digitalWrite(redled, LOW); delay(1000); //wait for a second while the modem sends an ""OK"" mySerial.print(""AT+CMGF=1\\r""); //Because we want to send the SMS in text mode delay(1000); mySerial.print(""AT+CMGS=\\""+233540518223\\""\\r""); //Start accepting the text for the message delay(1000); mySerial.print(temp); mySerial.print("" \\r""); mySerial.print(""WATER TEMPERATURE= \\r""); //The text for the message mySerial.print(sensors.getTempCByIndex(0)); mySerial.print(""*C\\r""); mySerial.println(""\\r""); mySerial.print(lev); mySerial.print("" \\r""); mySerial.print(""WATER LEVEL= \\r""); //The text for the message mySerial.print(sonar.ping_result / US_ROUNDTRIP_CM); mySerial.print(""cm\\r""); mySerial.println(""\\r""); mySerial.print(phm); mySerial.print("" \\r""); mySerial.print(""WATER PH VALUE= \\r""); //The text for the message mySerial.print(phValue); mySerial.println(""\\r""); mySerial.print(turb); mySerial.print("" \\r""); mySerial.print(""WATER TURBIDITY= \\r""); //The text for the message mySerial.print(turbidityV); mySerial.print(""NBT\\r""); digitalWrite(greenled, HIGH); digitalWrite(tempgreenled, HIGH); digitalWrite(levgreenled, HIGH); digitalWrite(turbgreenled, HIGH); delay(3000); /*lcd.clear(); lcd.setCursor(5,0);//set cursor (colum by row) indexing from 0 lcd.print(""SMS SENT ""); lcd.setCursor(2,1); lcd.print(""SUCCESSFULLY "");*/ mySerial.write(0x1A); //Equivalent to sending Ctrl+Z } void send_sms1(){ lcd.clear(); lcd.setCursor(2,0);//set cursor (colum by row) indexing from 0 lcd.print(""ATTENTION!!! ""); lcd.setCursor(2,1); lcd.print(""SENDING SMS ""); String temp; String lev; String phm; String turb; int turbidityValue = analogRead(A1); float turbidityV = turbidityValue/100; int buf[10]; //buffer for read analog for(int i=0;i<10;i++) //Get 10 sample value from the sensor for smooth the value { buf[i]=analogRead(SensorPin); delay(10); } for(int i=0;i<9;i++) //sort the analog from small to large { for(int j=i+1;j<10;j++) { if(buf[i]>buf[j]) { int temp=buf[i]; buf[i]=buf[j]; buf[j]=temp; } } } avgValue=0; for(int i=2;i<8;i++) //take the average value of 6 center sample avgValue+=buf[i]; float phValue=(float)avgValue*3.8/1030/6; //convert the analog into millivolt phValue=3.3*phValue+Offset; if(sensors.getTempCByIndex(0) > 40){ temp = String(""HIGH""); } if(sensors.getTempCByIndex(0) >= 10 && sensors.getTempCByIndex(0) <= 40){ temp = String(""NORMAL""); } if(sensors.getTempCByIndex(0) < 10){ temp = String(""LOW""); } if(sonar.ping_result / US_ROUNDTRIP_CM > 8){ lev = String(""LOW""); } if(sonar.ping_result / US_ROUNDTRIP_CM >= 5 && sonar.ping_result / US_ROUNDTRIP_CM <= 8){ lev = String(""NORMAL""); } if(sonar.ping_result / US_ROUNDTRIP_CM < 5){ lev = String(""HIGH""); } if(phValue >= 7.30){ phm = String(""ALKALINE""); } if(phValue >= 6.90 && phValue <= 7.19){ phm = String(""NORMAL""); } if(phValue < 6.89){ phm = String(""ACIDIC""); } if(turbidityV >= 6 && turbidityValue/100 <= 9){ turb = String(""CLEAN""); } if(turbidityV < 6){ turb = String(""DIRTY""); } mySerial.begin(19200); //Default serial port setting for the GPRS modem is 19200bps 8-N-1 mySerial.print(""\\r""); digitalWrite(buzzer, LOW); digitalWrite(blueled, LOW); digitalWrite(greenled, LOW); digitalWrite(redled, LOW); delay(1000); //wait for a second while the modem sends an ""OK"" mySerial.print(""AT+CMGF=1\\r""); //Because we want to send the SMS in text mode delay(1000); mySerial.print(""AT+CMGS=\\""+233265188849\\""\\r""); //Start accepting the text for the message delay(1000); mySerial.print(temp); mySerial.print("" \\r""); mySerial.print(""WATER TEMPERATURE= \\r""); //The text for the message mySerial.print(sensors.getTempCByIndex(0)); mySerial.print(""*C\\r""); mySerial.println(""\\r""); mySerial.print(lev); mySerial.print("" \\r""); mySerial.print(""WATER LEVEL= \\r""); //The text for the message mySerial.print(sonar.ping_result / US_ROUNDTRIP_CM); mySerial.print(""cm\\r""); mySerial.println(""\\r""); mySerial.print(phm); mySerial.print("" \\r""); mySerial.print(""WATER PH VALUE= \\r""); //The text for the message mySerial.print(phValue); mySerial.println(""\\r""); mySerial.print(turb); mySerial.print("" \\r""); mySerial.print(""WATER TURBIDITY= \\r""); //The text for the message mySerial.print(turbidityV); mySerial.print(""NBT\\r""); digitalWrite(greenled, HIGH); digitalWrite(tempgreenled, HIGH); digitalWrite(levgreenled, HIGH); digitalWrite(turbgreenled, HIGH); delay(3000); lcd.clear(); lcd.setCursor(5,0);//set cursor (colum by row) indexing from 0 lcd.print(""SMS SENT ""); lcd.setCursor(2,1); lcd.print(""SUCCESSFULLY ""); mySerial.write(0x1A); //Equivalent to sending Ctrl+Z } void PHblink() { digitalWrite(blueled, HIGH); delay(1000); digitalWrite(blueled, LOW); delay(1000); digitalWrite(blueled, HIGH); delay(1000); digitalWrite(blueled, LOW); delay(1000); digitalWrite(blueled, HIGH); delay(1000); digitalWrite(blueled, LOW); delay(1000); digitalWrite(blueled, HIGH); delay(1000); digitalWrite(blueled, LOW); delay(1000); } void TEMPblink() { digitalWrite(tempblueled, HIGH); delay(1000); digitalWrite(tempblueled, LOW); delay(1000); digitalWrite(tempblueled, HIGH); delay(1000); digitalWrite(tempblueled, LOW); delay(1000); digitalWrite(tempblueled, HIGH); delay(1000); digitalWrite(tempblueled, LOW); delay(1000); digitalWrite(tempblueled, HIGH); delay(1000); digitalWrite(tempblueled, LOW); delay(1000); } void LEVblink() { digitalWrite(levblueled, HIGH); delay(1000); digitalWrite(levblueled, LOW); delay(1000); digitalWrite(levblueled, HIGH); delay(1000); digitalWrite(levblueled, LOW); delay(1000); digitalWrite(levblueled, HIGH); delay(1000); digitalWrite(levblueled, LOW); delay(1000); digitalWrite(levblueled, HIGH); delay(1000); digitalWrite(levblueled, LOW); delay(1000); } void TURBblink() { digitalWrite(turbblueled, HIGH); delay(1000); digitalWrite(turbblueled, LOW); delay(1000); digitalWrite(turbblueled, HIGH); delay(1000); digitalWrite(turbblueled, LOW); delay(1000); digitalWrite(turbblueled, HIGH); delay(1000); digitalWrite(turbblueled, LOW); delay(1000); digitalWrite(turbblueled, HIGH); delay(1000); digitalWrite(turbblueled, LOW); delay(1000); } ",8322,False,1835.673132835581,median "CLASS zcl_abapgit_services_repo DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. CLASS-METHODS new_online IMPORTING !iv_url TYPE string RETURNING VALUE(ro_repo) TYPE REF TO zcl_abapgit_repo_online RAISING zcx_abapgit_exception. CLASS-METHODS refresh IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception . CLASS-METHODS remove IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception. CLASS-METHODS purge IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception. CLASS-METHODS new_offline RAISING zcx_abapgit_exception. CLASS-METHODS remote_attach IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception. CLASS-METHODS remote_detach IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception. CLASS-METHODS remote_change IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception. CLASS-METHODS refresh_local_checksums IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception. CLASS-METHODS toggle_favorite IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RAISING zcx_abapgit_exception . CLASS-METHODS open_se80 IMPORTING !iv_package TYPE devclass RAISING zcx_abapgit_exception . CLASS-METHODS transport_to_branch IMPORTING !iv_repository_key TYPE zif_abapgit_persistence=>ty_value RAISING zcx_abapgit_exception. CLASS-METHODS gui_deserialize IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RAISING zcx_abapgit_exception . PROTECTED SECTION. PRIVATE SECTION. CLASS-METHODS popup_overwrite CHANGING !ct_overwrite TYPE zif_abapgit_definitions=>ty_overwrite_tt RAISING zcx_abapgit_exception. CLASS-METHODS popup_package_overwrite CHANGING !ct_overwrite TYPE zif_abapgit_definitions=>ty_overwrite_tt RAISING zcx_abapgit_exception. ENDCLASS. CLASS ZCL_ABAPGIT_SERVICES_REPO IMPLEMENTATION. METHOD gui_deserialize. DATA: ls_checks TYPE zif_abapgit_definitions=>ty_deserialize_checks, lt_requirements TYPE zif_abapgit_dot_abapgit=>ty_requirement_tt. * find troublesome objects ls_checks = io_repo->deserialize_checks( ). * and let the user decide what to do TRY. popup_overwrite( CHANGING ct_overwrite = ls_checks-overwrite ). popup_package_overwrite( CHANGING ct_overwrite = ls_checks-warning_package ). IF ls_checks-requirements-met = 'N'. lt_requirements = io_repo->get_dot_abapgit( )->get_data( )-requirements. zcl_abapgit_requirement_helper=>requirements_popup( lt_requirements ). ls_checks-requirements-decision = 'Y'. ENDIF. IF ls_checks-transport-required = abap_true. ls_checks-transport-transport = zcl_abapgit_ui_factory=>get_popups( )->popup_transport_request( is_transport_type = ls_checks-transport-type ). ENDIF. CATCH zcx_abapgit_cancel. RETURN. ENDTRY. * and pass decisions to deserialize io_repo->deserialize( is_checks = ls_checks ii_log = io_repo->create_new_log( 'Pull Log' ) ). ENDMETHOD. METHOD new_offline. DATA: lo_repo TYPE REF TO zcl_abapgit_repo, ls_popup TYPE zif_abapgit_popups=>ty_popup. ls_popup = zcl_abapgit_ui_factory=>get_popups( )->repo_new_offline( ). IF ls_popup-cancel = abap_true. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->new_offline( iv_url = ls_popup-url iv_package = ls_popup-package iv_folder_logic = ls_popup-folder_logic ). lo_repo->rebuild_local_checksums( ). zcl_abapgit_persistence_user=>get_instance( )->set_repo_show( lo_repo->get_key( ) ). "" Set default repo for user toggle_favorite( lo_repo->get_key( ) ). COMMIT WORK AND WAIT. ENDMETHOD. METHOD new_online. DATA: ls_popup TYPE zif_abapgit_popups=>ty_popup. ls_popup = zcl_abapgit_ui_factory=>get_popups( )->repo_popup( iv_url ). IF ls_popup-cancel = abap_true. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. ro_repo = zcl_abapgit_repo_srv=>get_instance( )->new_online( iv_url = ls_popup-url iv_branch_name = ls_popup-branch_name iv_package = ls_popup-package iv_display_name = ls_popup-display_name iv_folder_logic = ls_popup-folder_logic iv_ign_subpkg = ls_popup-ign_subpkg ). toggle_favorite( ro_repo->get_key( ) ). * Set default repo for user zcl_abapgit_persistence_user=>get_instance( )->set_repo_show( ro_repo->get_key( ) ). COMMIT WORK. ENDMETHOD. METHOD open_se80. CALL FUNCTION 'RS_TOOL_ACCESS' EXPORTING operation = 'SHOW' in_new_window = abap_true object_name = iv_package object_type = 'DEVC' with_objectlist = abap_true. ENDMETHOD. METHOD popup_overwrite. DATA: lt_columns TYPE string_table, lt_selected LIKE ct_overwrite, lv_column LIKE LINE OF lt_columns, li_popups TYPE REF TO zif_abapgit_popups. FIELD-SYMBOLS: LIKE LINE OF ct_overwrite. IF lines( ct_overwrite ) = 0. RETURN. ENDIF. lv_column = 'OBJ_TYPE'. INSERT lv_column INTO TABLE lt_columns. lv_column = 'OBJ_NAME'. INSERT lv_column INTO TABLE lt_columns. li_popups = zcl_abapgit_ui_factory=>get_popups( ). li_popups->popup_to_select_from_list( EXPORTING it_list = ct_overwrite iv_header_text = |The following objects have been modified locally.| && | Select the objects which should be overwritten.| iv_select_column_text = 'Overwrite?' it_columns_to_display = lt_columns IMPORTING et_list = lt_selected ). LOOP AT ct_overwrite ASSIGNING . READ TABLE lt_selected WITH TABLE KEY object_type_and_name COMPONENTS obj_type = -obj_type obj_name = -obj_name TRANSPORTING NO FIELDS. IF sy-subrc = 0. -decision = 'Y'. ELSE. -decision = 'N'. ENDIF. ENDLOOP. ENDMETHOD. METHOD popup_package_overwrite. DATA: lt_colums_to_display TYPE string_table, lv_column LIKE LINE OF lt_colums_to_display, lt_selected LIKE ct_overwrite, li_popups TYPE REF TO zif_abapgit_popups. FIELD-SYMBOLS: LIKE LINE OF ct_overwrite. IF lines( ct_overwrite ) = 0. RETURN. ENDIF. lv_column = 'OBJ_TYPE'. INSERT lv_column INTO TABLE lt_colums_to_display. lv_column = 'OBJ_NAME'. INSERT lv_column INTO TABLE lt_colums_to_display. lv_column = 'DEVCLASS'. INSERT lv_column INTO TABLE lt_colums_to_display. li_popups = zcl_abapgit_ui_factory=>get_popups( ). li_popups->popup_to_select_from_list( EXPORTING it_list = ct_overwrite iv_header_text = |The following objects have been created in other packages.| && | Select the objects which should be overwritten.| iv_select_column_text = |Overwrite?| it_columns_to_display = lt_colums_to_display IMPORTING et_list = lt_selected ). LOOP AT ct_overwrite ASSIGNING . READ TABLE lt_selected WITH TABLE KEY object_type_and_name COMPONENTS obj_type = -obj_type obj_name = -obj_name TRANSPORTING NO FIELDS. IF sy-subrc = 0. -decision = 'Y'. ELSE. -decision = 'N'. ENDIF. ENDLOOP. ENDMETHOD. METHOD purge. DATA: lt_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt, lv_answer TYPE c LENGTH 1, lo_repo TYPE REF TO zcl_abapgit_repo, lv_package TYPE devclass, lv_question TYPE c LENGTH 100, ls_checks TYPE zif_abapgit_definitions=>ty_delete_checks. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lv_package = lo_repo->get_package( ). lt_tadir = zcl_abapgit_factory=>get_tadir( )->read( lv_package ). IF lines( lt_tadir ) > 0. lv_question = |This will DELETE all objects in package { lv_package } ({ lines( lt_tadir ) } objects) from the system|. ""#EC NOTEXT lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Uninstall' iv_text_question = lv_question iv_text_button_1 = 'Delete' iv_icon_button_1 = 'ICON_DELETE' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. ENDIF. ls_checks = lo_repo->delete_checks( ). IF ls_checks-transport-required = abap_true. ls_checks-transport-transport = zcl_abapgit_ui_factory=>get_popups( )->popup_transport_request( ls_checks-transport-type ). ENDIF. zcl_abapgit_repo_srv=>get_instance( )->purge( io_repo = lo_repo is_checks = ls_checks ). COMMIT WORK. ENDMETHOD. METHOD refresh. zcl_abapgit_repo_srv=>get_instance( )->get( iv_key )->refresh( ). ENDMETHOD. METHOD refresh_local_checksums. DATA: lv_answer TYPE c, lv_question TYPE string, lo_repo TYPE REF TO zcl_abapgit_repo. IF zcl_abapgit_auth=>is_allowed( zif_abapgit_auth=>gc_authorization-update_local_checksum ) = abap_false. zcx_abapgit_exception=>raise( 'Not authorized' ). ENDIF. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lv_question = 'This will rebuild and overwrite local repo checksums.'. IF lo_repo->is_offline( ) = abap_false. lv_question = lv_question && ' The logic: if local and remote file differs then:' && ' if remote branch is ahead then assume changes are remote,' && ' else (branches are equal) assume changes are local.' && ' This will lead to incorrect state for files changed on both sides.' && ' Please make sure you don''t have ones like that.'. ENDIF. lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Warning' iv_text_question = lv_question iv_text_button_1 = 'OK' iv_icon_button_1 = 'ICON_DELETE' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. lo_repo->rebuild_local_checksums( ). COMMIT WORK AND WAIT. ENDMETHOD. METHOD remote_attach. DATA: ls_popup TYPE zif_abapgit_popups=>ty_popup, ls_loc TYPE zif_abapgit_persistence=>ty_repo-local_settings, lo_repo TYPE REF TO zcl_abapgit_repo_online. ls_loc = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key )->get_local_settings( ). ls_popup = zcl_abapgit_ui_factory=>get_popups( )->repo_popup( iv_title = 'Attach repo to remote ...' iv_url = '' iv_display_name = ls_loc-display_name iv_package = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key )->get_package( ) iv_freeze_package = abap_true ). IF ls_popup-cancel = abap_true. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. zcl_abapgit_repo_srv=>get_instance( )->get( iv_key )->switch_repo_type( iv_offline = abap_false ). lo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lo_repo->set_url( ls_popup-url ). lo_repo->set_branch_name( ls_popup-branch_name ). ls_loc = lo_repo->get_local_settings( ). "" Just in case ... if switch affects LS state ls_loc-display_name = ls_popup-display_name. lo_repo->set_local_settings( ls_loc ). COMMIT WORK. ENDMETHOD. METHOD remote_change. DATA: ls_popup TYPE zif_abapgit_popups=>ty_popup, ls_loc TYPE zif_abapgit_persistence=>ty_repo-local_settings, lo_repo TYPE REF TO zcl_abapgit_repo_online. lo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). ls_loc = lo_repo->get_local_settings( ). ls_popup = zcl_abapgit_ui_factory=>get_popups( )->repo_popup( iv_title = 'Change repo remote ...' iv_url = lo_repo->get_url( ) iv_package = lo_repo->get_package( ) iv_display_name = ls_loc-display_name iv_freeze_package = abap_true ). IF ls_popup-cancel = abap_true. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. lo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lo_repo->set_url( ls_popup-url ). lo_repo->set_branch_name( ls_popup-branch_name ). ls_loc-display_name = ls_popup-display_name. lo_repo->set_local_settings( ls_loc ). COMMIT WORK. ENDMETHOD. METHOD remote_detach. DATA: lv_answer TYPE c LENGTH 1. lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Make repository OFF-line' iv_text_question = 'This will detach the repo from remote and make it OFF-line' iv_text_button_1 = 'Make OFF-line' iv_icon_button_1 = 'ICON_WF_UNLINK' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. zcl_abapgit_repo_srv=>get_instance( )->get( iv_key )->switch_repo_type( iv_offline = abap_true ). COMMIT WORK. ENDMETHOD. METHOD remove. DATA: lv_answer TYPE c LENGTH 1, lo_repo TYPE REF TO zcl_abapgit_repo, lv_package TYPE devclass, lv_question TYPE c LENGTH 200. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). lv_package = lo_repo->get_package( ). lv_question = |This will remove the repository reference to the package { lv_package }. All objects will safely remain in the system.|. lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Remove' iv_text_question = lv_question iv_text_button_1 = 'Remove' iv_icon_button_1 = 'ICON_WF_UNLINK' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). ""#EC NOTEXT IF lv_answer = '2'. RAISE EXCEPTION TYPE zcx_abapgit_cancel. ENDIF. zcl_abapgit_repo_srv=>get_instance( )->delete( lo_repo ). COMMIT WORK. ENDMETHOD. METHOD toggle_favorite. zcl_abapgit_persistence_user=>get_instance( )->toggle_favorite( iv_key ). ENDMETHOD. METHOD transport_to_branch. DATA: lo_repository TYPE REF TO zcl_abapgit_repo_online, lo_transport_to_branch TYPE REF TO zcl_abapgit_transport_2_branch, lt_transport_headers TYPE trwbo_request_headers, lt_transport_objects TYPE zif_abapgit_definitions=>ty_tadir_tt, ls_transport_to_branch TYPE zif_abapgit_definitions=>ty_transport_to_branch. IF zcl_abapgit_auth=>is_allowed( zif_abapgit_auth=>gc_authorization-transport_to_branch ) = abap_false. zcx_abapgit_exception=>raise( 'Not authorized' ). ENDIF. lo_repository ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_repository_key ). lt_transport_headers = zcl_abapgit_ui_factory=>get_popups( )->popup_to_select_transports( ). lt_transport_objects = zcl_abapgit_transport=>to_tadir( lt_transport_headers ). IF lt_transport_objects IS INITIAL. zcx_abapgit_exception=>raise( 'Canceled or List of objects is empty ' ). ENDIF. ls_transport_to_branch = zcl_abapgit_ui_factory=>get_popups( )->popup_to_create_transp_branch( lt_transport_headers ). CREATE OBJECT lo_transport_to_branch. lo_transport_to_branch->create( io_repository = lo_repository is_transport_to_branch = ls_transport_to_branch it_transport_objects = lt_transport_objects ). ENDMETHOD. ENDCLASS. ",4372,False,1025.5321348145915,median "[[smpp-component]] = SMPP Component *Since Camel 2.2* // HEADER START *Both producer and consumer is supported* // HEADER END This component provides access to an SMSC (Short Message Service Center) over the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP] protocol to send and receive SMS. The http://jsmpp.org[JSMPP] library is used for the protocol implementation. The Camel component currently operates as an http://en.wikipedia.org/wiki/ESME[ESME] (External Short Messaging Entity) and not as an SMSC itself. You are also able to execute ReplaceSm, QuerySm, SubmitMulti, CancelSm and DataSm. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-smpp x.x.x ------------------------------------------------------------ == SMS limitations SMS is neither reliable or secure. Users who require reliable and secure delivery may want to consider using the XMPP or SIP components instead, combined with a smartphone app supporting the chosen protocol. * Reliability: although the SMPP standard offers a range of feedback mechanisms to indicate errors, non-delivery and confirmation of delivery it is not uncommon for mobile networks to hide or simulate these responses. For example, some networks automatically send a delivery confirmation for every message even if the destination number is invalid or not switched on. Some networks silently drop messages if they think they are spam. Spam detection rules in the network may be very crude, sometimes more than 100 messages per day from a single sender may be considered spam. * Security: there is basic encryption for the last hop from the radio tower down to the recipient handset. SMS messages are not encrypted or authenticated in any other part of the network. Some operators allow staff in retail outlets or call centres to browse through the SMS message histories of their customers. Message sender identity can be easily forged. Regulators and even the mobile telephone industry itself has cautioned against the use of SMS in two-factor authentication schemes and other purposes where security is important. While the Camel component makes it as easy as possible to send messages to the SMS network, it can not offer an easy solution to these problems. == Data coding, alphabet and international character sets Data coding and alphabet can be specified on a per-message basis. Default values can be specified for the endpoint. It is important to understand the relationship between these options and the way the component acts when more than one value is set. Data coding is an 8 bit field in the SMPP wire format. Alphabet corresponds to bits 0-3 of the data coding field. For some types of message, where a message class is used (by setting bit 5 of the data coding field), the lower two bits of the data coding field are not interpreted as alphabet and only bits 2 and 3 impact the alphabet. Furthermore, current version of the JSMPP library only seems to support bits 2 and 3, assuming that bits 0 and 1 are used for message class. This is why the Alphabet class in JSMPP doesn't support the value 3 (binary 0011) which indicates ISO-8859-1. Although JSMPP provides a representation of the message class parameter, the Camel component doesn't currently provide a way to set it other than manually setting the corresponding bits in the data coding field. When setting the data coding field in the outgoing message, the Camel component considers the following values and uses the first one it can find: * the data coding specified in a header * the alphabet specified in a header * the data coding specified in the endpoint configuration (URI parameter) Older versions of Camel had bugs in support for international character sets. This feature only worked when a single encoding was used for all messages and was troublesome when users wanted to change it on a per-message basis. Users who require this to work should ensure their version of Camel includes the fix for JIRA Issues Macro: com.atlassian.sal.api.net.ResponseStatusException: Unexpected response received. Status code: 404 . In addition to trying to send the data coding value to the SMSC, the Camel component also tries to analyze the message body, convert it to a Java String (Unicode) and convert that to a byte array in the corresponding alphabet When deciding which alphabet to use in the byte array, the Camel SMPP component does not consider the data coding value (header or configuration), it only considers the specified alphabet (from either the header or endpoint parameter). If some characters in the String can't be represented in the chosen alphabet, they may be replaced by the question mark ( ? ) symbol. Users of the API may want to consider checking if their message body can be converted to ISO-8859-1 before passing it to the component and if not, setting the alphabet header to request UCS-2 encoding. If the alphabet and data coding options are not specified at all then the component may try to detect the required encoding and set the data coding for you. The list of alphabet codes are specified in the SMPP specification v3.4, section 5.2.19. One notable limitation of the SMPP specification is that there is no alphabet code for explicitly requesting use of the GSM 3.38 (7 bit) character set. Choosing the value 0 for the alphabet selects the SMSC _default_ alphabet, this usually means GSM 3.38 but it is not guaranteed. The SMPP gateway Nexmo https://help.nexmo.com/hc/en-us/articles/204015813-How-to-change-the-character-encoding-in-SMPP-[actually allows the default to be mapped to any other character set with a control panel option]. It is suggested that users check with their SMSC operator to confirm exactly which character set is being used as the default. == Message splitting and throttling After transforming a message body from a String to a byte array, the Camel component is also responsible for splitting the message into parts (within the 140 byte SMS size limit) before passing it to JSMPP. This is completed automatically. If the GSM 3.38 alphabet is used, the component will pack up to 160 characters into the 140 byte message body. If an 8 bit character set is used (e.g. ISO-8859-1 for western Europe) then 140 characters will be allowed within the 140 byte message body. If 16 bit UCS-2 encoding is used then just 70 characters fit into each 140 byte message. Some SMSC providers implement throttling rules. Each part of a message that has been split may be counted separately by the provider's throttling mechanism. The Camel Throttler component can be useful for throttling messages in the SMPP route before handing them to the SMSC. == URI format [source,java] -------------------------------------------- smpp://[username@]hostname[:port][?options] smpps://[username@]hostname[:port][?options] -------------------------------------------- If no *username* is provided, then Camel will provide the default value `smppclient`. + If no *port* number is provided, then Camel will provide the default value `2775`. + If the protocol name is ""smpps"", camel-smpp with try to use SSLSocket to init a connection to the server. You can append query options to the URI in the following format, `?option=value&option=value&...` == URI Options // component options: START The SMPP component supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (advanced) | To use the shared SmppConfiguration as configuration. | | SmppConfiguration | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean |=== // component options: END // endpoint options: START The SMPP endpoint is configured using URI syntax: ---- smpp:host:port ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *host* | Hostname for the SMSC server to use. | localhost | String | *port* | Port number for the SMSC server to use. | 2775 | Integer |=== === Query Parameters (40 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *initialReconnectDelay* (common) | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | long | *maxReconnect* (common) | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | int | *reconnectDelay* (common) | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | long | *splittingPolicy* (common) | You can specify a policy for handling long messages: ALLOW - the default, long messages are split to 140 bytes per message TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered. REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long. | ALLOW | SmppSplittingPolicy | *systemType* (common) | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *addressRange* (consumer) | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *destAddr* (producer) | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *destAddrNpi* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *destAddrTon* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *lazySessionCreation* (producer) | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *numberingPlanIndicator* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *priorityFlag* (producer) | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level 2 priority 3: Level 3 (highest) priority | | byte | *protocolId* (producer) | The protocol id | | byte | *registeredDelivery* (producer) | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined: 0: No SMSC delivery receipt requested. 1: SMSC delivery receipt requested where final delivery outcome is success or failure. 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure. | | byte | *replaceIfPresentFlag* (producer) | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined: 0: Don't replace 1: Replace | | byte | *serviceType* (producer) | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined: CMT: Cellular Messaging CPT: Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting WAP: Wireless Application Protocol USSD: Unstructured Supplementary Services Data | | String | *sourceAddr* (producer) | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *sourceAddrNpi* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *sourceAddrTon* (producer) | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *typeOfNumber* (producer) | Defines the type of number (TON) to be used in the SME. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *enquireLinkTimer* (advanced) | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *sessionStateListener* (advanced) | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transactionTimer* (advanced) | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *alphabet* (codec) | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19. 0: SMSC Default Alphabet 4: 8 bit Alphabet 8: UCS2 Alphabet | | byte | *dataCoding* (codec) | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are: 0: SMSC Default Alphabet 3: Latin 1 (ISO-8859-1) 4: Octet unspecified (8-bit binary) 8: UCS2 (ISO/IEC-10646) 13: Extended Kanji JIS(X 0212-1990) | | byte | *encoding* (codec) | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *httpProxyHost* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *httpProxyPassword* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *httpProxyPort* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *httpProxyUsername* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *proxyHeaders* (proxy) | These headers will be passed to the proxy server while establishing the connection. | | Map | *password* (security) | The password for connecting to SMSC server. | | String | *systemId* (security) | The system id (username) for connecting to SMSC server. | smppclient | String | *usingSSL* (security) | Whether using SSL with the smpps protocol | false | boolean |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel.springboot camel-smpp-starter x.x.x ---- The component supports 40 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.smpp.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.smpp.bridge-error-handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | Boolean | *camel.component.smpp.configuration.address-range* | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *camel.component.smpp.configuration.alphabet* | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19.
  • 0: SMSC Default Alphabet
  • 4: 8 bit Alphabet
  • 8: UCS2 Alphabet
| | Byte | *camel.component.smpp.configuration.data-coding* | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are:
  • 0: SMSC Default Alphabet
  • 3: Latin 1 (ISO-8859-1)
  • 4: Octet unspecified (8-bit binary)
  • 8: UCS2 (ISO/IEC-10646)
  • 13: Extended Kanji JIS(X 0212-1990)
| | Byte | *camel.component.smpp.configuration.dest-addr* | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *camel.component.smpp.configuration.dest-addr-npi* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.dest-addr-ton* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.encoding* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *camel.component.smpp.configuration.enquire-link-timer* | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *camel.component.smpp.configuration.host* | Hostname for the SMSC server to use. | localhost | String | *camel.component.smpp.configuration.http-proxy-host* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-password* | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-port* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *camel.component.smpp.configuration.http-proxy-username* | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *camel.component.smpp.configuration.initial-reconnect-delay* | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | Long | *camel.component.smpp.configuration.lazy-session-creation* | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | Boolean | *camel.component.smpp.configuration.max-reconnect* | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | Integer | *camel.component.smpp.configuration.numbering-plan-indicator* | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.password* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | | String | *camel.component.smpp.configuration.port* | Port number for the SMSC server to use. | 2775 | Integer | *camel.component.smpp.configuration.priority-flag* | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported:
  • 0: Level 0 (lowest) priority
  • 1: Level 1 priority
  • 2: Level 2 priority
  • 3: Level 3 (highest) priority
| | Byte | *camel.component.smpp.configuration.protocol-id* | The protocol id | | Byte | *camel.component.smpp.configuration.proxy-headers* | These headers will be passed to the proxy server while establishing the connection. | | Map | *camel.component.smpp.configuration.reconnect-delay* | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | Long | *camel.component.smpp.configuration.registered-delivery* | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined:
  • 0: No SMSC delivery receipt requested.
  • 1: SMSC delivery receipt requested where final delivery outcome is success or failure.
  • 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure.
| | Byte | *camel.component.smpp.configuration.replace-if-present-flag* | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined:
  • 0: Don't replace
  • 1: Replace
| | Byte | *camel.component.smpp.configuration.service-type* | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined:
  • CMT: Cellular Messaging
  • CPT: Cellular Paging
  • VMN: Voice Mail Notification
  • VMA: Voice Mail Alerting
  • WAP: Wireless Application Protocol
  • USSD: Unstructured Supplementary Services Data
| | String | *camel.component.smpp.configuration.session-state-listener* | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *camel.component.smpp.configuration.source-addr* | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *camel.component.smpp.configuration.source-addr-npi* | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.source-addr-ton* | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.splitting-policy* | You can specify a policy for handling long messages:
  • ALLOW - the default, long messages are split to 140 bytes per message
  • TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered.
  • REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long.
| | SmppSplittingPolicy | *camel.component.smpp.configuration.system-id* | The system id (username) for connecting to SMSC server. | smppclient | String | *camel.component.smpp.configuration.system-type* | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *camel.component.smpp.configuration.transaction-timer* | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *camel.component.smpp.configuration.type-of-number* | Defines the type of number (TON) to be used in the SME. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.using-s-s-l* | Whether using SSL with the smpps protocol | false | Boolean | *camel.component.smpp.enabled* | Enable smpp component | true | Boolean | *camel.component.smpp.lazy-start-producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | Boolean |=== // spring-boot-auto-configure options: END You can have as many of these options as you like. [source,java] ------------------------------------------------------------------------------------------------------------------ smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer ------------------------------------------------------------------------------------------------------------------ == Producer Message Headers The following message headers can be used to affect the behavior of the SMPP producer [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppDestAddr` |`List`/`String` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the destination SME address(es). For mobile terminated messages, this is the directory number of the recipient MS. Is must be a `List` for SubmitMulti and a `String` otherwise. |`CamelSmppDestAddrTon` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the type of number (TON) to be used in the SME destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppDestAddrNpi` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddr` |`String` |Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrTon` |`Byte` |Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppSourceAddrNpi` |`Byte` |Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppServiceType` |`String` |The service type parameter can be used to indicate the SMS Application service associated with the message. Use the URI option `serviceType` settings above. |`CamelSmppRegisteredDelivery` |`Byte` |*only for SubmitSm, ReplaceSm, SubmitMulti and DataSm* Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. Use the URI option `registeredDelivery` settings above. |`CamelSmppPriorityFlag` |`Byte` |*only for SubmitSm and SubmitMulti* Allows the originating SME to assign a priority level to the short message. Use the URI option `priorityFlag` settings above. |`CamelSmppScheduleDeliveryTime` |`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in chapter 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String`/`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. If it's provided as `Date`, it's interpreted as absolute time or relative time format if you provide it as `String` as specified in chapter 7.1.1 in the smpp specification v3.4. |`CamelSmppReplaceIfPresentFlag` |`Byte` |*only for SubmitSm and SubmitMulti* The replace if present flag parameter is used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following values are defined: `0`, Don't replace and `1`, Replace |`CamelSmppAlphabet` / `CamelSmppDataCoding` |`Byte` |*For SubmitSm, SubmitMulti and ReplaceSm* The data coding according to the SMPP 3.4 specification, section 5.2.19. Use the URI option `alphabet` settings above. |`CamelSmppOptionalParameter` |`Map` |*only for SubmitSm, SubmitMulti and DataSm* The optional parameter which are send to the SMSC. The value is converted in the following way: `String` -> `org.jsmpp.bean.OptionalParameter.COctetString`, `byte[]` -> `org.jsmpp.bean.OptionalParameter.OctetString`, `Byte` -> `org.jsmpp.bean.OptionalParameter.Byte`, `Integer` -> `org.jsmpp.bean.OptionalParameter.Int`, `Short` -> `org.jsmpp.bean.OptionalParameter.Short`, `null` -> `org.jsmpp.bean.OptionalParameter.Null` |CamelSmppEncoding |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the encoding (character set name) of the bytes in the message body. If the message body is a string then this is not relevant because Java Strings are always Unicode. If the body is a byte array then this header can be used to indicate that it is ISO-8859-1 or some other value. Default value is specified by the endpoint configuration parameter _encoding_ |CamelSmppSplittingPolicy |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the policy for message splitting for this exchange. Possible values are described in the endpoint configuration parameter _splittingPolicy_ |======================================================================= The following message headers are used by the SMPP producer to set the response from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppId` |`List`/`String` |The id to identify the submitted short message(s) for later use. In case of a ReplaceSm, QuerySm, CancelSm and DataSm this header vaule is a `String`. In case of a SubmitSm or SubmitMultiSm this header vaule is a `List`. |`CamelSmppSentMessageCount` |`Integer` |*only for SubmitSm and SubmitMultiSm* The total number of messages which has been sent. |`CamelSmppError` |`Map>>` |*only for SubmitMultiSm* The errors which occurred by sending the short message(s) the form `Map>>` (messageID : (destAddr : address, error : errorCode)). |`CamelSmppOptionalParameter` |`Map` |*only for DataSm* The optional parameter which are returned from the SMSC by sending the message. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= == Consumer Message Headers The following message headers are used by the SMPP consumer to set the request data from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppSequenceNumber` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* A sequence number allows a response PDU to be correlated with a request PDU. The associated SMPP response PDU must preserve this field. |`CamelSmppCommandId` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* The command id field identifies the particular SMPP PDU. For the complete list of defined values see chapter 5.1.2.1 in the smpp specification v3.4. |`CamelSmppSourceAddr` |`String` |*only for AlertNotification, DeliverSm and DataSm* Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrNpi` |`Byte` |*only for AlertNotification and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddrTon` |`Byte` |*only for AlertNotification and DataSm* Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppEsmeAddr` |`String` |*only for AlertNotification* Defines the destination ESME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppEsmeAddrNpi` |`Byte` |*only for AlertNotification* Defines the numeric plan indicator (NPI) to be used in the ESME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppEsmeAddrTon` |`Byte` |*only for AlertNotification* Defines the type of number (TON) to be used in the ESME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppId` |`String` |*only for smsc DeliveryReceipt and DataSm* The message ID allocated to the message by the SMSC when originally submitted. |`CamelSmppDelivered` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages delivered. This is only relevant where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDoneDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message reached it's final state. The format is as follows: YYMMDDhhmm. |`CamelSmppStatus` |`DeliveryReceiptState` |*only for smsc DeliveryReceipt:* The final status of the message. The following values are defined: `DELIVRD`: Message is delivered to destination, `EXPIRED`: Message validity period has expired, `DELETED`: Message has been deleted, `UNDELIV`: Message is undeliverable, `ACCEPTD`: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service), `UNKNOWN`: Message is in invalid state, `REJECTD`: Message is in a rejected state |`CamelSmppCommandStatus` |`Integer` |*only for DataSm* The Command status of the message. |`CamelSmppError` |`String` |*only for smsc DeliveryReceipt* Where appropriate this may hold a Network specific error code or an SMSC error code for the attempted delivery of the message. These errors are Network or SMSC specific and are not included here. |`CamelSmppSubmitDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message was submitted. In the case of a message which has been replaced, this is the date that the original message was replaced. The format is as follows: YYMMDDhhmm. |`CamelSmppSubmitted` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages originally submitted. This is only relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDestAddr` |`String` |*only for DeliverSm and DataSm:* Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppScheduleDeliveryTime` |`String` |*only for DeliverSm:* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in Section 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String` |*only for DeliverSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. It can be defined in absolute time format or relative time format. The encoding of absolute and relative time format is specified in Section 7.1.1 in the smpp specification v3.4. |`CamelSmppServiceType` |`String` |*only for DeliverSm and DataSm* The service type parameter indicates the SMS Application service associated with the message. |`CamelSmppRegisteredDelivery` |`Byte` |*only for DataSm* Is used to request an delivery receipt and/or SME originated acknowledgements. Same values as in Producer header list above. |`CamelSmppDestAddrNpi` |`Byte` |*only for DataSm* Defines the numeric plan indicator (NPI) in the destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppDestAddrTon` |`Byte` |*only for DataSm* Defines the type of number (TON) in the destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppMessageType` |`String` |Identifies the type of an incoming message: `AlertNotification`: an SMSC alert notification, `DataSm`: an SMSC data short message, `DeliveryReceipt`: an SMSC delivery receipt, `DeliverSm`: an SMSC deliver short message |`CamelSmppOptionalParameter` |`Map` |*only for DeliverSm* The optional parameters send back by the SMSC. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= TIP: *JSMPP library* See the documentation of the http://jsmpp.org[JSMPP Library] for more details about the underlying library. == Exception handling This component supports the general Camel exception handling capabilities When an error occurs sending a message with SubmitSm (the default action), the org.apache.camel.component.smpp.SmppException is thrown with a nested exception, org.jsmpp.extra.NegativeResponseException. Call NegativeResponseException.getCommandStatus() to obtain the exact SMPP negative response code, the values are explained in the SMPP specification 3.4, section 5.1.3. + When the SMPP consumer receives a `DeliverSm` or `DataSm` short message and the processing of these messages fails, you can also throw a `ProcessRequestException` instead of handle the failure. In this case, this exception is forwarded to the underlying http://jsmpp.org[JSMPP library] which will return the included error code to the SMSC. This feature is useful to e.g. instruct the SMSC to resend the short message at a later time. This could be done with the following lines of code: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .doTry() .to(""bean:dao?method=updateSmsState"") .doCatch(Exception.class) .throwException(new ProcessRequestException(""update of sms state failed"", 100)) .end(); -------------------------------------------------------------------------------------------------------------------------- Please refer to the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP specification] for the complete list of error codes and their meanings. == Samples A route which sends an SMS using the Java DSL: [source,java] ------------------------------------------------------------------------------------------ from(""direct:start"") .to(""smpp://smppclient@localhost:2775? password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=producer""); ------------------------------------------------------------------------------------------ A route which sends an SMS using the Spring XML DSL: [source,xml] ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Java DSL: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Spring XML DSL: [source,xml] ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- TIP: *SMSC simulator* If you need an SMSC simulator for your test, you can use the simulator provided by http://opensmpp.logica.com/CommonPart/Download/download2.html#simulator[Logica]. == Debug logging This component has log level *DEBUG*, which can be helpful in debugging problems. If you use log4j, you can add the following line to your configuration: [source,java] -------------------------------------------------- log4j.logger.org.apache.camel.component.smpp=DEBUG -------------------------------------------------- ",12109,False,2387.790384054265,median "// The complete list is available here: https://github.com/olikraus/u8g2/wiki/u8x8setupcpp // Please update the pin numbers according to your setup. Use U8X8_PIN_NONE if the reset pin is not connected //U8X8_NULL u8x8; // null device, a 8x8 pixel display which does nothing //U8X8_SSD1306_128X64_NONAME_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1306_128X64_NONAME_4W_HW_SPI u8x8(/* cs=*/ 6, /* dc=*/ 4, /* reset=*/ 12); // Arduboy (DevKit) //U8X8_SSD1306_128X64_NONAME_4W_HW_SPI u8x8(/* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy 10 (Production, Kickstarter Edition) //U8X8_SSD1306_128X64_NONAME_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1306_128X64_NONAME_3W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); //U8X8_SSD1306_128X64_ALT0_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ 2, /* data=*/ 0, /* reset=*/ U8X8_PIN_NONE); // Digispark ATTiny85 //U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // OLEDs without Reset of the Display //U8X8_SSD1306_128X64_VCOMH0_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8X8_SSD1306_128X64_ALT0_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but may solve the ""every 2nd line skipped"" problem //U8X8_SH1106_128X64_NONAME_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); //U8X8_SH1106_128X64_VCOMH0_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but maximizes setContrast() range //U8X8_SH1106_128X64_WINSTAR_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // same as the NONAME variant, but uses updated SH1106 init sequence //U8X8_SH1106_72X40_WISE_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SH1107_64X128_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SH1107_128X128_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SH1107_128X128_HW_I2C u8x8(/* reset=*/ 8); //U8X8_SH1107_SEEED_96X96_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SH1108_160X160_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1306_128X32_UNIVISION_SW_I2C u8x8(/* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather ESP8266/32u4 Boards + FeatherWing OLED //U8X8_SSD1306_128X32_UNIVISION_SW_I2C u8x8(/* clock=*/ 21, /* data=*/ 20, /* reset=*/ U8X8_PIN_NONE); // Adafruit Feather M0 Basic Proto + FeatherWing OLED //U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); // Adafruit ESP8266/32u4/ARM Boards + FeatherWing OLED //U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA); // pin remapping with ESP8266 HW I2C //U8X8_SSD1306_64X48_ER_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); // EastRising 0.66"" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered //U8X8_SSD1306_48X64_WINSTAR_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); //U8X8_SSD1306_64X32_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); //U8X8_SSD1306_64X32_1F_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); //U8X8_SSD1306_96X16_ER_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); // EastRising 0.69"" //U8X8_SSD1306_128X64_NONAME_6800 u8x8(13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8X8_SSD1306_128X64_NONAME_8080 u8x8(13, 11, 2, 3, 4, 5, 6, A4, /*enable=*/ 7, /*cs=*/ 10, /*dc=*/ 9, /*reset=*/ 8); //U8X8_SSD1309_128X64_NONAME0_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1309_128X64_NONAME0_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1309_128X64_NONAME2_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1309_128X64_NONAME2_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1317_96X96_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1317_96X96_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1322_NHD_256X64_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1322_NHD_256X64_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1322_NHD_128X64_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1322_NHD_128X64_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1325_NHD_128X64_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1325_NHD_128X64_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD0323_OS128064_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD0323_OS128064_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1326_ER_256X32_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // experimental driver for ER-OLED018-1 //U8X8_SSD1327_SEEED_96X96_SW_I2C u8x8(/* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8X8_SSD1327_SEEED_96X96_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); // Seeedstudio Grove OLED 96x96 //U8X8_SSD1327_EA_W128128_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1327_EA_W128128_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1327_MIDAS_128X128_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1327_MIDAS_128X128_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1329_128X96_NONAME_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1329_128X96_NONAME_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1305_128X32_NONAME_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1305_128X32_NONAME_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1305_128X32_ADAFRUIT_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1305_128X32_ADAFRUIT_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1305_128X64_ADAFRUIT_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_SSD1305_128X64_ADAFRUIT_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_KS0108_128X64 u8x8(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! //U8X8_KS0108_ERM19264 u8x8(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! //U8X8_UC1701_EA_DOGS102_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_UC1701_EA_DOGS102_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_PCD8544_84X48_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8X8_PCD8544_84X48_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Nokia 5110 Display //U8X8_PCF8812_96X65_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8X8_PCF8812_96X65_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Could be also PCF8814 //U8X8_HX1230_96X68_3W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8X8_HX1230_96X68_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_EA_DOGM128_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_EA_DOGM128_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_64128N_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_64128N_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_EA_DOGM132_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8X8_ST7565_EA_DOGM132_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); // DOGM132 Shield //U8X8_ST7565_ZOLEN_128X64_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_ZOLEN_128X64_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_LM6059_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8X8_ST7565_LM6059_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Adafruit ST7565 GLCD //U8X8_ST7565_LX12864_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_LX12864_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_ERC12864_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_ERC12864_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_NHD_C12832_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_NHD_C12832_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_NHD_C12864_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_NHD_C12864_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_JLX12864_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7565_JLX12864_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7567_PI_132X64_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8X8_ST7567_PI_132X64_4W_HW_SPI u8x8(/* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6 //U8X8_ST7567_JLX12864_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7567_JLX12864_4W_HW_SPI u8x8(/* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7567_ENH_DG128064_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7567_ENH_DG128064_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7567_ENH_DG128064I_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7567_ENH_DG128064I_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7567_64X32_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); //U8X8_ST75256_JLX172104_4W_SW_SPI u8x8( /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST75256_JLX172104_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST75256_JLX256128_4W_SW_SPI u8x8( /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST75256_JLX256128_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST75256_JLX256160_4W_SW_SPI u8x8( /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST75256_JLX256160_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST75256_JLX240160_4W_SW_SPI u8x8( /* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST75256_JLX240160_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST75256_JLX25664_2ND_HW_I2C u8x8(/* reset=*/ 8); // Due, 2nd I2C //U8X8_NT7534_TG12864R_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_NT7534_TG12864R_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_ST7588_JLX12864_SW_I2C u8x8(/* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ 5); //U8X8_ST7588_JLX12864_HW_I2C u8x8(/* reset=*/ 5); //U8X8_IST3020_ERC19264_6800 u8x8(44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 28, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect WR pin with GND //U8X8_IST3020_ERC19264_8080 u8x8(44, 43, 42, 41, 40, 39, 38, 37, /*enable=*/ 29, /*cs=*/ 32, /*dc=*/ 30, /*reset=*/ 31); // Connect RD pin with 3.3V //U8X8_IST3020_ERC19264_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_UC1601_128X32_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_UC1601_128X32_3W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* reset=*/ 8); //U8X8_UC1604_JLX19264_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_UC1604_JLX19264_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_UC1608_ERC24064_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Due, SW SPI, ERC24064-1 Test Board //U8X8_UC1608_ERC240120_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_UC1608_240X128_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); //U8X8_UC1610_EA_DOGXL160_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8X8_UC1610_EA_DOGXL160_4W_HW_SPI u8x8(/* cs=*/ 10, /* dc=*/ 9, /* reset=*/ U8X8_PIN_NONE); //U8X8_UC1611_EA_DOGM240_2ND_HW_I2C u8x8(/* reset=*/ 8); // Due, 2nd I2C, DOGM240 Test Board //U8X8_UC1611_EA_DOGM240_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8X8_UC1611_EA_DOGXL240_2ND_HW_I2C u8x8(/* reset=*/ 8); // Due, 2nd I2C, DOGXL240 Test Board //U8X8_UC1611_EA_DOGXL240_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // SW SPI, Due DOGXL240 Test Board //U8X8_UC1611_EW50850_8080 u8x8(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 //U8X8_UC1638_160X128_4W_HW_SPI u8x8(/* cs=*/ 2, /* dc=*/ 3, /* reset=*/ 4); // Not tested //U8X8_SSD1606_172X72_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display //U8X8_SSD1607_200X200_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT from embedded artists //U8X8_SSD1607_GS_200X200_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // Good Display //U8X8_IL3820_296X128_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, original LUT //U8X8_IL3820_V2_296X128_4W_SW_SPI u8x8(/* clock=*/ 13, /* data=*/ 11, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8); // eInk/ePaper Display, optimized (lesser screen flicker) ",8047,False,2348.3386359988313,median "CLASS zcl_abapgit_git_pack DEFINITION PUBLIC CREATE PUBLIC . PUBLIC SECTION. TYPES: BEGIN OF ty_node, chmod TYPE zif_abapgit_definitions=>ty_chmod, name TYPE string, sha1 TYPE zif_abapgit_definitions=>ty_sha1, END OF ty_node . TYPES: ty_nodes_tt TYPE STANDARD TABLE OF ty_node WITH DEFAULT KEY . TYPES: BEGIN OF ty_commit, tree TYPE zif_abapgit_definitions=>ty_sha1, parent TYPE zif_abapgit_definitions=>ty_sha1, parent2 TYPE zif_abapgit_definitions=>ty_sha1, author TYPE string, committer TYPE string, gpgsig TYPE string, body TYPE string, END OF ty_commit . TYPES: BEGIN OF ty_tag, object TYPE string, type TYPE string, tag TYPE string, tagger_name TYPE string, tagger_email TYPE string, message TYPE string, body TYPE string, END OF ty_tag . CLASS-METHODS decode IMPORTING !iv_data TYPE xstring RETURNING VALUE(rt_objects) TYPE zif_abapgit_definitions=>ty_objects_tt RAISING zcx_abapgit_exception . CLASS-METHODS decode_tree IMPORTING !iv_data TYPE xstring RETURNING VALUE(rt_nodes) TYPE ty_nodes_tt RAISING zcx_abapgit_exception . CLASS-METHODS decode_commit IMPORTING !iv_data TYPE xstring RETURNING VALUE(rs_commit) TYPE ty_commit RAISING zcx_abapgit_exception . CLASS-METHODS decode_tag IMPORTING !iv_data TYPE xstring RETURNING VALUE(rs_tag) TYPE ty_tag RAISING zcx_abapgit_exception . CLASS-METHODS encode IMPORTING !it_objects TYPE zif_abapgit_definitions=>ty_objects_tt RETURNING VALUE(rv_data) TYPE xstring RAISING zcx_abapgit_exception . CLASS-METHODS encode_tree IMPORTING !it_nodes TYPE ty_nodes_tt RETURNING VALUE(rv_data) TYPE xstring . CLASS-METHODS encode_commit IMPORTING !is_commit TYPE ty_commit RETURNING VALUE(rv_data) TYPE xstring . CLASS-METHODS encode_tag IMPORTING !is_tag TYPE ty_tag RETURNING VALUE(rv_data) TYPE xstring RAISING zcx_abapgit_exception . PROTECTED SECTION. PRIVATE SECTION. CONSTANTS: c_pack_start TYPE x LENGTH 4 VALUE '5041434B' ##NO_TEXT. CONSTANTS: c_zlib TYPE x LENGTH 2 VALUE '789C' ##NO_TEXT. CONSTANTS: c_zlib_hmm TYPE x LENGTH 2 VALUE '7801' ##NO_TEXT. CONSTANTS: "" PACK c_version TYPE x LENGTH 4 VALUE '00000002' ##NO_TEXT. CLASS-METHODS decode_deltas CHANGING !ct_objects TYPE zif_abapgit_definitions=>ty_objects_tt RAISING zcx_abapgit_exception . CLASS-METHODS delta IMPORTING !is_object TYPE zif_abapgit_definitions=>ty_object CHANGING !ct_objects TYPE zif_abapgit_definitions=>ty_objects_tt RAISING zcx_abapgit_exception . CLASS-METHODS delta_header IMPORTING !io_stream TYPE REF TO lcl_stream RETURNING VALUE(rv_header) TYPE i . CLASS-METHODS sort_tree IMPORTING !it_nodes TYPE ty_nodes_tt RETURNING VALUE(rt_nodes) TYPE ty_nodes_tt . CLASS-METHODS get_type IMPORTING !iv_x TYPE x RETURNING VALUE(rv_type) TYPE zif_abapgit_definitions=>ty_type RAISING zcx_abapgit_exception . CLASS-METHODS get_length EXPORTING !ev_length TYPE i CHANGING !cv_data TYPE xstring . CLASS-METHODS type_and_length IMPORTING !iv_type TYPE zif_abapgit_definitions=>ty_type !iv_length TYPE i RETURNING VALUE(rv_xstring) TYPE xstring RAISING zcx_abapgit_exception . CLASS-METHODS zlib_decompress CHANGING !cv_data TYPE xstring !cv_decompressed TYPE xstring RAISING zcx_abapgit_exception . ENDCLASS. CLASS ZCL_ABAPGIT_GIT_PACK IMPLEMENTATION. METHOD decode. DATA: lv_x TYPE x, lv_data TYPE xstring, lv_type TYPE c LENGTH 6, lv_zlib TYPE x LENGTH 2, lv_objects TYPE i, lv_len TYPE i, lv_sha1 TYPE zif_abapgit_definitions=>ty_sha1, lv_ref_delta TYPE zif_abapgit_definitions=>ty_sha1, lv_compressed_len TYPE i, lv_compressed TYPE xstring, lv_decompressed TYPE xstring, lv_decompress_len TYPE i, lv_xstring TYPE xstring, lv_expected TYPE i, ls_object LIKE LINE OF rt_objects, lv_uindex TYPE sy-index. lv_data = iv_data. * header IF NOT xstrlen( lv_data ) > 4 OR lv_data(4) <> c_pack_start. zcx_abapgit_exception=>raise( |Unexpected pack header| ). ENDIF. lv_data = lv_data+4. * version IF lv_data(4) <> c_version. zcx_abapgit_exception=>raise( |Version not supported| ). ENDIF. lv_data = lv_data+4. * number of objects lv_xstring = lv_data(4). lv_objects = zcl_abapgit_convert=>xstring_to_int( lv_xstring ). lv_data = lv_data+4. DO lv_objects TIMES. lv_uindex = sy-index. lv_x = lv_data(1). lv_type = get_type( lv_x ). get_length( IMPORTING ev_length = lv_expected CHANGING cv_data = lv_data ). IF lv_type = zif_abapgit_definitions=>c_type-ref_d. lv_ref_delta = lv_data(20). lv_data = lv_data+20. ENDIF. * strip header, '789C', CMF + FLG lv_zlib = lv_data(2). IF lv_zlib <> c_zlib AND lv_zlib <> c_zlib_hmm. zcx_abapgit_exception=>raise( |Unexpected zlib header| ). ENDIF. lv_data = lv_data+2. ******************************* IF lv_zlib = c_zlib. cl_abap_gzip=>decompress_binary( EXPORTING gzip_in = lv_data IMPORTING raw_out = lv_decompressed raw_out_len = lv_decompress_len ). IF lv_expected <> lv_decompress_len. zcx_abapgit_exception=>raise( |Decompression falied| ). ENDIF. cl_abap_gzip=>compress_binary( EXPORTING raw_in = lv_decompressed IMPORTING gzip_out = lv_compressed gzip_out_len = lv_compressed_len ). IF lv_compressed(lv_compressed_len) <> lv_data(lv_compressed_len). ""Lets try with zlib before error in out for good ""This fixes issues with TFS 2017 and visualstudio.com Git repos zlib_decompress( CHANGING cv_data = lv_data cv_decompressed = lv_decompressed ). ELSE. lv_data = lv_data+lv_compressed_len. ENDIF. ELSEIF lv_zlib = c_zlib_hmm. * cl_abap_gzip copmression works for header '789C', but does not work for * '7801', call custom implementation of DEFLATE algorithm. * The custom implementation could handle both, but most likely the kernel * implementation runs faster than the custom ABAP. zlib_decompress( CHANGING cv_data = lv_data cv_decompressed = lv_decompressed ). ENDIF. CLEAR ls_object. ls_object-adler32 = lv_data(4). lv_data = lv_data+4. "" skip adler checksum IF lv_type = zif_abapgit_definitions=>c_type-ref_d. ls_object-sha1 = lv_ref_delta. TRANSLATE ls_object-sha1 TO LOWER CASE. ELSE. ls_object-sha1 = zcl_abapgit_hash=>sha1( iv_type = lv_type iv_data = lv_decompressed ). ENDIF. ls_object-type = lv_type. ls_object-data = lv_decompressed. ls_object-index = lv_uindex. APPEND ls_object TO rt_objects. ENDDO. * check SHA1 at end of pack lv_len = xstrlen( iv_data ) - 20. lv_xstring = iv_data(lv_len). lv_sha1 = zcl_abapgit_hash=>sha1_raw( lv_xstring ). IF to_upper( lv_sha1 ) <> lv_data. zcx_abapgit_exception=>raise( |SHA1 at end of pack doesnt match| ). ENDIF. decode_deltas( CHANGING ct_objects = rt_objects ). ENDMETHOD. METHOD decode_commit. DATA: lv_string TYPE string, lv_word TYPE string, lv_offset TYPE i, lv_length TYPE i, lv_length_gpgsig TYPE i, lv_trash TYPE string ##NEEDED, lt_string TYPE TABLE OF string. FIELD-SYMBOLS: LIKE LINE OF lt_string. lv_string = zcl_abapgit_convert=>xstring_to_string_utf8( iv_data ). SPLIT lv_string AT zif_abapgit_definitions=>c_newline INTO TABLE lt_string. LOOP AT lt_string ASSIGNING . lv_length = strlen( ) + 1. lv_string = lv_string+lv_length. SPLIT AT space INTO lv_word lv_trash. CASE lv_word. WHEN 'tree'. rs_commit-tree = +5. WHEN 'parent'. IF rs_commit-parent IS INITIAL. rs_commit-parent = +7. ELSE. rs_commit-parent2 = +7. ENDIF. WHEN 'author'. rs_commit-author = +7. WHEN 'committer'. rs_commit-committer = +10. EXIT. "" current loop WHEN OTHERS. ASSERT 1 = 0. ENDCASE. ENDLOOP. lv_length = strlen( lv_string ). IF lv_length >= 6 AND lv_string+0(6) = 'gpgsig'. FIND REGEX |-----END PGP SIGNATURE-----[[:space:]]+| IN lv_string MATCH OFFSET lv_offset MATCH LENGTH lv_length. lv_length = lv_length - 1. lv_length_gpgsig = lv_offset + lv_length - 7. lv_length = lv_offset + lv_length. rs_commit-gpgsig = lv_string+7(lv_length_gpgsig). lv_string = lv_string+lv_length. ENDIF. rs_commit-body = lv_string+1. IF rs_commit-author IS INITIAL OR rs_commit-committer IS INITIAL OR rs_commit-tree IS INITIAL. zcx_abapgit_exception=>raise( |multiple parents? not supported| ). ENDIF. ENDMETHOD. METHOD decode_deltas. DATA: ls_object LIKE LINE OF ct_objects, li_progress TYPE REF TO zif_abapgit_progress, lt_deltas LIKE ct_objects. LOOP AT ct_objects INTO ls_object USING KEY type WHERE type = zif_abapgit_definitions=>c_type-ref_d. INSERT ls_object INTO TABLE lt_deltas. ENDLOOP. DELETE ct_objects USING KEY type WHERE type = zif_abapgit_definitions=>c_type-ref_d. ""Restore correct Delta Order SORT lt_deltas BY index. li_progress = zcl_abapgit_progress=>get_instance( lines( lt_deltas ) ). LOOP AT lt_deltas INTO ls_object. li_progress->show( iv_current = sy-tabix iv_text = 'Decode deltas' ). delta( EXPORTING is_object = ls_object CHANGING ct_objects = ct_objects ). ENDLOOP. ENDMETHOD. METHOD decode_tag. DATA: lv_string TYPE string, lv_word TYPE string, lv_trash TYPE string ##NEEDED, lt_string TYPE TABLE OF string. FIELD-SYMBOLS: LIKE LINE OF lt_string. lv_string = zcl_abapgit_convert=>xstring_to_string_utf8( iv_data ). SPLIT lv_string AT zif_abapgit_definitions=>c_newline INTO TABLE lt_string. LOOP AT lt_string ASSIGNING . SPLIT AT space INTO lv_word lv_trash. CASE lv_word. WHEN 'object'. rs_tag-object = lv_trash. WHEN 'type'. rs_tag-type = lv_trash. WHEN 'tag'. rs_tag-tag = lv_trash. WHEN 'tagger'. FIND FIRST OCCURRENCE OF REGEX `(.*)<(.*)>` IN lv_trash SUBMATCHES rs_tag-tagger_name rs_tag-tagger_email. rs_tag-tagger_name = condense( rs_tag-tagger_name ). WHEN ''. "" ignore blank lines CONTINUE. WHEN OTHERS. "" these are the non empty line which don't start with a key word "" the first one is the message, the rest are cumulated to the body IF rs_tag-message IS INITIAL. rs_tag-message = . ELSE. IF rs_tag-body IS NOT INITIAL. rs_tag-body = rs_tag-body && zif_abapgit_definitions=>c_newline. ENDIF. rs_tag-body = rs_tag-body && . ENDIF. ENDCASE. ENDLOOP. ENDMETHOD. METHOD decode_tree. CONSTANTS: lc_sha_length TYPE i VALUE 20, lc_null TYPE x VALUE '00'. DATA: lv_xstring TYPE xstring, lv_chmod TYPE zif_abapgit_definitions=>ty_chmod, lv_name TYPE string, lv_string TYPE string, lv_len TYPE i, lv_offset TYPE i, lv_cursor TYPE i, lv_match TYPE i, ls_node TYPE ty_node. DO. FIND FIRST OCCURRENCE OF lc_null IN SECTION OFFSET lv_cursor OF iv_data IN BYTE MODE MATCH OFFSET lv_match. IF sy-subrc <> 0. EXIT. ENDIF. lv_len = lv_match - lv_cursor. lv_xstring = iv_data+lv_cursor(lv_len). lv_string = zcl_abapgit_convert=>xstring_to_string_utf8( lv_xstring ). SPLIT lv_string AT space INTO lv_chmod lv_name. CLEAR ls_node. ls_node-chmod = lv_chmod. IF ls_node-chmod <> zif_abapgit_definitions=>c_chmod-dir AND ls_node-chmod <> zif_abapgit_definitions=>c_chmod-file AND ls_node-chmod <> zif_abapgit_definitions=>c_chmod-executable. zcx_abapgit_exception=>raise( |Unknown chmod| ). ENDIF. lv_offset = lv_match + 1. ls_node-name = lv_name. ls_node-sha1 = iv_data+lv_offset(lc_sha_length). TRANSLATE ls_node-sha1 TO LOWER CASE. APPEND ls_node TO rt_nodes. lv_cursor = lv_match + 1 + lc_sha_length. ENDDO. ENDMETHOD. METHOD delta. CONSTANTS: lc_1 TYPE x VALUE '01', lc_2 TYPE x VALUE '02', lc_4 TYPE x VALUE '04', lc_8 TYPE x VALUE '08', lc_16 TYPE x VALUE '10', lc_32 TYPE x VALUE '20', lc_64 TYPE x VALUE '40', lc_128 TYPE x VALUE '80'. DATA: lv_base TYPE xstring, lv_result TYPE xstring, lv_offset TYPE i, lo_stream TYPE REF TO lcl_stream, lv_sha1 TYPE zif_abapgit_definitions=>ty_sha1, ls_object LIKE LINE OF ct_objects, lv_len TYPE i, lv_tmp TYPE xstring, lv_org TYPE x. FIELD-SYMBOLS: LIKE LINE OF ct_objects. CREATE OBJECT lo_stream EXPORTING iv_data = is_object-data. * find base READ TABLE ct_objects ASSIGNING WITH KEY sha COMPONENTS sha1 = is_object-sha1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |Base not found, { is_object-sha1 }| ). ELSEIF -type = zif_abapgit_definitions=>c_type-ref_d. * sanity check zcx_abapgit_exception=>raise( |Delta, base eq delta| ). ENDIF. lv_base = -data. * skip the 2 headers delta_header( lo_stream ). delta_header( lo_stream ). WHILE xstrlen( lo_stream->get( ) ) > 0. lv_org = lo_stream->eat_byte( ). IF lv_org BIT-AND lc_128 = lc_128. "" MSB = 1 lv_offset = 0. IF lv_org BIT-AND lc_1 = lc_1. lv_offset = lo_stream->eat_byte( ). ENDIF. IF lv_org BIT-AND lc_2 = lc_2. lv_offset = lv_offset + lo_stream->eat_byte( ) * 256. ENDIF. IF lv_org BIT-AND lc_4 = lc_4. lv_offset = lv_offset + lo_stream->eat_byte( ) * 65536. ENDIF. IF lv_org BIT-AND lc_8 = lc_8. lv_offset = lv_offset + lo_stream->eat_byte( ) * 16777216. "" hmm, overflow? ENDIF. lv_len = 0. IF lv_org BIT-AND lc_16 = lc_16. lv_len = lo_stream->eat_byte( ). ENDIF. IF lv_org BIT-AND lc_32 = lc_32. lv_len = lv_len + lo_stream->eat_byte( ) * 256. ENDIF. IF lv_org BIT-AND lc_64 = lc_64. lv_len = lv_len + lo_stream->eat_byte( ) * 65536. ENDIF. IF lv_len = 0. lv_len = 65536. ENDIF. CONCATENATE lv_result lv_base+lv_offset(lv_len) INTO lv_result IN BYTE MODE. ELSE. "" lv_bitbyte(1) = '0' * insert from delta lv_len = lv_org. "" convert to int lv_tmp = lo_stream->eat_bytes( lv_len ). CONCATENATE lv_result lv_tmp INTO lv_result IN BYTE MODE. ENDIF. ENDWHILE. lv_sha1 = zcl_abapgit_hash=>sha1( iv_type = -type iv_data = lv_result ). CLEAR ls_object. ls_object-sha1 = lv_sha1. ls_object-type = -type. ls_object-data = lv_result. ls_object-index = -index. ""Retain sort index APPEND ls_object TO ct_objects. ENDMETHOD. METHOD delta_header. DATA: lv_bitbyte TYPE zif_abapgit_definitions=>ty_bitbyte, lv_bits TYPE string, lv_x TYPE x. lv_bits = ''. DO. lv_x = io_stream->eat_byte( ). lv_bitbyte = zcl_abapgit_convert=>x_to_bitbyte( lv_x ). CONCATENATE lv_bitbyte+1 lv_bits INTO lv_bits. IF lv_bitbyte(1) = '0'. EXIT. "" current loop ENDIF. ENDDO. rv_header = zcl_abapgit_convert=>bitbyte_to_int( lv_bits ). ENDMETHOD. METHOD encode. DATA: lv_sha1 TYPE x LENGTH 20, lv_adler32 TYPE zif_abapgit_definitions=>ty_adler32, lv_compressed TYPE xstring, lv_xstring TYPE xstring, li_progress TYPE REF TO zif_abapgit_progress, lv_objects_total TYPE i. FIELD-SYMBOLS: LIKE LINE OF it_objects. rv_data = c_pack_start. CONCATENATE rv_data c_version INTO rv_data IN BYTE MODE. lv_xstring = zcl_abapgit_convert=>int_to_xstring4( lines( it_objects ) ). CONCATENATE rv_data lv_xstring INTO rv_data IN BYTE MODE. lv_objects_total = lines( it_objects ). li_progress = zcl_abapgit_progress=>get_instance( lv_objects_total ). LOOP AT it_objects ASSIGNING . IF sy-tabix MOD 200 = 0. li_progress->show( iv_current = sy-tabix iv_text = |Encoding objects ( { sy-tabix } of { lv_objects_total } )| ). ENDIF. lv_xstring = type_and_length( iv_type = -type iv_length = xstrlen( -data ) ). CONCATENATE rv_data lv_xstring INTO rv_data IN BYTE MODE. cl_abap_gzip=>compress_binary( EXPORTING raw_in = -data IMPORTING gzip_out = lv_compressed ). CONCATENATE rv_data c_zlib lv_compressed INTO rv_data IN BYTE MODE. IF NOT -adler32 IS INITIAL. lv_adler32 = -adler32. ELSE. lv_adler32 = zcl_abapgit_hash=>adler32( -data ). ENDIF. CONCATENATE rv_data lv_adler32 INTO rv_data IN BYTE MODE. ENDLOOP. lv_sha1 = to_upper( zcl_abapgit_hash=>sha1_raw( rv_data ) ). CONCATENATE rv_data lv_sha1 INTO rv_data IN BYTE MODE. ENDMETHOD. METHOD encode_commit. DATA: lv_string TYPE string, lv_tmp TYPE string, lv_tree_lower TYPE string, lv_parent_lower TYPE string. lv_tree_lower = is_commit-tree. TRANSLATE lv_tree_lower TO LOWER CASE. lv_string = ''. CONCATENATE 'tree' lv_tree_lower INTO lv_tmp SEPARATED BY space. CONCATENATE lv_string lv_tmp zif_abapgit_definitions=>c_newline INTO lv_string. IF NOT is_commit-parent IS INITIAL. lv_parent_lower = is_commit-parent. TRANSLATE lv_parent_lower TO LOWER CASE. CONCATENATE 'parent' lv_parent_lower INTO lv_tmp SEPARATED BY space. CONCATENATE lv_string lv_tmp zif_abapgit_definitions=>c_newline INTO lv_string. ENDIF. IF NOT is_commit-parent2 IS INITIAL. lv_parent_lower = is_commit-parent2. TRANSLATE lv_parent_lower TO LOWER CASE. CONCATENATE 'parent' lv_parent_lower INTO lv_tmp SEPARATED BY space. CONCATENATE lv_string lv_tmp zif_abapgit_definitions=>c_newline INTO lv_string. ENDIF. CONCATENATE 'author' is_commit-author INTO lv_tmp SEPARATED BY space. CONCATENATE lv_string lv_tmp zif_abapgit_definitions=>c_newline INTO lv_string. CONCATENATE 'committer' is_commit-committer INTO lv_tmp SEPARATED BY space. CONCATENATE lv_string lv_tmp zif_abapgit_definitions=>c_newline INTO lv_string. IF NOT is_commit-gpgsig IS INITIAL. CONCATENATE 'gpgsig' is_commit-gpgsig INTO lv_tmp SEPARATED BY space. CONCATENATE lv_string lv_tmp INTO lv_string. ENDIF. CONCATENATE lv_string zif_abapgit_definitions=>c_newline is_commit-body INTO lv_string. rv_data = zcl_abapgit_convert=>string_to_xstring_utf8( lv_string ). ENDMETHOD. METHOD encode_tag. DATA: lv_string TYPE string, lv_time TYPE zcl_abapgit_time=>ty_unixtime. lv_time = zcl_abapgit_time=>get_unix( ). lv_string = |object { is_tag-object }{ zif_abapgit_definitions=>c_newline }| && |type { is_tag-type }{ zif_abapgit_definitions=>c_newline }| && |tag { zcl_abapgit_git_tag=>remove_tag_prefix( is_tag-tag ) }{ zif_abapgit_definitions=>c_newline }| && |tagger { is_tag-tagger_name } <{ is_tag-tagger_email }> { lv_time }| && |{ zif_abapgit_definitions=>c_newline }| && |{ zif_abapgit_definitions=>c_newline }| && |{ is_tag-message }|. rv_data = zcl_abapgit_convert=>string_to_xstring_utf8( lv_string ). ENDMETHOD. METHOD encode_tree. CONSTANTS: lc_null TYPE x VALUE '00'. DATA: lv_string TYPE string, lt_nodes LIKE it_nodes, lv_hex20 TYPE x LENGTH 20, lv_xstring TYPE xstring. FIELD-SYMBOLS: LIKE LINE OF it_nodes. lt_nodes = sort_tree( it_nodes ). LOOP AT lt_nodes ASSIGNING . ASSERT NOT -chmod IS INITIAL. ASSERT NOT -name IS INITIAL. ASSERT NOT -sha1 IS INITIAL. CONCATENATE -chmod -name INTO lv_string SEPARATED BY space. lv_xstring = zcl_abapgit_convert=>string_to_xstring_utf8( lv_string ). lv_hex20 = to_upper( -sha1 ). CONCATENATE rv_data lv_xstring lc_null lv_hex20 INTO rv_data IN BYTE MODE. ENDLOOP. ENDMETHOD. METHOD get_length. DATA: lv_x TYPE x, lv_length_bits TYPE string, lv_bitbyte TYPE zif_abapgit_definitions=>ty_bitbyte. lv_x = cv_data(1). lv_bitbyte = zcl_abapgit_convert=>x_to_bitbyte( lv_x ). cv_data = cv_data+1. lv_length_bits = lv_bitbyte+4. WHILE lv_bitbyte(1) <> '0'. lv_x = cv_data(1). lv_bitbyte = zcl_abapgit_convert=>x_to_bitbyte( lv_x ). cv_data = cv_data+1. CONCATENATE lv_bitbyte+1 lv_length_bits INTO lv_length_bits. ENDWHILE. ev_length = zcl_abapgit_convert=>bitbyte_to_int( lv_length_bits ). ENDMETHOD. METHOD get_type. CONSTANTS: lc_mask TYPE x VALUE 112. DATA: lv_xtype TYPE x. lv_xtype = iv_x BIT-AND lc_mask. CASE lv_xtype. WHEN 16. rv_type = zif_abapgit_definitions=>c_type-commit. WHEN 32. rv_type = zif_abapgit_definitions=>c_type-tree. WHEN 48. rv_type = zif_abapgit_definitions=>c_type-blob. WHEN 64. rv_type = zif_abapgit_definitions=>c_type-tag. WHEN 112. rv_type = zif_abapgit_definitions=>c_type-ref_d. WHEN OTHERS. zcx_abapgit_exception=>raise( |Todo, unknown git pack type| ). ENDCASE. ENDMETHOD. METHOD sort_tree. TYPES: BEGIN OF ty_sort, sort TYPE string, node TYPE ty_node, END OF ty_sort. DATA: lt_sort TYPE STANDARD TABLE OF ty_sort WITH DEFAULT KEY. FIELD-SYMBOLS: LIKE LINE OF lt_sort, LIKE LINE OF it_nodes. LOOP AT it_nodes ASSIGNING . APPEND INITIAL LINE TO lt_sort ASSIGNING . IF -chmod = zif_abapgit_definitions=>c_chmod-dir. CONCATENATE -name '/' INTO -sort. ELSE. -sort = -name. ENDIF. -node = . ENDLOOP. * following has to be done, or unpack will fail on server side SORT lt_sort BY sort ASCENDING. LOOP AT lt_sort ASSIGNING . APPEND -node TO rt_nodes. ENDLOOP. ENDMETHOD. METHOD type_and_length. * see http://stefan.saasen.me/articles/git-clone-in-haskell-from-the-bottom-up/#pack_file_objects DATA: lv_type TYPE i, lv_length TYPE i, lv_hex TYPE x LENGTH 1. CASE iv_type. WHEN zif_abapgit_definitions=>c_type-commit. lv_type = 16. WHEN zif_abapgit_definitions=>c_type-tree. lv_type = 32. WHEN zif_abapgit_definitions=>c_type-blob. lv_type = 48. WHEN zif_abapgit_definitions=>c_type-tag. lv_type = 64. WHEN zif_abapgit_definitions=>c_type-ref_d. lv_type = 112. WHEN OTHERS. zcx_abapgit_exception=>raise( |Unexpected object type while encoding pack| ). ENDCASE. lv_length = iv_length. * first byte IF lv_length > 15. lv_hex = 128. ENDIF. lv_hex = lv_hex + lv_type + lv_length MOD 16. rv_xstring = lv_hex. lv_length = lv_length DIV 16. * subsequent bytes WHILE lv_length >= 128. lv_hex = 128 + lv_length MOD 128. CONCATENATE rv_xstring lv_hex INTO rv_xstring IN BYTE MODE. lv_length = lv_length DIV 128. ENDWHILE. * last byte IF lv_length > 0. lv_hex = lv_length. CONCATENATE rv_xstring lv_hex INTO rv_xstring IN BYTE MODE. ENDIF. ENDMETHOD. METHOD zlib_decompress. DATA: ls_data TYPE zcl_abapgit_zlib=>ty_decompress, lv_compressed_len TYPE i, lv_adler32 TYPE zif_abapgit_definitions=>ty_adler32. ls_data = zcl_abapgit_zlib=>decompress( cv_data ). lv_compressed_len = ls_data-compressed_len. cv_decompressed = ls_data-raw. IF lv_compressed_len IS INITIAL. zcx_abapgit_exception=>raise( |Decompression falied :o/| ). ENDIF. cv_data = cv_data+lv_compressed_len. lv_adler32 = zcl_abapgit_hash=>adler32( cv_decompressed ). IF cv_data(4) <> lv_adler32. cv_data = cv_data+1. ENDIF. IF cv_data(4) <> lv_adler32. cv_data = cv_data+1. ENDIF. IF cv_data(4) <> lv_adler32. zcx_abapgit_exception=>raise( |Wrong Adler checksum| ). ENDIF. ENDMETHOD. ENDCLASS. ",7295,False,1504.3915878389116,median "/* This is an example sketch to test the core functionalities of the SIM7000/7070/7500/7600 modules. * Please see the ""LTE_Demo"" sketch which supports many other SIMCom 2G, 3G modules; this sketch * takes up less memory than the LTE_Demo sketch and is therefore suitable for microcontrollers * like the ATmega32u4. * * Author: Timothy Woo (www.botletics.com) * Github: https://github.com/botletics/SIM7000-LTE-Shield * Last Updated: 1/30/2021 * License: GNU GPL v3.0 */ /******* ORIGINAL ADAFRUIT FONA LIBRARY TEXT *******/ /*************************************************** This is an example for our Adafruit FONA Cellular Module Designed specifically to work with the Adafruit FONA ----> http://www.adafruit.com/products/1946 ----> http://www.adafruit.com/products/1963 ----> http://www.adafruit.com/products/2468 ----> http://www.adafruit.com/products/2542 These cellular modules use TTL Serial to communicate, 2 pins are required to interface 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. BSD license, all text above must be included in any redistribution ****************************************************/ #include ""Adafruit_FONA.h"" // Define *one* of the following lines: #define SIMCOM_7000 // #define SIMCOM_7070 // #define SIMCOM_7500 //#define SIMCOM_7600 #if defined(SIMCOM_7000) || defined(SIMCOM_7070) // For botletics SIM7000/7070 shield #define FONA_PWRKEY 6 #define FONA_RST 7 // No RST pin for SIM7070 //#define FONA_DTR 8 // Connect with solder jumper //#define FONA_RI 9 // Need to enable via AT commands #define FONA_TX 10 // Microcontroller RX #define FONA_RX 11 // Microcontroller TX //#define T_ALERT 12 // Connect with solder jumper #elif defined(SIMCOM_7500) || defined(SIMCOM_7600) // For botletics SIM7500 shield #define FONA_PWRKEY 6 #define FONA_RST 7 //#define FONA_DTR 9 // Connect with solder jumper //#define FONA_RI 8 // Need to enable via AT commands #define FONA_TX 11 // Microcontroller RX #define FONA_RX 10 // Microcontroller TX //#define T_ALERT 5 // Connect with solder jumper #endif // this is a large buffer for replies char replybuffer[255]; // We default to using software serial. If you want to use hardware serial // (because softserial isnt supported) comment out the following three lines // and uncomment the HardwareSerial line #include SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); // Use the following line for ESP8266 instead of the line above (comment out the one above) //SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX, false, 256); // TX, RX, inverted logic, buffer size SoftwareSerial *fonaSerial = &fonaSS; // Hardware serial is also possible! //HardwareSerial *fonaSerial = &Serial1; // For ESP32 hardware serial use these lines instead //#include //HardwareSerial fonaSS(1); Adafruit_FONA_LTE fona = Adafruit_FONA_LTE(); uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); uint8_t type; char imei[16] = {0}; // MUST use a 16 character buffer for IMEI! void setup() { // while (!Serial); pinMode(FONA_RST, OUTPUT); digitalWrite(FONA_RST, HIGH); // Default state // Turn on the module by pulsing PWRKEY low for a little bit // This amount of time depends on the specific module that's used fona.powerOn(FONA_PWRKEY); Serial.begin(9600); Serial.println(F(""SIM7XXX Demo"")); // SIM7000 takes about 3s to turn on and SIM7500 takes about 15s // Press Arduino reset button if the module is still turning on and the board doesn't find it. // When the module is on it should communicate right after pressing reset // Software serial: fonaSS.begin(115200); // Default SIM7000 shield baud rate Serial.println(F(""Configuring to 9600 baud"")); fonaSS.println(""AT+IPR=9600""); // Set baud rate delay(100); // Short pause to let the command run fonaSS.begin(9600); if (! fona.begin(fonaSS)) { Serial.println(F(""Couldn't find FONA"")); while (1); // Don't proceed if it couldn't find the device } // Hardware serial: /* fonaSerial->begin(115200); // Default SIM7000 baud rate if (! fona.begin(*fonaSerial)) { DEBUG_PRINTLN(F(""Couldn't find SIM7000"")); } */ // The commented block of code below is an alternative that will find the module at 115200 // Then switch it to 9600 without having to wait for the module to turn on and manually // press the reset button in order to establish communication. However, once the baud is set // this method will be much slower. /* fonaSerial->begin(115200); // Default LTE shield baud rate fona.begin(*fonaSerial); // Don't use if statement because an OK reply could be sent incorrectly at 115200 baud Serial.println(F(""Configuring to 9600 baud"")); fona.setBaudrate(9600); // Set to 9600 baud fonaSerial->begin(9600); if (!fona.begin(*fonaSerial)) { Serial.println(F(""Couldn't find modem"")); while(1); // Don't proceed if it couldn't find the device } */ type = fona.type(); Serial.println(F(""FONA is OK"")); Serial.print(F(""Found "")); switch (type) { case SIM7000: Serial.println(F(""SIM7000"")); break; case SIM7070: Serial.println(F(""SIM7070"")); break; case SIM7500: Serial.println(F(""SIM7500"")); break; case SIM7600: Serial.println(F(""SIM7600"")); break; default: Serial.println(F(""???"")); break; } // Print module IMEI number. uint8_t imeiLen = fona.getIMEI(imei); if (imeiLen > 0) { Serial.print(""Module IMEI: ""); Serial.println(imei); } // Set modem to full functionality fona.setFunctionality(1); // AT+CFUN=1 // Configure a GPRS APN, username, and password. // You might need to do this to access your network's GPRS/data // network. Contact your provider for the exact APN, username, // and password values. Username and password are optional and // can be removed, but APN is required. //fona.setNetworkSettings(F(""your APN""), F(""your username""), F(""your password"")); //fona.setNetworkSettings(F(""m2m.com.attz"")); // For AT&T IoT SIM card //fona.setNetworkSettings(F(""telstra.internet"")); // For Telstra (Australia) SIM card - CAT-M1 (Band 28) fona.setNetworkSettings(F(""hologram"")); // For Hologram SIM card // Optionally configure HTTP gets to follow redirects over SSL. // Default is not to follow SSL redirects, however if you uncomment // the following line then redirects over SSL will be followed. //fona.setHTTPSRedirect(true); /* // Other examples of some things you can set: fona.setPreferredMode(38); // Use LTE only, not 2G fona.setPreferredLTEMode(1); // Use LTE CAT-M only, not NB-IoT fona.setOperatingBand(""CAT-M"", 12); // AT&T uses band 12 // fona.setOperatingBand(""CAT-M"", 13); // Verizon uses band 13 fona.enableRTC(true); fona.enableSleepMode(true); fona.set_eDRX(1, 4, ""0010""); fona.enablePSM(true); // Set the network status LED blinking pattern while connected to a network (see AT+SLEDS command) fona.setNetLED(true, 2, 64, 3000); // on/off, mode, timer_on, timer_off fona.setNetLED(false); // Disable network status LED */ printMenu(); } void printMenu(void) { Serial.println(F(""-------------------------------------"")); Serial.println(F(""[?] Print this menu"")); Serial.println(F(""[a] Read the ADC, 0V-VBAT for SIM7000"")); Serial.println(F(""[b] Read supply voltage"")); // Will also give battery % charged for LiPo battery Serial.println(F(""[C] Read the SIM CCID"")); Serial.println(F(""[U] Unlock SIM with PIN code"")); Serial.println(F(""[i] Read signal strength (RSSI)"")); Serial.println(F(""[n] Get network status"")); #if defined(SIMCOM_7500) || defined(SIMCOM_7600) // Audio/Volume Serial.println(F(""[v] Set audio Volume"")); Serial.println(F(""[V] Get volume"")); Serial.println(F(""[H] Set headphone audio"")); Serial.println(F(""[e] Set external audio"")); #endif // Phone Serial.println(F(""[c] Make phone Call"")); Serial.println(F(""[A] Get call status"")); Serial.println(F(""[h] Hang up phone"")); Serial.println(F(""[p] Pick up phone"")); // SMS Serial.println(F(""[N] Number of SMS's"")); Serial.println(F(""[r] Read SMS #"")); Serial.println(F(""[R] Read all SMS"")); Serial.println(F(""[d] Delete SMS #"")); Serial.println(F(""[s] Send SMS"")); // Time Serial.println(F(""[y] Enable local time stamp"")); Serial.println(F(""[Y] Enable NTP time sync"")); // Need to use ""G"" command first! Serial.println(F(""[t] Get network time"")); // Works just by being connected to network // Data Connection Serial.println(F(""[G] Enable GPRS"")); Serial.println(F(""[g] Disable GPRS"")); // Serial.println(F(""[w] Read webpage (GPRS)"")); // Serial.println(F(""[W] Post to website (GPRS)"")); Serial.println(F(""[1] Get connection info"")); // See what connection type and band you're on! // The following option below posts dummy data to dweet.io for demonstration purposes. See the // IoT_example sketch for an actual application of this function! #if defined(SIMCOM_7000) || defined(SIMCOM_7070) Serial.println(F(""[2] Post to dweet.io - LTE CAT-M / NB-IoT"")); // SIM7000/7070 #elif defined(SIMCOM_7500) || defined(SIMCOM_7600) Serial.println(F(""[3] Post to dweet.io - 4G LTE (SIM7X00)"")); // SIM7500/7600 #endif // GPS Serial.println(F(""[O] Turn GPS on)"")); Serial.println(F(""[o] Turn GPS off"")); Serial.println(F(""[L] Query GPS location"")); // Serial.println(F(""[S] Create serial passthru tunnel"")); Serial.println(F(""-------------------------------------"")); Serial.println(F("""")); } void loop() { Serial.print(F(""FONA> "")); while (! Serial.available() ) { if (fona.available()) { Serial.write(fona.read()); } } char command = Serial.read(); Serial.println(command); switch (command) { case '?': { printMenu(); break; } case 'a': { // read the ADC uint16_t adc; if (! fona.getADCVoltage(&adc)) { Serial.println(F(""Failed to read ADC"")); } else { Serial.print(F(""ADC = "")); Serial.print(adc); Serial.println(F("" mV"")); } break; } case 'b': { // Read the battery voltage and percentage uint16_t vbat; if (! fona.getBattVoltage(&vbat)) { Serial.println(F(""Failed to read Batt"")); } else { Serial.print(F(""VBat = "")); Serial.print(vbat); Serial.println(F("" mV"")); } if ( type != SIM7500 ) { if (! fona.getBattPercent(&vbat)) { Serial.println(F(""Failed to read Batt"")); } else { Serial.print(F(""VPct = "")); Serial.print(vbat); Serial.println(F(""%"")); } } break; } case 'U': { // Unlock the SIM with a PIN code char PIN[5]; flushSerial(); Serial.println(F(""Enter 4-digit PIN"")); readline(PIN, 3); Serial.println(PIN); Serial.print(F(""Unlocking SIM card: "")); if (! fona.unlockSIM(PIN)) { Serial.println(F(""Failed"")); } else { Serial.println(F(""OK!"")); } break; } case 'C': { // read the CCID fona.getSIMCCID(replybuffer); // make sure replybuffer is at least 21 bytes! Serial.print(F(""SIM CCID = "")); Serial.println(replybuffer); break; } case 'i': { // read the RSSI uint8_t n = fona.getRSSI(); int8_t r; Serial.print(F(""RSSI = "")); Serial.print(n); Serial.print("": ""); if (n == 0) r = -115; if (n == 1) r = -111; if (n == 31) r = -52; if ((n >= 2) && (n <= 30)) { r = map(n, 2, 30, -110, -54); } Serial.print(r); Serial.println(F("" dBm"")); break; } case 'n': { // read the network/cellular status uint8_t n = fona.getNetworkStatus(); Serial.print(F(""Network status "")); Serial.print(n); Serial.print(F("": "")); if (n == 0) Serial.println(F(""Not registered"")); if (n == 1) Serial.println(F(""Registered (home)"")); if (n == 2) Serial.println(F(""Not registered (searching)"")); if (n == 3) Serial.println(F(""Denied"")); if (n == 4) Serial.println(F(""Unknown"")); if (n == 5) Serial.println(F(""Registered roaming"")); break; } /*** Audio ***/ #if defined(SIMCOM_7500) || defined(SIMCOM_7600) case 'v': { // set volume flushSerial(); if ( (type == SIM5320A) || (type == SIM5320E) ) { Serial.print(F(""Set Vol [0-8] "")); } else if ( type == SIM7500 ) { Serial.print(F(""Set Vol [0-5] "")); } else { Serial.print(F(""Set Vol % [0-100] "")); } uint8_t vol = readnumber(); Serial.println(); if (! fona.setVolume(vol)) { Serial.println(F(""Failed"")); } else { Serial.println(F(""OK!"")); } break; } case 'V': { uint8_t v = fona.getVolume(); Serial.print(v); if ( (type == SIM5320A) || (type == SIM5320E) ) { Serial.println("" / 8""); } else { Serial.println(""%""); } break; } case 'H': { // Set Headphone output if (! fona.setAudio(FONA_HEADSETAUDIO)) { Serial.println(F(""Failed"")); } else { Serial.println(F(""OK!"")); } fona.setMicVolume(FONA_HEADSETAUDIO, 15); break; } case 'e': { // Set External output if (! fona.setAudio(FONA_EXTAUDIO)) { Serial.println(F(""Failed"")); } else { Serial.println(F(""OK!"")); } fona.setMicVolume(FONA_EXTAUDIO, 10); break; } /*** Call ***/ case 'c': { // call a phone! char number[30]; flushSerial(); Serial.print(F(""Call #"")); readline(number, 30); Serial.println(); Serial.print(F(""Calling "")); Serial.println(number); if (!fona.callPhone(number)) { Serial.println(F(""Failed"")); } else { Serial.println(F(""Sent!"")); } break; } case 'A': { // get call status int8_t callstat = fona.getCallStatus(); switch (callstat) { case 0: Serial.println(F(""Ready"")); break; case 1: Serial.println(F(""Could not get status"")); break; case 3: Serial.println(F(""Ringing (incoming)"")); break; case 4: Serial.println(F(""Ringing/in progress (outgoing)"")); break; default: Serial.println(F(""Unknown"")); break; } break; } case 'h': { // hang up! if (! fona.hangUp()) { Serial.println(F(""Failed"")); } else { Serial.println(F(""OK!"")); } break; } case 'p': { // pick up! if (! fona.pickUp()) { Serial.println(F(""Failed"")); } else { Serial.println(F(""OK!"")); } break; } #endif /*** SMS ***/ case 'N': { // read the number of SMS's! int8_t smsnum = fona.getNumSMS(); if (smsnum < 0) { Serial.println(F(""Could not read # SMS"")); } else { Serial.print(smsnum); Serial.println(F("" SMS's on SIM card!"")); } break; } case 'r': { // read an SMS flushSerial(); Serial.print(F(""Read #"")); uint8_t smsn = readnumber(); Serial.print(F(""\\n\\rReading SMS #"")); Serial.println(smsn); // Retrieve SMS sender address/phone number. if (! fona.getSMSSender(smsn, replybuffer, 250)) { Serial.println(""Failed!""); break; } Serial.print(F(""FROM: "")); Serial.println(replybuffer); // Retrieve SMS value. uint16_t smslen; if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! Serial.println(""Failed!""); break; } Serial.print(F(""***** SMS #"")); Serial.print(smsn); Serial.print("" (""); Serial.print(smslen); Serial.println(F("") bytes *****"")); Serial.println(replybuffer); Serial.println(F(""*****"")); break; } case 'R': { // read all SMS int8_t smsnum = fona.getNumSMS(); uint16_t smslen; int8_t smsn; if ( (type == SIM5320A) || (type == SIM5320E) ) { smsn = 0; // zero indexed smsnum--; } else { smsn = 1; // 1 indexed } for ( ; smsn <= smsnum; smsn++) { Serial.print(F(""\\n\\rReading SMS #"")); Serial.println(smsn); if (!fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len! Serial.println(F(""Failed!"")); break; } // if the length is zero, its a special case where the index number is higher // so increase the max we'll look at! if (smslen == 0) { Serial.println(F(""[empty slot]"")); smsnum++; continue; } Serial.print(F(""***** SMS #"")); Serial.print(smsn); Serial.print("" (""); Serial.print(smslen); Serial.println(F("") bytes *****"")); Serial.println(replybuffer); Serial.println(F(""*****"")); } break; } case 'd': { // delete an SMS flushSerial(); Serial.print(F(""Delete #"")); uint8_t smsn = readnumber(); Serial.print(F(""\\n\\rDeleting SMS #"")); Serial.println(smsn); if (fona.deleteSMS(smsn)) { Serial.println(F(""OK!"")); } else { Serial.println(F(""Couldn't delete"")); } break; } case 's': { // send an SMS! char sendto[21], message[141]; flushSerial(); Serial.print(F(""Send to #"")); readline(sendto, 20); Serial.println(sendto); Serial.print(F(""Type out one-line message (140 char): "")); readline(message, 140); Serial.println(message); if (!fona.sendSMS(sendto, message)) { Serial.println(F(""Failed"")); } else { Serial.println(F(""Sent!"")); } break; } /*** Time ***/ case 'y': { // enable network time sync if (!fona.enableRTC(true)) Serial.println(F(""Failed to enable"")); break; } case 'Y': { // enable NTP time sync if (!fona.enableNTPTimeSync(true, F(""pool.ntp.org""))) Serial.println(F(""Failed to enable"")); break; } case 't': { // read the time char buffer[23]; fona.getTime(buffer, 23); // make sure replybuffer is at least 23 bytes! Serial.print(F(""Time = "")); Serial.println(buffer); break; } /******* GPS *******/ case 'o': { // turn GPS off if (!fona.enableGPS(false)) Serial.println(F(""Failed to turn off"")); break; } case 'O': { // turn GPS on if (!fona.enableGPS(true)) Serial.println(F(""Failed to turn on"")); break; } case 'L': { /* // Uncomment this block if all you want to see is the AT command response // check for GPS location char gpsdata[120]; fona.getGPS(0, gpsdata, 120); if (type == SIM808_V1) Serial.println(F(""Reply in format: mode,longitude,latitude,altitude,utctime(yyyymmddHHMMSS),ttff,satellites,speed,course"")); else if ( (type == SIM5320A) || (type == SIM5320E) || (type == SIM7500) ) Serial.println(F(""Reply in format: [],[],[],[],[],[(yyyymmddHHMMSS)],[],[],[]"")); else Serial.println(F(""Reply in format: mode,fixstatus,utctime(yyyymmddHHMMSS),latitude,longitude,altitude,speed,course,fixmode,reserved1,HDOP,PDOP,VDOP,reserved2,view_satellites,used_satellites,reserved3,C/N0max,HPA,VPA"")); Serial.println(gpsdata); break; */ float latitude, longitude, speed_kph, heading, altitude; // Uncomment the definitions below and the line immediately below the definitions if you want // to parse UTC time data as well, or use the line below it if you don't care // float second; // uint16_t year; // uint8_t month, day, hour, minute; // if (fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude, &year, &month, &day, &hour, &minute, &second)) { if (fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude)) { // Use this line instead if you don't want UTC time Serial.println(F(""---------------------"")); Serial.print(F(""Latitude: "")); Serial.println(latitude, 6); Serial.print(F(""Longitude: "")); Serial.println(longitude, 6); Serial.print(F(""Speed: "")); Serial.println(speed_kph); Serial.print(F(""Heading: "")); Serial.println(heading); Serial.print(F(""Altitude: "")); Serial.println(altitude); // Comment out the stuff below if you don't care about UTC time /* Serial.print(F(""Year: "")); Serial.println(year); Serial.print(F(""Month: "")); Serial.println(month); Serial.print(F(""Day: "")); Serial.println(day); Serial.print(F(""Hour: "")); Serial.println(hour); Serial.print(F(""Minute: "")); Serial.println(minute); Serial.print(F(""Second: "")); Serial.println(second); */ Serial.println(F(""---------------------"")); } break; } /******* GPRS *******/ case 'g': { // turn GPRS off if (!fona.enableGPRS(false)) Serial.println(F(""Failed to turn off"")); break; } case 'G': { // turn GPRS off first for SIM7500/7600 #if defined(SIMCOM_7500) || defined(SIMCOM_7600) fona.enableGPRS(false); #endif // turn GPRS on if (!fona.enableGPRS(true)) Serial.println(F(""Failed to turn on"")); break; } /* case 'w': { // read website URL uint16_t statuscode; int16_t length; char url[80]; flushSerial(); Serial.println(F(""NOTE: in beta! Use small webpages to read!"")); Serial.println(F(""URL to read (e.g. www.adafruit.com/testwifi/index.html):"")); Serial.print(F(""http://"")); readline(url, 79); Serial.println(url); Serial.println(F(""****"")); if (!fona.HTTP_GET_start(url, &statuscode, (uint16_t *)&length)) { Serial.println(""Failed!""); break; } while (length > 0) { while (fona.available()) { char c = fona.read(); // Serial.write is too slow, we'll write directly to Serial register! #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) loop_until_bit_is_set(UCSR0A, UDRE0); // Wait until data register empty UDR0 = c; #else Serial.write(c); #endif length--; if (! length) break; } } Serial.println(F(""\\n****"")); fona.HTTP_GET_end(); break; } case 'W': { // Post data to website uint16_t statuscode; int16_t length; char url[80]; char data[80]; flushSerial(); Serial.println(F(""NOTE: in beta! Use simple websites to post!"")); Serial.println(F(""URL to post (e.g. httpbin.org/post):"")); Serial.print(F(""http://"")); readline(url, 79); Serial.println(url); Serial.println(F(""Data to post (e.g. \\""foo\\"" or \\""{\\""simple\\"":\\""json\\""}\\""):"")); readline(data, 79); Serial.println(data); Serial.println(F(""****"")); if (!fona.HTTP_POST_start(url, F(""text/plain""), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) { Serial.println(""Failed!""); break; } while (length > 0) { while (fona.available()) { char c = fona.read(); #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) loop_until_bit_is_set(UCSR0A, UDRE0); // Wait until data register empty UDR0 = c; #else Serial.write(c); #endif length--; if (! length) break; } } Serial.println(F(""\\n****"")); fona.HTTP_POST_end(); break; } */ case '1': { // Get connection type, cellular band, carrier name, etc. fona.getNetworkInfo(); break; } #if defined(SIMCOM_2G) || defined(SIMCOM_7000) || defined(SIMCOM_7070) case '2': { // Post data to website via 2G or LTE CAT-M/NB-IoT float temperature = analogRead(A0)*1.23; // Change this to suit your needs uint16_t battLevel; if (! fona.getBattVoltage(&battLevel)) battLevel = 3800; // Use dummy voltage if can't read // Create char buffers for the floating point numbers for sprintf // Make sure these buffers are long enough for your request URL char URL[150]; char body[100]; char tempBuff[16]; // Format the floating point numbers as needed dtostrf(temperature, 1, 2, tempBuff); // float_val, min_width, digits_after_decimal, char_buffer #ifdef SIMCOM_7070 // Add headers as needed // fona.HTTP_addHeader(""User-Agent"", ""SIM7070"", 7); // fona.HTTP_addHeader(""Cache-control"", ""no-cache"", 8); // fona.HTTP_addHeader(""Connection"", ""keep-alive"", 10); // fona.HTTP_addHeader(""Accept"", ""*/*, 3); // Connect to server // If https:// is used, #define SSL_FONA 1 in Adafruit_FONA.h if (! fona.HTTP_connect(""http://dweet.io"")) { Serial.println(F(""Failed to connect to server..."")); break; } // GET request // Format URI with GET request query string sprintf(URL, ""/dweet/for/%s?temp=%s&batt=%i"", imei, tempBuff, battLevel); fona.HTTP_GET(URL); // POST request /* sprintf(URL, ""/dweet/for/%s"", imei); // Format URI // Format JSON body for POST request // Example JSON body: ""{\\""temp\\"":\\""22.3\\"",\\""batt\\"":\\""3800\\""}"" sprintf(body, ""{\\""temp\\"":\\""%s\\"",\\""batt\\"":\\""%i\\""}"", tempBuff, battLevel); // construct JSON body fona.HTTP_addHeader(""Content-Type"", ""application/json"", 16); fona.HTTP_POST(URL, body, strlen(body)); */ #else // Construct the appropriate URL's and body, depending on request type // Use IMEI as device ID for this example // GET request sprintf(URL, ""dweet.io/dweet/for/%s?temp=%s&batt=%i"", imei, tempBuff, battLevel); // No need to specify http:// or https:// // sprintf(URL, ""http://dweet.io/dweet/for/%s?temp=%s&batt=%i"", imei, tempBuff, battLevel); // But this works too if (!fona.postData(""GET"", URL)) Serial.println(F(""Failed to complete HTTP GET..."")); // POST request /* sprintf(URL, ""http://dweet.io/dweet/for/%s"", imei); sprintf(body, ""{\\""temp\\"":%s,\\""batt\\"":%i}"", tempBuff, battLevel); if (!fona.postData(""POST"", URL, body)) // Can also add authorization token parameter! Serial.println(F(""Failed to complete HTTP POST..."")); */ #endif break; } #endif #if defined(SIMCOM_7500) || defined(SIMCOM_7600) case '3': { // Post data to website via 3G or 4G LTE float temperature = analogRead(A0)*1.23; // Change this to suit your needs uint16_t battLevel; if (! fona.getBattVoltage(&battLevel)) battLevel = 3800; // Use dummy voltage if can't read // Create char buffers for the floating point numbers for sprintf // Make sure these buffers are long enough for your request URL char URL[150]; char tempBuff[12]; // Format the floating point numbers as needed dtostrf(temperature, 1, 2, tempBuff); // float_val, min_width, digits_after_decimal, char_buffer // Construct the appropriate URL's and body, depending on request type // Use IMEI as device ID for this example // GET request sprintf(URL, ""GET /dweet/for/%s?temp=%s&batt=%i HTTP/1.1\\r\\nHost: dweet.io\\r\\nContent-Length: 0\\r\\n\\r\\n"", imei, tempBuff, battLevel); if (!fona.postData(""www.dweet.io"", 443, ""HTTPS"", URL)) // Server, port, connection type, URL Serial.println(F(""Failed to complete HTTP/HTTPS request..."")); break; } #endif /*****************************************/ case 'S': { Serial.println(F(""Creating SERIAL TUBE"")); while (1) { while (Serial.available()) { delay(1); fona.write(Serial.read()); } if (fona.available()) { Serial.write(fona.read()); } } break; } default: { Serial.println(F(""Unknown command"")); printMenu(); break; } } // flush input flushSerial(); while (fona.available()) { Serial.write(fona.read()); } } void flushSerial() { while (Serial.available()) Serial.read(); } char readBlocking() { while (!Serial.available()); return Serial.read(); } uint16_t readnumber() { uint16_t x = 0; char c; while (! isdigit(c = readBlocking())) { //Serial.print(c); } Serial.print(c); x = c - '0'; while (isdigit(c = readBlocking())) { Serial.print(c); x *= 10; x += c - '0'; } return x; } uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) { uint16_t buffidx = 0; boolean timeoutvalid = true; if (timeout == 0) timeoutvalid = false; while (true) { if (buffidx > maxbuff) { //Serial.println(F(""SPACE"")); break; } while (Serial.available()) { char c = Serial.read(); //Serial.print(c, HEX); Serial.print(""#""); Serial.println(c); if (c == '\\r') continue; if (c == 0xA) { if (buffidx == 0) // the first 0x0A is ignored continue; timeout = 0; // the second 0x0A is the end of the line timeoutvalid = true; break; } buff[buffidx] = c; buffidx++; } if (timeoutvalid && timeout == 0) { //Serial.println(F(""TIMEOUT"")); break; } delay(1); } buff[buffidx] = 0; // null term return buffidx; }",8325,False,1414.4967590812564,median "#include #include #include ""Adafruit_LEDBackpack.h"" #include ""Adafruit_GFX.h"" #include ""Clock16x16mapping.h"" RTC_DS1307 RTC; Adafruit_8x16matrix matrix = Adafruit_8x16matrix(); Adafruit_8x16matrix matrix2 = Adafruit_8x16matrix(); uint16_t active[16]; //Holds active matrix uint16_t last[16]; //Holds previous matrix unsigned int curHours; unsigned int hours = 99; unsigned int curMins; unsigned int mins = 99; int aniChoice = 0; void setup() { //Serial.begin(57600); RTC.begin(); delay(100); matrix.begin(0x71); // pass in the address matrix2.begin(0x70); // pass in the address delay(100); matrix.clear(); matrix2.clear(); matrix.writeDisplay(); matrix2.writeDisplay(); matrix2.drawPixel(8, 15, LED_ON); matrix2.writeDisplay(); matrix2.drawPixel(8, 15, LED_OFF); matrix2.writeDisplay(); matrix2.drawPixel(8, 15, LED_ON); matrix2.writeDisplay(); matrix2.drawPixel(8, 15, LED_OFF); matrix2.writeDisplay(); pinMode(5, INPUT); pinMode(6, INPUT); pinMode(7, INPUT); if(!RTC.isrunning()) { RTC.adjust(DateTime(2015,4,18,0,0,0)); } DateTime now = RTC.now(); hours = now.hour(); mins = now.minute(); doAnimation(); delay(100); } unsigned long currentMillis = millis(); unsigned long previousMillis = 0; unsigned long resetMillis = 0; unsigned long pressCheckA0 = 0; unsigned long pressCheckA1 = 0; unsigned long pressCheckA2 = 0; bool A0pressed = false; bool A1pressed = false; bool A2pressed = false; bool A0read = false; bool A1read = false; bool A2read = false; void loop () { if((unsigned long)(currentMillis - previousMillis) >= 5000) { //Serial.print(hours); //Serial.print(':'); //Serial.println(mins); checkTime(); previousMillis = currentMillis; } if( digitalRead(5) == HIGH && A0pressed == false) { A0pressed = true; pressCheckA0 = currentMillis; A0read = false; } if( digitalRead(6) == HIGH && A1pressed == false) { A1pressed = true; pressCheckA1 = currentMillis; A1read = false; } if( digitalRead(7) == HIGH && A2pressed == false) { A2pressed = true; pressCheckA2 = currentMillis; A2read = false; } if( A0pressed == true && A0read == false && (unsigned long)(currentMillis - pressCheckA0) >= 50) { DateTime now = RTC.now(); int newHour = now.hour() + 1; if (newHour > 23) { newHour = 0; } RTC.adjust(DateTime(now.year(),now.month(),now.day(),newHour,now.minute(),now.second())); hours = newHour; mins = now.minute(); curHours = newHour; curMins = now.minute(); wipe(); assemble(); drawDisplay(); A0read = true; } if( A1pressed == true && A1read == false && (unsigned long)(currentMillis - pressCheckA1) >= 50) { DateTime now = RTC.now(); int newMinute = now.minute() + 1; if (newMinute > 59) { newMinute = 0; } RTC.adjust(DateTime(now.year(),now.month(),now.day(),now.hour(),newMinute,now.second())); hours = now.hour(); mins = newMinute; curHours = now.hour(); curMins = newMinute; wipe(); assemble(); drawDisplay(); A1read = true; } if( A2pressed == true && A2read == false && (unsigned long)(currentMillis - pressCheckA2) >= 50) { aniChoice++; sampleAnimation(); A2read = true; } if( digitalRead(5) == LOW) { A0pressed = false; A0read = false; } if( digitalRead(6) == LOW) { A1pressed = false; A1read = false; } if( digitalRead(7) == LOW) { A2pressed = false; A2read = false; } wipe(); assemble(); delay(10); currentMillis = millis(); } void checkTime () { DateTime now = RTC.now(); curHours = now.hour(); curMins = now.minute(); if (curHours != hours || curMins != mins) { hours = curHours; mins = curMins; //software_Reset(); doAnimation(); } } void assemble() { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(it_is[i])); } //flag midnight if (hours == 0 && mins == 0) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(midnight[i])); } } else //flag noon if (hours == 12 && mins == 0) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(noon[i])); } } else { //If it's between 12:01 and 5:59 in the PM, flag in the afternoon if (hours > 12 && hours < 18 || ( hours == 12 && mins > 0)) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(in_the_afternoon[i])); } } else //If it's between 6 and 8:59 in the PM, flag in the evening if (hours > 17 && hours < 21) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(in_the_evening[i])); } } else //If it's between 9 and midnight in the PM, flag at night if (hours > 20) { for( int i = 0; i < 16; i++ ) { if(hours == 23 && mins == 45) {} else { active[i] = active[i] | pgm_read_word(&(at_night[i])); } } } else //If it's between 12:01 and 11:59 in the AM, flag in the morning if ( ((hours > 0 && hours < 12) || (hours == 0 && mins > 0)) ) { if(hours == 11 && mins == 45) { } else { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(in_the_morning[i])); } } } if ( hours == 12 && mins != 0) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h1[i])); } else { active[i] = active[i] | pgm_read_word(&(h12[i])); } } } else if ( hours == 0 && mins != 0) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h1[i])); } else { active[i] = active[i] | pgm_read_word(&(h12[i])); } } } else if ( hours == 1 || hours == 13) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h2[i])); } else { active[i] = active[i] | pgm_read_word(&(h1[i])); } } } else if ( hours == 2 || hours == 14) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h3[i])); } else { active[i] = active[i] | pgm_read_word(&(h2[i])); } } } else if ( hours == 3 || hours == 15) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h4[i])); } else { active[i] = active[i] | pgm_read_word(&(h3[i])); } } } else if ( hours == 4 || hours == 16) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h5[i])); } else { active[i] = active[i] | pgm_read_word(&(h4[i])); } } } else if ( hours == 1) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h2[i])); } else { active[i] = active[i] | pgm_read_word(&(h1[i])); } } } else if ( hours == 5 || hours == 17) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h6[i])); } else { active[i] = active[i] | pgm_read_word(&(h5[i])); } } } else if ( hours == 6 || hours == 18) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h7[i])); } else { active[i] = active[i] | pgm_read_word(&(h6[i])); } } } else if ( hours == 7 || hours == 19) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h8[i])); } else { active[i] = active[i] | pgm_read_word(&(h7[i])); } } } else if ( hours == 8 || hours == 20) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h9[i])); } else { active[i] = active[i] | pgm_read_word(&(h8[i])); } } } else if ( hours == 9 || hours == 21) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h10[i])); } else { active[i] = active[i] | pgm_read_word(&(h9[i])); } } } else if ( hours == 10 || hours == 22) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(h11[i])); } else { active[i] = active[i] | pgm_read_word(&(h10[i])); } } } else if ( hours == 11) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(noon[i])); } else { active[i] = active[i] | pgm_read_word(&(h11[i])); } } } else if ( hours == 23) { for( int i = 0; i < 16; i++ ) { if (mins == 45) { active[i] = active[i] | pgm_read_word(&(midnight[i])); } else { active[i] = active[i] | pgm_read_word(&(h11[i])); } } } //Minute handling if ( mins == 15) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m15[i])); } } else if ( mins == 45) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m45[i])); } } else if ( mins == 30) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(half_past[i])); } } else if ( mins == 0 && (hours != 12 && hours != 0)) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(o_clock[i])); } } else { if ( mins < 10 && mins > 0) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(o[i])); } } if ( mins == 1 || mins == 21 || mins == 31 || mins == 41 || mins == 51) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m1[i])); } } else if ( mins == 2 || mins == 22 || mins == 32 || mins == 42 || mins == 52) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m2[i])); } } else if ( mins == 3 || mins == 23 || mins == 33 || mins == 43 || mins == 53) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m3[i])); } } else if ( mins == 4 || mins == 24 || mins == 34 || mins == 44 || mins == 54) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m4[i])); } } else if ( mins == 5 || mins == 25 || mins == 35 || mins == 45 || mins == 55) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m5[i])); } } else if ( mins == 6 || mins == 26 || mins == 36 || mins == 46 || mins == 56) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m6[i])); } } else if ( mins == 7 || mins == 27 || mins == 37 || mins == 47 || mins == 57) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m7[i])); } } else if ( mins == 8 || mins == 28 || mins == 38 || mins == 48 || mins == 58) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m8[i])); } } else if ( mins == 9 || mins == 29 || mins == 39 || mins == 49 || mins == 59) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m9[i])); } } else if ( mins == 10 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m10[i])); } } else if ( mins == 11 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m11[i])); } } else if ( mins == 12 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m12[i])); } } else if ( mins == 13 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m13[i])); } } else if ( mins == 14 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m14[i])); } } else if ( mins == 16 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m16[i])); } } else if ( mins == 17 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m17[i])); } } else if ( mins == 18 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m18[i])); } } else if ( mins == 19 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m19[i])); } } if ( mins >= 20 && mins < 30 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m20[i])); } } if ( mins >= 30 && mins < 40 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m30[i])); } } if ( mins >= 40 && mins < 50 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m40[i])); } } if ( mins >= 50 && mins < 60 ) { for( int i = 0; i < 16; i++ ) { active[i] = active[i] | pgm_read_word(&(m50[i])); } } } //end quarter hour if-else } //end noon-midnight if-else } void wipe () { for( int i = 0; i < 16; i++ ) { active[i] = 0b0000000000000000; } } //Animation functions //No animation void drawDisplay() { matrix.clear(); matrix2.clear(); wipe(); assemble(); for( int y = 16; y >= 0; y-- ) { for( int x = 0; x < 16; x++) { if(bitRead( active[15 - y] , 15 - x)) { if( y < 8) { matrix.drawPixel(y, x, LED_ON); } else { matrix2.drawPixel(y - 8, x, LED_ON); } } else { } } } matrix.writeDisplay(); matrix2.writeDisplay(); } //Fade out and back in void fadeOut() { for(int b = 16; b >= 0; b--) { matrix.setBrightness(b); matrix2.setBrightness(b); delay(50); } wipe(); drawDisplay(); delay(250); assemble(); drawDisplay(); for(int b = 0; b < 16 ; b++) { matrix.setBrightness(b); matrix2.setBrightness(b); delay(50); } } //Random dissolve to all on, then fade back to time void whiteOut () { int randomizer[256] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256 }; bubbleUnsort (randomizer, 256); for( int i = 0; i < 256; i++) { int y = randomizer[i ]/16; int x = randomizer[i ]%16; if( y < 8) { matrix.drawPixel(y, x, LED_ON); } else { matrix2.drawPixel(y - 8, x, LED_ON); } matrix.writeDisplay(); matrix2.writeDisplay(); } wipe(); bubbleUnsort (randomizer, 256); assemble(); for( int i = 0; i < 256; i++) { int y = randomizer[i]/16; int x = randomizer[i]%16; if(bitRead( active[15 - y] , 15 - x)) { if( y < 8) { matrix.drawPixel(y, x, LED_ON); } else { matrix2.drawPixel(y - 8, x, LED_ON); } } else { if( y < 8) { matrix.drawPixel(y, x, LED_OFF); } else { matrix2.drawPixel(y - 8, x, LED_OFF); } } matrix.writeDisplay(); matrix2.writeDisplay(); } } //Horizontal sweep. void sweep() { for( int x = 0; x < 16; x++) { last[x] = active[x]; } wipe(); assemble(); for( int x = 0; x < 16; x++) { for( int y = 16; y >= 0; y-- ) { if(!bitRead( active[15 - y] , 15 - x)) { if( y < 8) { matrix.drawPixel(y, x, LED_OFF); } else { matrix2.drawPixel(y - 8, x, LED_OFF); } } matrix.writeDisplay(); matrix2.writeDisplay(); } } for( int x = 0; x < 16; x++) { for( int y = 16; y >= 0; y-- ) { if(bitRead( active[15 - y] , 15 - x)) { if( y < 8) { matrix.drawPixel(y, x, LED_ON); } else { matrix2.drawPixel(y - 8, x, LED_ON); } } matrix.writeDisplay(); matrix2.writeDisplay(); } } } //Matrixy. void matrixy() { wipe(); assemble(); int cols[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; bubbleUnsort( cols, 16); for(int r = 0; r < 2; r++) { for( int i = 0; i < 16; i++) { int x = cols[i]; int x2 = cols[i+1]; int x3 = cols[i+2]; int x4 = cols[i+3]; for( int y = 16; y >= 0; y-- ) { if( y < 8) { matrix.drawPixel(y, x, LED_ON); matrix.drawPixel(y, x2, LED_ON); matrix.drawPixel(y, x3, LED_ON); matrix.drawPixel(y, x4, LED_ON); } else { matrix2.drawPixel(y - 8, x, LED_ON); matrix2.drawPixel(y - 8, x2, LED_ON); matrix2.drawPixel(y - 8, x3, LED_ON); matrix2.drawPixel(y - 8, x4, LED_ON); } matrix.writeDisplay(); matrix2.writeDisplay(); delay(10); if(!bitRead( active[15 - y] , 15 - x)) { if( y < 8) { matrix.drawPixel(y, x, LED_OFF); } else { matrix2.drawPixel(y - 8, x, LED_OFF); } } if(!bitRead( active[15 - y] , 15 - x2)) { if( y < 8) { matrix.drawPixel(y, x2, LED_OFF); } else { matrix2.drawPixel(y - 8, x2, LED_OFF); } } if(!bitRead( active[15 - y] , 15 - x3)) { if( y < 8) { matrix.drawPixel(y, x3, LED_OFF); } else { matrix2.drawPixel(y - 8, x3, LED_OFF); } } if(!bitRead( active[15 - y] , 15 - x4)) { if( y < 8) { matrix.drawPixel(y, x4, LED_OFF); } else { matrix2.drawPixel(y - 8, x4, LED_OFF); } } matrix.writeDisplay(); matrix2.writeDisplay(); } } } } void sampleAnimation () { if( aniChoice > 5) { aniChoice = 0; } if (aniChoice == 0 ) { matrix.clear(); matrix2.clear(); matrix.writeDisplay(); matrix2.writeDisplay(); delay(250); drawDisplay(); delay(250); matrix.clear(); matrix2.clear(); matrix.writeDisplay(); matrix2.writeDisplay(); delay(250); drawDisplay(); } if (aniChoice == 1 ) { fadeOut(); } if (aniChoice == 2 ) { whiteOut(); } if (aniChoice == 3 ) { matrix.clear(); matrix2.clear(); matrix.writeDisplay(); matrix2.writeDisplay(); sweep(); } if (aniChoice == 4 ) { matrixy(); } if (aniChoice == 5 ) { matrix.clear(); matrix2.clear(); matrix.writeDisplay(); matrix2.writeDisplay(); delay(100); drawDisplay(); delay(100); matrix.clear(); matrix2.clear(); matrix.writeDisplay(); matrix2.writeDisplay(); delay(100); drawDisplay(); delay(100); matrix.clear(); matrix2.clear(); matrix.writeDisplay(); matrix2.writeDisplay(); delay(100); drawDisplay(); } } void doAnimation () { bool isRandom = false; if( aniChoice > 5) { aniChoice = 0; } if(aniChoice == 5) { isRandom = true; int randAni[4] = {1,2,3,4}; bubbleUnsort(randAni,4); aniChoice = randAni[0]; } if (aniChoice == 0 ) { drawDisplay(); } if (aniChoice == 1 ) { fadeOut(); } if (aniChoice == 2 ) { whiteOut(); } if (aniChoice == 3 ) { sweep(); } if (aniChoice == 4 ) { matrixy(); } if( isRandom == true) { aniChoice = 5; } } //Math! void bubbleUnsort(int *list, int elem) { for (int a=elem-1; a>0; a--) { //int r = random(a+1); int r = rand_range(a+1); if (r != a) { int temp = list[a]; list[a] = list[r]; list[r] = temp; } } } // generate a value between 0 <= x < n, thus there are n possible outputs int rand_range(int n) { int r, ul; ul = RAND_MAX - RAND_MAX % n; while ((r = random(RAND_MAX+1)) >= ul); return r % n; } void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers { asm volatile ("" jmp 0""); } ",8381,False,1681.4570389185715,median "/****************************************************************************** ** Filename: intproto.c ** Purpose: Definition of data structures for integer protos. ** Author: Dan Johnson ** ** (c) Copyright Hewlett-Packard Company, 1988. ** Licensed under the Apache License, Version 2.0 (the ""License""); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an ""AS IS"" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ******************************************************************************/ /*----------------------------------------------------------------------------- Include Files and Type Defines -----------------------------------------------------------------------------*/ #define _USE_MATH_DEFINES // for M_PI // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H # include ""config_auto.h"" #endif #include ""intproto.h"" #include ""classify.h"" #include ""fontinfo.h"" #include ""mfoutline.h"" #include ""picofeat.h"" #include ""points.h"" #include ""shapetable.h"" #ifndef GRAPHICS_DISABLED #include ""svmnode.h"" #endif #include ""helpers.h"" #include #include #include // for M_PI, std::floor #include namespace tesseract { /* match debug display constants*/ #define PROTO_PRUNER_SCALE (4.0) #define INT_DESCENDER (0.0 * INT_CHAR_NORM_RANGE) #define INT_BASELINE (0.25 * INT_CHAR_NORM_RANGE) #define INT_XHEIGHT (0.75 * INT_CHAR_NORM_RANGE) #define INT_CAPHEIGHT (1.0 * INT_CHAR_NORM_RANGE) #define INT_XCENTER (0.5 * INT_CHAR_NORM_RANGE) #define INT_YCENTER (0.5 * INT_CHAR_NORM_RANGE) #define INT_XRADIUS (0.2 * INT_CHAR_NORM_RANGE) #define INT_YRADIUS (0.2 * INT_CHAR_NORM_RANGE) #define INT_MIN_X 0 #define INT_MIN_Y 0 #define INT_MAX_X INT_CHAR_NORM_RANGE #define INT_MAX_Y INT_CHAR_NORM_RANGE /** define pad used to snap near horiz/vertical protos to horiz/vertical */ #define HV_TOLERANCE (0.0025) /* approx 0.9 degrees */ typedef enum { StartSwitch, EndSwitch, LastSwitch } SWITCH_TYPE; #define MAX_NUM_SWITCHES 3 struct FILL_SWITCH { SWITCH_TYPE Type; int8_t X, Y; int16_t YInit; int16_t Delta; }; struct TABLE_FILLER { uint8_t NextSwitch; uint8_t AngleStart, AngleEnd; int8_t X; int16_t YStart, YEnd; int16_t StartDelta, EndDelta; FILL_SWITCH Switch[MAX_NUM_SWITCHES]; }; struct FILL_SPEC { int8_t X; int8_t YStart, YEnd; uint8_t AngleStart, AngleEnd; }; /* constants for conversion from old inttemp format */ #define OLD_MAX_NUM_CONFIGS 32 #define OLD_WERDS_PER_CONFIG_VEC ((OLD_MAX_NUM_CONFIGS + BITS_PER_WERD - 1) / BITS_PER_WERD) /*----------------------------------------------------------------------------- Macros -----------------------------------------------------------------------------*/ /** macro for performing circular increments of bucket indices */ #define CircularIncrement(i, r) (((i) < (r)-1) ? ((i)++) : ((i) = 0)) /** macro for mapping floats to ints without bounds checking */ #define MapParam(P, O, N) (std::floor(((P) + (O)) * (N))) /*--------------------------------------------------------------------------- Private Function Prototypes ----------------------------------------------------------------------------*/ float BucketStart(int Bucket, float Offset, int NumBuckets); float BucketEnd(int Bucket, float Offset, int NumBuckets); void DoFill(FILL_SPEC *FillSpec, CLASS_PRUNER_STRUCT *Pruner, uint32_t ClassMask, uint32_t ClassCount, uint32_t WordIndex); bool FillerDone(TABLE_FILLER *Filler); void FillPPCircularBits(uint32_t ParamTable[NUM_PP_BUCKETS][WERDS_PER_PP_VECTOR], int Bit, float Center, float Spread, bool debug); void FillPPLinearBits(uint32_t ParamTable[NUM_PP_BUCKETS][WERDS_PER_PP_VECTOR], int Bit, float Center, float Spread, bool debug); void GetCPPadsForLevel(int Level, float *EndPad, float *SidePad, float *AnglePad); ScrollView::Color GetMatchColorFor(float Evidence); void GetNextFill(TABLE_FILLER *Filler, FILL_SPEC *Fill); void InitTableFiller(float EndPad, float SidePad, float AnglePad, PROTO_STRUCT *Proto, TABLE_FILLER *Filler); #ifndef GRAPHICS_DISABLED void RenderIntFeature(ScrollView *window, const INT_FEATURE_STRUCT *Feature, ScrollView::Color color); void RenderIntProto(ScrollView *window, INT_CLASS_STRUCT *Class, PROTO_ID ProtoId, ScrollView::Color color); #endif // !GRAPHICS_DISABLED /*----------------------------------------------------------------------------- Global Data Definitions and Declarations -----------------------------------------------------------------------------*/ #ifndef GRAPHICS_DISABLED /* global display lists used to display proto and feature match information*/ static ScrollView *IntMatchWindow = nullptr; static ScrollView *FeatureDisplayWindow = nullptr; static ScrollView *ProtoDisplayWindow = nullptr; #endif /*----------------------------------------------------------------------------- Variables -----------------------------------------------------------------------------*/ /* control knobs */ static INT_VAR(classify_num_cp_levels, 3, ""Number of Class Pruner Levels""); static double_VAR(classify_cp_angle_pad_loose, 45.0, ""Class Pruner Angle Pad Loose""); static double_VAR(classify_cp_angle_pad_medium, 20.0, ""Class Pruner Angle Pad Medium""); static double_VAR(classify_cp_angle_pad_tight, 10.0, ""CLass Pruner Angle Pad Tight""); static double_VAR(classify_cp_end_pad_loose, 0.5, ""Class Pruner End Pad Loose""); static double_VAR(classify_cp_end_pad_medium, 0.5, ""Class Pruner End Pad Medium""); static double_VAR(classify_cp_end_pad_tight, 0.5, ""Class Pruner End Pad Tight""); static double_VAR(classify_cp_side_pad_loose, 2.5, ""Class Pruner Side Pad Loose""); static double_VAR(classify_cp_side_pad_medium, 1.2, ""Class Pruner Side Pad Medium""); static double_VAR(classify_cp_side_pad_tight, 0.6, ""Class Pruner Side Pad Tight""); static double_VAR(classify_pp_angle_pad, 45.0, ""Proto Pruner Angle Pad""); static double_VAR(classify_pp_end_pad, 0.5, ""Proto Prune End Pad""); static double_VAR(classify_pp_side_pad, 2.5, ""Proto Pruner Side Pad""); /** * This routine truncates Param to lie within the range * of Min-Max inclusive. * * @param Param parameter value to be truncated * @param Min, Max parameter limits (inclusive) * * @return Truncated parameter. */ static int TruncateParam(float Param, int Min, int Max) { int result; if (Param < Min) { result = Min; } else if (Param > Max) { result = Max; } else { result = static_cast(std::floor(Param)); } return result; } /*----------------------------------------------------------------------------- Public Code -----------------------------------------------------------------------------*/ /// Builds a feature from an FCOORD for position with all the necessary /// clipping and rounding. INT_FEATURE_STRUCT::INT_FEATURE_STRUCT(const FCOORD &pos, uint8_t theta) : X(ClipToRange(static_cast(pos.x() + 0.5), 0, 255)) , Y(ClipToRange(static_cast(pos.y() + 0.5), 0, 255)) , Theta(theta) , CP_misses(0) {} /** Builds a feature from ints with all the necessary clipping and casting. */ INT_FEATURE_STRUCT::INT_FEATURE_STRUCT(int x, int y, int theta) : X(static_cast(ClipToRange(x, 0, UINT8_MAX))) , Y(static_cast(ClipToRange(y, 0, UINT8_MAX))) , Theta(static_cast(ClipToRange(theta, 0, UINT8_MAX))) , CP_misses(0) {} /** * This routine adds a new class structure to a set of * templates. Classes have to be added to Templates in * the order of increasing ClassIds. * * @param Templates templates to add new class to * @param ClassId class id to associate new class with * @param Class class data structure to add to templates * * Globals: none */ void AddIntClass(INT_TEMPLATES_STRUCT *Templates, CLASS_ID ClassId, INT_CLASS_STRUCT *Class) { int Pruner; assert(LegalClassId(ClassId)); if (ClassId != Templates->NumClasses) { fprintf(stderr, ""Please make sure that classes are added to templates"" "" in increasing order of ClassIds\\n""); exit(1); } ClassForClassId(Templates, ClassId) = Class; Templates->NumClasses++; if (Templates->NumClasses > MaxNumClassesIn(Templates)) { Pruner = Templates->NumClassPruners++; Templates->ClassPruners[Pruner] = new CLASS_PRUNER_STRUCT; memset(Templates->ClassPruners[Pruner], 0, sizeof(CLASS_PRUNER_STRUCT)); } } /* AddIntClass */ /** * This routine returns the index of the next free config * in Class. * * @param Class class to add new configuration to * * Globals: none * * @return Index of next free config. */ int AddIntConfig(INT_CLASS_STRUCT *Class) { int Index; assert(Class->NumConfigs < MAX_NUM_CONFIGS); Index = Class->NumConfigs++; Class->ConfigLengths[Index] = 0; return Index; } /* AddIntConfig */ /** * This routine allocates the next free proto in Class and * returns its index. * * @param Class class to add new proto to * * Globals: none * * @return Proto index of new proto. */ int AddIntProto(INT_CLASS_STRUCT *Class) { if (Class->NumProtos >= MAX_NUM_PROTOS) { return (NO_PROTO); } int Index = Class->NumProtos++; if (Class->NumProtos > MaxNumIntProtosIn(Class)) { int ProtoSetId = Class->NumProtoSets++; auto ProtoSet = new PROTO_SET_STRUCT; Class->ProtoSets[ProtoSetId] = ProtoSet; memset(ProtoSet, 0, sizeof(*ProtoSet)); /* reallocate space for the proto lengths and install in class */ Class->ProtoLengths.resize(MaxNumIntProtosIn(Class)); } /* initialize proto so its length is zero and it isn't in any configs */ Class->ProtoLengths[Index] = 0; auto Proto = ProtoForProtoId(Class, Index); for (uint32_t *Word = Proto->Configs; Word < Proto->Configs + WERDS_PER_CONFIG_VEC; *Word++ = 0) { } return (Index); } /** * This routine adds Proto to the class pruning tables * for the specified class in Templates. * * Globals: * - classify_num_cp_levels number of levels used in the class pruner * @param Proto floating-pt proto to add to class pruner * @param ClassId class id corresponding to Proto * @param Templates set of templates containing class pruner */ void AddProtoToClassPruner(PROTO_STRUCT *Proto, CLASS_ID ClassId, INT_TEMPLATES_STRUCT *Templates) #define MAX_LEVEL 2 { CLASS_PRUNER_STRUCT *Pruner; uint32_t ClassMask; uint32_t ClassCount; uint32_t WordIndex; int Level; float EndPad, SidePad, AnglePad; TABLE_FILLER TableFiller; FILL_SPEC FillSpec; Pruner = CPrunerFor(Templates, ClassId); WordIndex = CPrunerWordIndexFor(ClassId); ClassMask = CPrunerMaskFor(MAX_LEVEL, ClassId); for (Level = classify_num_cp_levels - 1; Level >= 0; Level--) { GetCPPadsForLevel(Level, &EndPad, &SidePad, &AnglePad); ClassCount = CPrunerMaskFor(Level, ClassId); InitTableFiller(EndPad, SidePad, AnglePad, Proto, &TableFiller); while (!FillerDone(&TableFiller)) { GetNextFill(&TableFiller, &FillSpec); DoFill(&FillSpec, Pruner, ClassMask, ClassCount, WordIndex); } } } /* AddProtoToClassPruner */ /** * This routine updates the proto pruner lookup tables * for Class to include a new proto identified by ProtoId * and described by Proto. * @param Proto floating-pt proto to be added to proto pruner * @param ProtoId id of proto * @param Class integer class that contains desired proto pruner * @param debug debug flag * @note Globals: none */ void AddProtoToProtoPruner(PROTO_STRUCT *Proto, int ProtoId, INT_CLASS_STRUCT *Class, bool debug) { float X, Y, Length; float Pad; if (ProtoId >= Class->NumProtos) { tprintf(""AddProtoToProtoPruner:assert failed: %d < %d"", ProtoId, Class->NumProtos); } assert(ProtoId < Class->NumProtos); int Index = IndexForProto(ProtoId); auto ProtoSet = Class->ProtoSets[SetForProto(ProtoId)]; float Angle = Proto->Angle; #ifndef _WIN32 assert(!std::isnan(Angle)); #endif FillPPCircularBits(ProtoSet->ProtoPruner[PRUNER_ANGLE], Index, Angle + ANGLE_SHIFT, classify_pp_angle_pad / 360.0, debug); Angle *= 2.0 * M_PI; Length = Proto->Length; X = Proto->X + X_SHIFT; Pad = std::max(fabs(cos(Angle)) * (Length / 2.0 + classify_pp_end_pad * GetPicoFeatureLength()), fabs(sin(Angle)) * (classify_pp_side_pad * GetPicoFeatureLength())); FillPPLinearBits(ProtoSet->ProtoPruner[PRUNER_X], Index, X, Pad, debug); Y = Proto->Y + Y_SHIFT; Pad = std::max(fabs(sin(Angle)) * (Length / 2.0 + classify_pp_end_pad * GetPicoFeatureLength()), fabs(cos(Angle)) * (classify_pp_side_pad * GetPicoFeatureLength())); FillPPLinearBits(ProtoSet->ProtoPruner[PRUNER_Y], Index, Y, Pad, debug); } /* AddProtoToProtoPruner */ /** * Returns a quantized bucket for the given param shifted by offset, * notionally (param + offset) * num_buckets, but clipped and casted to the * appropriate type. */ uint8_t Bucket8For(float param, float offset, int num_buckets) { int bucket = IntCastRounded(MapParam(param, offset, num_buckets)); return static_cast(ClipToRange(bucket, 0, num_buckets - 1)); } uint16_t Bucket16For(float param, float offset, int num_buckets) { int bucket = IntCastRounded(MapParam(param, offset, num_buckets)); return static_cast(ClipToRange(bucket, 0, num_buckets - 1)); } /** * Returns a quantized bucket for the given circular param shifted by offset, * notionally (param + offset) * num_buckets, but modded and casted to the * appropriate type. */ uint8_t CircBucketFor(float param, float offset, int num_buckets) { int bucket = IntCastRounded(MapParam(param, offset, num_buckets)); return static_cast(Modulo(bucket, num_buckets)); } /* CircBucketFor */ #ifndef GRAPHICS_DISABLED /** * This routine clears the global feature and proto * display lists. * * Globals: * - FeatureShapes display list for features * - ProtoShapes display list for protos */ void UpdateMatchDisplay() { if (IntMatchWindow != nullptr) { IntMatchWindow->Update(); } } /* ClearMatchDisplay */ #endif /** * This operation updates the config vectors of all protos * in Class to indicate that the protos with 1's in Config * belong to a new configuration identified by ConfigId. * It is assumed that the length of the Config bit vector is * equal to the number of protos in Class. * @param Config config to be added to class * @param ConfigId id to be used for new config * @param Class class to add new config to */ void ConvertConfig(BIT_VECTOR Config, int ConfigId, INT_CLASS_STRUCT *Class) { int ProtoId; INT_PROTO_STRUCT *Proto; int TotalLength; for (ProtoId = 0, TotalLength = 0; ProtoId < Class->NumProtos; ProtoId++) { if (test_bit(Config, ProtoId)) { Proto = ProtoForProtoId(Class, ProtoId); SET_BIT(Proto->Configs, ConfigId); TotalLength += Class->ProtoLengths[ProtoId]; } } Class->ConfigLengths[ConfigId] = TotalLength; } /* ConvertConfig */ /** * This routine converts Proto to integer format and * installs it as ProtoId in Class. * @param Proto floating-pt proto to be converted to integer format * @param ProtoId id of proto * @param Class integer class to add converted proto to */ void Classify::ConvertProto(PROTO_STRUCT *Proto, int ProtoId, INT_CLASS_STRUCT *Class) { assert(ProtoId < Class->NumProtos); INT_PROTO_STRUCT *P = ProtoForProtoId(Class, ProtoId); float Param = Proto->A * 128; P->A = TruncateParam(Param, -128, 127); Param = -Proto->B * 256; P->B = TruncateParam(Param, 0, 255); Param = Proto->C * 128; P->C = TruncateParam(Param, -128, 127); Param = Proto->Angle * 256; if (Param < 0 || Param >= 256) { P->Angle = 0; } else { P->Angle = static_cast(Param); } /* round proto length to nearest integer number of pico-features */ Param = (Proto->Length / GetPicoFeatureLength()) + 0.5; Class->ProtoLengths[ProtoId] = TruncateParam(Param, 1, 255); if (classify_learning_debug_level >= 2) { tprintf(""Converted ffeat to (A=%d,B=%d,C=%d,L=%d)"", P->A, P->B, P->C, Class->ProtoLengths[ProtoId]); } } /* ConvertProto */ /** * This routine converts from the old floating point format * to the new integer format. * @param FloatProtos prototypes in old floating pt format * @param target_unicharset the UNICHARSET to use * @return New set of training templates in integer format. * @note Globals: none */ INT_TEMPLATES_STRUCT *Classify::CreateIntTemplates(CLASSES FloatProtos, const UNICHARSET &target_unicharset) { CLASS_TYPE FClass; INT_CLASS_STRUCT *IClass; int ClassId; int ProtoId; int ConfigId; auto IntTemplates = new INT_TEMPLATES_STRUCT; for (ClassId = 0; ClassId < target_unicharset.size(); ClassId++) { FClass = &(FloatProtos[ClassId]); if (FClass->NumProtos == 0 && FClass->NumConfigs == 0 && strcmp(target_unicharset.id_to_unichar(ClassId), "" "") != 0) { tprintf(""Warning: no protos/configs for %s in CreateIntTemplates()\\n"", target_unicharset.id_to_unichar(ClassId)); } assert(UnusedClassIdIn(IntTemplates, ClassId)); IClass = new INT_CLASS_STRUCT(FClass->NumProtos, FClass->NumConfigs); FontSet fs{FClass->font_set.size()}; for (int i = 0; i < fs.size(); ++i) { fs[i] = FClass->font_set.at(i); } if (this->fontset_table_.contains(fs)) { IClass->font_set_id = this->fontset_table_.get_id(fs); } else { IClass->font_set_id = this->fontset_table_.push_back(fs); } AddIntClass(IntTemplates, ClassId, IClass); for (ProtoId = 0; ProtoId < FClass->NumProtos; ProtoId++) { AddIntProto(IClass); ConvertProto(ProtoIn(FClass, ProtoId), ProtoId, IClass); AddProtoToProtoPruner(ProtoIn(FClass, ProtoId), ProtoId, IClass, classify_learning_debug_level >= 2); AddProtoToClassPruner(ProtoIn(FClass, ProtoId), ClassId, IntTemplates); } for (ConfigId = 0; ConfigId < FClass->NumConfigs; ConfigId++) { AddIntConfig(IClass); ConvertConfig(FClass->Configurations[ConfigId], ConfigId, IClass); } } return (IntTemplates); } /* CreateIntTemplates */ #ifndef GRAPHICS_DISABLED /** * This routine renders the specified feature into a * global display list. * * Globals: * - FeatureShapes global display list for features * @param Feature pico-feature to be displayed * @param Evidence best evidence for this feature (0-1) */ void DisplayIntFeature(const INT_FEATURE_STRUCT *Feature, float Evidence) { ScrollView::Color color = GetMatchColorFor(Evidence); RenderIntFeature(IntMatchWindow, Feature, color); if (FeatureDisplayWindow) { RenderIntFeature(FeatureDisplayWindow, Feature, color); } } /* DisplayIntFeature */ /** * This routine renders the specified proto into a * global display list. * * Globals: * - ProtoShapes global display list for protos * @param Class class to take proto from * @param ProtoId id of proto in Class to be displayed * @param Evidence total evidence for proto (0-1) */ void DisplayIntProto(INT_CLASS_STRUCT *Class, PROTO_ID ProtoId, float Evidence) { ScrollView::Color color = GetMatchColorFor(Evidence); RenderIntProto(IntMatchWindow, Class, ProtoId, color); if (ProtoDisplayWindow) { RenderIntProto(ProtoDisplayWindow, Class, ProtoId, color); } } /* DisplayIntProto */ #endif /// This constructor creates a new integer class data structure /// and returns it. Sufficient space is allocated /// to handle the specified number of protos and configs. /// @param MaxNumProtos number of protos to allocate space for /// @param MaxNumConfigs number of configs to allocate space for INT_CLASS_STRUCT::INT_CLASS_STRUCT(int MaxNumProtos, int MaxNumConfigs) : NumProtos(0), NumProtoSets((MaxNumProtos + PROTOS_PER_PROTO_SET - 1) / PROTOS_PER_PROTO_SET), NumConfigs(0), ProtoLengths(MaxNumIntProtosIn(this)) { assert(MaxNumConfigs <= MAX_NUM_CONFIGS); assert(NumProtoSets <= MAX_NUM_PROTO_SETS); for (int i = 0; i < NumProtoSets; i++) { /* allocate space for a proto set, install in class, and initialize */ auto ProtoSet = new PROTO_SET_STRUCT; memset(ProtoSet, 0, sizeof(*ProtoSet)); ProtoSets[i] = ProtoSet; /* allocate space for the proto lengths and install in class */ } memset(ConfigLengths, 0, sizeof(ConfigLengths)); } INT_CLASS_STRUCT::~INT_CLASS_STRUCT() { for (int i = 0; i < NumProtoSets; i++) { delete ProtoSets[i]; } } /// This constructor allocates a new set of integer templates /// initialized to hold 0 classes. INT_TEMPLATES_STRUCT::INT_TEMPLATES_STRUCT() { NumClasses = 0; NumClassPruners = 0; for (int i = 0; i < MAX_NUM_CLASSES; i++) { ClassForClassId(this, i) = nullptr; } } INT_TEMPLATES_STRUCT::~INT_TEMPLATES_STRUCT() { for (int i = 0; i < NumClasses; i++) { delete Class[i]; } for (int i = 0; i < NumClassPruners; i++) { delete ClassPruners[i]; } } /** * This routine reads a set of integer templates from * File. File must already be open and must be in the * correct binary format. * @param fp open file to read templates from * @return Pointer to integer templates read from File. * @note Globals: none */ INT_TEMPLATES_STRUCT *Classify::ReadIntTemplates(TFile *fp) { int i, j, w, x, y, z; int unicharset_size; int version_id = 0; INT_TEMPLATES_STRUCT *Templates; CLASS_PRUNER_STRUCT *Pruner; INT_CLASS_STRUCT *Class; /* variables for conversion from older inttemp formats */ int b, bit_number, last_cp_bit_number, new_b, new_i, new_w; CLASS_ID class_id, max_class_id; std::vector ClassIdFor(MAX_NUM_CLASSES); std::vector TempClassPruner(MAX_NUM_CLASS_PRUNERS); uint32_t SetBitsForMask = // word with NUM_BITS_PER_CLASS (1 << NUM_BITS_PER_CLASS) - 1; // set starting at bit 0 uint32_t Mask, NewMask, ClassBits; int MaxNumConfigs = MAX_NUM_CONFIGS; int WerdsPerConfigVec = WERDS_PER_CONFIG_VEC; /* first read the high level template struct */ Templates = new INT_TEMPLATES_STRUCT; // Read Templates in parts for 64 bit compatibility. if (fp->FReadEndian(&unicharset_size, sizeof(unicharset_size), 1) != 1) { tprintf(""Bad read of inttemp!\\n""); } if (fp->FReadEndian(&Templates->NumClasses, sizeof(Templates->NumClasses), 1) != 1 || fp->FReadEndian(&Templates->NumClassPruners, sizeof(Templates->NumClassPruners), 1) != 1) { tprintf(""Bad read of inttemp!\\n""); } if (Templates->NumClasses < 0) { // This file has a version id! version_id = -Templates->NumClasses; if (fp->FReadEndian(&Templates->NumClasses, sizeof(Templates->NumClasses), 1) != 1) { tprintf(""Bad read of inttemp!\\n""); } } if (version_id < 3) { MaxNumConfigs = OLD_MAX_NUM_CONFIGS; WerdsPerConfigVec = OLD_WERDS_PER_CONFIG_VEC; } if (version_id < 2) { std::vector IndexFor(MAX_NUM_CLASSES); if (fp->FReadEndian(&IndexFor[0], sizeof(IndexFor[0]), unicharset_size) != unicharset_size) { tprintf(""Bad read of inttemp!\\n""); } if (fp->FReadEndian(&ClassIdFor[0], sizeof(ClassIdFor[0]), Templates->NumClasses) != Templates->NumClasses) { tprintf(""Bad read of inttemp!\\n""); } } /* then read in the class pruners */ const int kNumBuckets = NUM_CP_BUCKETS * NUM_CP_BUCKETS * NUM_CP_BUCKETS * WERDS_PER_CP_VECTOR; for (i = 0; i < Templates->NumClassPruners; i++) { Pruner = new CLASS_PRUNER_STRUCT; if (fp->FReadEndian(Pruner, sizeof(Pruner->p[0][0][0][0]), kNumBuckets) != kNumBuckets) { tprintf(""Bad read of inttemp!\\n""); } if (version_id < 2) { TempClassPruner[i] = Pruner; } else { Templates->ClassPruners[i] = Pruner; } } /* fix class pruners if they came from an old version of inttemp */ if (version_id < 2) { // Allocate enough class pruners to cover all the class ids. max_class_id = 0; for (i = 0; i < Templates->NumClasses; i++) { if (ClassIdFor[i] > max_class_id) { max_class_id = ClassIdFor[i]; } } for (i = 0; i <= CPrunerIdFor(max_class_id); i++) { Templates->ClassPruners[i] = new CLASS_PRUNER_STRUCT; memset(Templates->ClassPruners[i], 0, sizeof(CLASS_PRUNER_STRUCT)); } // Convert class pruners from the old format (indexed by class index) // to the new format (indexed by class id). last_cp_bit_number = NUM_BITS_PER_CLASS * Templates->NumClasses - 1; for (i = 0; i < Templates->NumClassPruners; i++) { for (x = 0; x < NUM_CP_BUCKETS; x++) { for (y = 0; y < NUM_CP_BUCKETS; y++) { for (z = 0; z < NUM_CP_BUCKETS; z++) { for (w = 0; w < WERDS_PER_CP_VECTOR; w++) { if (TempClassPruner[i]->p[x][y][z][w] == 0) { continue; } for (b = 0; b < BITS_PER_WERD; b += NUM_BITS_PER_CLASS) { bit_number = i * BITS_PER_CP_VECTOR + w * BITS_PER_WERD + b; if (bit_number > last_cp_bit_number) { break; // the rest of the bits in this word are not used } class_id = ClassIdFor[bit_number / NUM_BITS_PER_CLASS]; // Single out NUM_BITS_PER_CLASS bits relating to class_id. Mask = SetBitsForMask << b; ClassBits = TempClassPruner[i]->p[x][y][z][w] & Mask; // Move these bits to the new position in which they should // appear (indexed corresponding to the class_id). new_i = CPrunerIdFor(class_id); new_w = CPrunerWordIndexFor(class_id); new_b = CPrunerBitIndexFor(class_id) * NUM_BITS_PER_CLASS; if (new_b > b) { ClassBits <<= (new_b - b); } else { ClassBits >>= (b - new_b); } // Copy bits relating to class_id to the correct position // in Templates->ClassPruner. NewMask = SetBitsForMask << new_b; Templates->ClassPruners[new_i]->p[x][y][z][new_w] &= ~NewMask; Templates->ClassPruners[new_i]->p[x][y][z][new_w] |= ClassBits; } } } } } } for (i = 0; i < Templates->NumClassPruners; i++) { delete TempClassPruner[i]; } } /* then read in each class */ for (i = 0; i < Templates->NumClasses; i++) { /* first read in the high level struct for the class */ Class = new INT_CLASS_STRUCT; if (fp->FReadEndian(&Class->NumProtos, sizeof(Class->NumProtos), 1) != 1 || fp->FRead(&Class->NumProtoSets, sizeof(Class->NumProtoSets), 1) != 1 || fp->FRead(&Class->NumConfigs, sizeof(Class->NumConfigs), 1) != 1) { tprintf(""Bad read of inttemp!\\n""); } if (version_id == 0) { // Only version 0 writes 5 pointless pointers to the file. for (j = 0; j < 5; ++j) { int32_t junk; if (fp->FRead(&junk, sizeof(junk), 1) != 1) { tprintf(""Bad read of inttemp!\\n""); } } } int num_configs = version_id < 4 ? MaxNumConfigs : Class->NumConfigs; ASSERT_HOST(num_configs <= MaxNumConfigs); if (fp->FReadEndian(Class->ConfigLengths, sizeof(uint16_t), num_configs) != num_configs) { tprintf(""Bad read of inttemp!\\n""); } if (version_id < 2) { ClassForClassId(Templates, ClassIdFor[i]) = Class; } else { ClassForClassId(Templates, i) = Class; } /* then read in the proto lengths */ Class->ProtoLengths.clear(); if (MaxNumIntProtosIn(Class) > 0) { Class->ProtoLengths.resize(MaxNumIntProtosIn(Class)); if (fp->FRead(&Class->ProtoLengths[0], sizeof(uint8_t), MaxNumIntProtosIn(Class)) != MaxNumIntProtosIn(Class)) { tprintf(""Bad read of inttemp!\\n""); } } /* then read in the proto sets */ for (j = 0; j < Class->NumProtoSets; j++) { auto ProtoSet = new PROTO_SET_STRUCT; int num_buckets = NUM_PP_PARAMS * NUM_PP_BUCKETS * WERDS_PER_PP_VECTOR; if (fp->FReadEndian(&ProtoSet->ProtoPruner, sizeof(ProtoSet->ProtoPruner[0][0][0]), num_buckets) != num_buckets) { tprintf(""Bad read of inttemp!\\n""); } for (x = 0; x < PROTOS_PER_PROTO_SET; x++) { if (fp->FRead(&ProtoSet->Protos[x].A, sizeof(ProtoSet->Protos[x].A), 1) != 1 || fp->FRead(&ProtoSet->Protos[x].B, sizeof(ProtoSet->Protos[x].B), 1) != 1 || fp->FRead(&ProtoSet->Protos[x].C, sizeof(ProtoSet->Protos[x].C), 1) != 1 || fp->FRead(&ProtoSet->Protos[x].Angle, sizeof(ProtoSet->Protos[x].Angle), 1) != 1) { tprintf(""Bad read of inttemp!\\n""); } if (fp->FReadEndian(&ProtoSet->Protos[x].Configs, sizeof(ProtoSet->Protos[x].Configs[0]), WerdsPerConfigVec) != WerdsPerConfigVec) { tprintf(""Bad read of inttemp!\\n""); } } Class->ProtoSets[j] = ProtoSet; } if (version_id < 4) { Class->font_set_id = -1; } else { fp->FReadEndian(&Class->font_set_id, sizeof(Class->font_set_id), 1); } } if (version_id < 2) { /* add an empty nullptr class with class id 0 */ assert(UnusedClassIdIn(Templates, 0)); ClassForClassId(Templates, 0) = new INT_CLASS_STRUCT(1, 1); ClassForClassId(Templates, 0)->font_set_id = -1; Templates->NumClasses++; /* make sure the classes are contiguous */ for (i = 0; i < MAX_NUM_CLASSES; i++) { if (i < Templates->NumClasses) { if (ClassForClassId(Templates, i) == nullptr) { fprintf(stderr, ""Non-contiguous class ids in inttemp\\n""); exit(1); } } else { if (ClassForClassId(Templates, i) != nullptr) { fprintf(stderr, ""Class id %d exceeds NumClassesIn (Templates) %d\\n"", i, Templates->NumClasses); exit(1); } } } } if (version_id >= 4) { using namespace std::placeholders; // for _1, _2 this->fontinfo_table_.read(fp, std::bind(read_info, _1, _2)); if (version_id >= 5) { this->fontinfo_table_.read(fp, std::bind(read_spacing_info, _1, _2)); } this->fontset_table_.read(fp, [](auto *f, auto *fs) { return f->DeSerialize(*fs); } ); } return (Templates); } /* ReadIntTemplates */ #ifndef GRAPHICS_DISABLED /** * This routine sends the shapes in the global display * lists to the match debugger window. * * Globals: * - FeatureShapes display list containing feature matches * - ProtoShapes display list containing proto matches */ void Classify::ShowMatchDisplay() { InitIntMatchWindowIfReqd(); if (ProtoDisplayWindow) { ProtoDisplayWindow->Clear(); } if (FeatureDisplayWindow) { FeatureDisplayWindow->Clear(); } ClearFeatureSpaceWindow(static_cast(static_cast(classify_norm_method)), IntMatchWindow); IntMatchWindow->ZoomToRectangle(INT_MIN_X, INT_MIN_Y, INT_MAX_X, INT_MAX_Y); if (ProtoDisplayWindow) { ProtoDisplayWindow->ZoomToRectangle(INT_MIN_X, INT_MIN_Y, INT_MAX_X, INT_MAX_Y); } if (FeatureDisplayWindow) { FeatureDisplayWindow->ZoomToRectangle(INT_MIN_X, INT_MIN_Y, INT_MAX_X, INT_MAX_Y); } } /* ShowMatchDisplay */ /// Clears the given window and draws the featurespace guides for the /// appropriate normalization method. void ClearFeatureSpaceWindow(NORM_METHOD norm_method, ScrollView *window) { window->Clear(); window->Pen(ScrollView::GREY); // Draw the feature space limit rectangle. window->Rectangle(0, 0, INT_MAX_X, INT_MAX_Y); if (norm_method == baseline) { window->SetCursor(0, INT_DESCENDER); window->DrawTo(INT_MAX_X, INT_DESCENDER); window->SetCursor(0, INT_BASELINE); window->DrawTo(INT_MAX_X, INT_BASELINE); window->SetCursor(0, INT_XHEIGHT); window->DrawTo(INT_MAX_X, INT_XHEIGHT); window->SetCursor(0, INT_CAPHEIGHT); window->DrawTo(INT_MAX_X, INT_CAPHEIGHT); } else { window->Rectangle(INT_XCENTER - INT_XRADIUS, INT_YCENTER - INT_YRADIUS, INT_XCENTER + INT_XRADIUS, INT_YCENTER + INT_YRADIUS); } } #endif /** * This routine writes Templates to File. The format * is an efficient binary format. File must already be open * for writing. * @param File open file to write templates to * @param Templates templates to save into File * @param target_unicharset the UNICHARSET to use */ void Classify::WriteIntTemplates(FILE *File, INT_TEMPLATES_STRUCT *Templates, const UNICHARSET &target_unicharset) { int i, j; INT_CLASS_STRUCT *Class; int unicharset_size = target_unicharset.size(); int version_id = -5; // When negated by the reader -1 becomes +1 etc. if (Templates->NumClasses != unicharset_size) { tprintf( ""Warning: executing WriteIntTemplates() with %d classes in"" "" Templates, while target_unicharset size is %d\\n"", Templates->NumClasses, unicharset_size); } /* first write the high level template struct */ fwrite(&unicharset_size, sizeof(unicharset_size), 1, File); fwrite(&version_id, sizeof(version_id), 1, File); fwrite(&Templates->NumClassPruners, sizeof(Templates->NumClassPruners), 1, File); fwrite(&Templates->NumClasses, sizeof(Templates->NumClasses), 1, File); /* then write out the class pruners */ for (i = 0; i < Templates->NumClassPruners; i++) { fwrite(Templates->ClassPruners[i], sizeof(CLASS_PRUNER_STRUCT), 1, File); } /* then write out each class */ for (i = 0; i < Templates->NumClasses; i++) { Class = Templates->Class[i]; /* first write out the high level struct for the class */ fwrite(&Class->NumProtos, sizeof(Class->NumProtos), 1, File); fwrite(&Class->NumProtoSets, sizeof(Class->NumProtoSets), 1, File); ASSERT_HOST(Class->NumConfigs == this->fontset_table_.at(Class->font_set_id).size()); fwrite(&Class->NumConfigs, sizeof(Class->NumConfigs), 1, File); for (j = 0; j < Class->NumConfigs; ++j) { fwrite(&Class->ConfigLengths[j], sizeof(uint16_t), 1, File); } /* then write out the proto lengths */ if (MaxNumIntProtosIn(Class) > 0) { fwrite(&Class->ProtoLengths[0], sizeof(uint8_t), MaxNumIntProtosIn(Class), File); } /* then write out the proto sets */ for (j = 0; j < Class->NumProtoSets; j++) { fwrite(Class->ProtoSets[j], sizeof(PROTO_SET_STRUCT), 1, File); } /* then write the fonts info */ fwrite(&Class->font_set_id, sizeof(int), 1, File); } /* Write the fonts info tables */ using namespace std::placeholders; // for _1, _2 this->fontinfo_table_.write(File, std::bind(write_info, _1, _2)); this->fontinfo_table_.write(File, std::bind(write_spacing_info, _1, _2)); this->fontset_table_.write(File, std::bind(write_set, _1, _2)); } /* WriteIntTemplates */ /*----------------------------------------------------------------------------- Private Code -----------------------------------------------------------------------------*/ /** * This routine returns the parameter value which * corresponds to the beginning of the specified bucket. * The bucket number should have been generated using the * BucketFor() function with parameters Offset and NumBuckets. * @param Bucket bucket whose start is to be computed * @param Offset offset used to map params to buckets * @param NumBuckets total number of buckets * @return Param value corresponding to start position of Bucket. * @note Globals: none */ float BucketStart(int Bucket, float Offset, int NumBuckets) { return ((static_cast(Bucket) / NumBuckets) - Offset); } /* BucketStart */ /** * This routine returns the parameter value which * corresponds to the end of the specified bucket. * The bucket number should have been generated using the * BucketFor() function with parameters Offset and NumBuckets. * @param Bucket bucket whose end is to be computed * @param Offset offset used to map params to buckets * @param NumBuckets total number of buckets * @return Param value corresponding to end position of Bucket. * @note Globals: none */ float BucketEnd(int Bucket, float Offset, int NumBuckets) { return ((static_cast(Bucket + 1) / NumBuckets) - Offset); } /* BucketEnd */ /** * This routine fills in the section of a class pruner * corresponding to a single x value for a single proto of * a class. * @param FillSpec specifies which bits to fill in pruner * @param Pruner class pruner to be filled * @param ClassMask indicates which bits to change in each word * @param ClassCount indicates what to change bits to * @param WordIndex indicates which word to change */ void DoFill(FILL_SPEC *FillSpec, CLASS_PRUNER_STRUCT *Pruner, uint32_t ClassMask, uint32_t ClassCount, uint32_t WordIndex) { int X, Y, Angle; uint32_t OldWord; X = FillSpec->X; if (X < 0) { X = 0; } if (X >= NUM_CP_BUCKETS) { X = NUM_CP_BUCKETS - 1; } if (FillSpec->YStart < 0) { FillSpec->YStart = 0; } if (FillSpec->YEnd >= NUM_CP_BUCKETS) { FillSpec->YEnd = NUM_CP_BUCKETS - 1; } for (Y = FillSpec->YStart; Y <= FillSpec->YEnd; Y++) { for (Angle = FillSpec->AngleStart;; CircularIncrement(Angle, NUM_CP_BUCKETS)) { OldWord = Pruner->p[X][Y][Angle][WordIndex]; if (ClassCount > (OldWord & ClassMask)) { OldWord &= ~ClassMask; OldWord |= ClassCount; Pruner->p[X][Y][Angle][WordIndex] = OldWord; } if (Angle == FillSpec->AngleEnd) { break; } } } } /* DoFill */ /** * Return true if the specified table filler is done, i.e. * if it has no more lines to fill. * @param Filler table filler to check if done * @return true if no more lines to fill, false otherwise. * @note Globals: none */ bool FillerDone(TABLE_FILLER *Filler) { FILL_SWITCH *Next; Next = &(Filler->Switch[Filler->NextSwitch]); return Filler->X > Next->X && Next->Type == LastSwitch; } /* FillerDone */ /** * This routine sets Bit in each bit vector whose * bucket lies within the range Center +- Spread. The fill * is done for a circular dimension, i.e. bucket 0 is adjacent * to the last bucket. It is assumed that Center and Spread * are expressed in a circular coordinate system whose range * is 0 to 1. * @param ParamTable table of bit vectors, one per param bucket * @param Bit bit position in vectors to be filled * @param Center center of filled area * @param Spread spread of filled area * @param debug debug flag */ void FillPPCircularBits(uint32_t ParamTable[NUM_PP_BUCKETS][WERDS_PER_PP_VECTOR], int Bit, float Center, float Spread, bool debug) { int i, FirstBucket, LastBucket; if (Spread > 0.5) { Spread = 0.5; } FirstBucket = static_cast(std::floor((Center - Spread) * NUM_PP_BUCKETS)); if (FirstBucket < 0) { FirstBucket += NUM_PP_BUCKETS; } LastBucket = static_cast(std::floor((Center + Spread) * NUM_PP_BUCKETS)); if (LastBucket >= NUM_PP_BUCKETS) { LastBucket -= NUM_PP_BUCKETS; } if (debug) { tprintf(""Circular fill from %d to %d"", FirstBucket, LastBucket); } for (i = FirstBucket; true; CircularIncrement(i, NUM_PP_BUCKETS)) { SET_BIT(ParamTable[i], Bit); /* exit loop after we have set the bit for the last bucket */ if (i == LastBucket) { break; } } } /* FillPPCircularBits */ /** * This routine sets Bit in each bit vector whose * bucket lies within the range Center +- Spread. The fill * is done for a linear dimension, i.e. there is no wrap-around * for this dimension. It is assumed that Center and Spread * are expressed in a linear coordinate system whose range * is approximately 0 to 1. Values outside this range will * be clipped. * @param ParamTable table of bit vectors, one per param bucket * @param Bit bit number being filled * @param Center center of filled area * @param Spread spread of filled area * @param debug debug flag */ void FillPPLinearBits(uint32_t ParamTable[NUM_PP_BUCKETS][WERDS_PER_PP_VECTOR], int Bit, float Center, float Spread, bool debug) { int i, FirstBucket, LastBucket; FirstBucket = static_cast(std::floor((Center - Spread) * NUM_PP_BUCKETS)); if (FirstBucket < 0) { FirstBucket = 0; } LastBucket = static_cast(std::floor((Center + Spread) * NUM_PP_BUCKETS)); if (LastBucket >= NUM_PP_BUCKETS) { LastBucket = NUM_PP_BUCKETS - 1; } if (debug) { tprintf(""Linear fill from %d to %d"", FirstBucket, LastBucket); } for (i = FirstBucket; i <= LastBucket; i++) { SET_BIT(ParamTable[i], Bit); } } /* FillPPLinearBits */ /*---------------------------------------------------------------------------*/ #ifndef GRAPHICS_DISABLED /** * This routine prompts the user with Prompt and waits * for the user to enter something in the debug window. * @param Prompt prompt to print while waiting for input from window * @param adaptive_on * @param pretrained_on * @param shape_id * @return Character entered in the debug window. * @note Globals: none */ CLASS_ID Classify::GetClassToDebug(const char *Prompt, bool *adaptive_on, bool *pretrained_on, int *shape_id) { tprintf(""%s\\n"", Prompt); SVEvent *ev; SVEventType ev_type; int unichar_id = INVALID_UNICHAR_ID; // Wait until a click or popup event. do { ev = IntMatchWindow->AwaitEvent(SVET_ANY); ev_type = ev->type; if (ev_type == SVET_POPUP) { if (ev->command_id == IDA_SHAPE_INDEX) { if (shape_table_ != nullptr) { *shape_id = atoi(ev->parameter); *adaptive_on = false; *pretrained_on = true; if (*shape_id >= 0 && *shape_id < shape_table_->NumShapes()) { int font_id; shape_table_->GetFirstUnicharAndFont(*shape_id, &unichar_id, &font_id); tprintf(""Shape %d, first unichar=%d, font=%d\\n"", *shape_id, unichar_id, font_id); return unichar_id; } tprintf(""Shape index '%s' not found in shape table\\n"", ev->parameter); } else { tprintf(""No shape table loaded!\\n""); } } else { if (unicharset.contains_unichar(ev->parameter)) { unichar_id = unicharset.unichar_to_id(ev->parameter); if (ev->command_id == IDA_ADAPTIVE) { *adaptive_on = true; *pretrained_on = false; *shape_id = -1; } else if (ev->command_id == IDA_STATIC) { *adaptive_on = false; *pretrained_on = true; } else { *adaptive_on = true; *pretrained_on = true; } if (ev->command_id == IDA_ADAPTIVE || shape_table_ == nullptr) { *shape_id = -1; return unichar_id; } for (int s = 0; s < shape_table_->NumShapes(); ++s) { if (shape_table_->GetShape(s).ContainsUnichar(unichar_id)) { tprintf(""%s\\n"", shape_table_->DebugStr(s).c_str()); } } } else { tprintf(""Char class '%s' not found in unicharset"", ev->parameter); } } } delete ev; } while (ev_type != SVET_CLICK); return 0; } /* GetClassToDebug */ #endif /** * This routine copies the appropriate global pad variables * into EndPad, SidePad, and AnglePad. This is a kludge used * to get around the fact that global control variables cannot * be arrays. If the specified level is illegal, the tightest * possible pads are returned. * @param Level ""tightness"" level to return pads for * @param EndPad place to put end pad for Level * @param SidePad place to put side pad for Level * @param AnglePad place to put angle pad for Level */ void GetCPPadsForLevel(int Level, float *EndPad, float *SidePad, float *AnglePad) { switch (Level) { case 0: *EndPad = classify_cp_end_pad_loose * GetPicoFeatureLength(); *SidePad = classify_cp_side_pad_loose * GetPicoFeatureLength(); *AnglePad = classify_cp_angle_pad_loose / 360.0; break; case 1: *EndPad = classify_cp_end_pad_medium * GetPicoFeatureLength(); *SidePad = classify_cp_side_pad_medium * GetPicoFeatureLength(); *AnglePad = classify_cp_angle_pad_medium / 360.0; break; case 2: *EndPad = classify_cp_end_pad_tight * GetPicoFeatureLength(); *SidePad = classify_cp_side_pad_tight * GetPicoFeatureLength(); *AnglePad = classify_cp_angle_pad_tight / 360.0; break; default: *EndPad = classify_cp_end_pad_tight * GetPicoFeatureLength(); *SidePad = classify_cp_side_pad_tight * GetPicoFeatureLength(); *AnglePad = classify_cp_angle_pad_tight / 360.0; break; } if (*AnglePad > 0.5) { *AnglePad = 0.5; } } /* GetCPPadsForLevel */ /** * @param Evidence evidence value to return color for * @return Color which corresponds to specified Evidence value. * @note Globals: none */ ScrollView::Color GetMatchColorFor(float Evidence) { assert(Evidence >= 0.0); assert(Evidence <= 1.0); if (Evidence >= 0.90) { return ScrollView::WHITE; } else if (Evidence >= 0.75) { return ScrollView::GREEN; } else if (Evidence >= 0.50) { return ScrollView::RED; } else { return ScrollView::BLUE; } } /* GetMatchColorFor */ /** * This routine returns (in Fill) the specification of * the next line to be filled from Filler. FillerDone() should * always be called before GetNextFill() to ensure that we * do not run past the end of the fill table. * @param Filler filler to get next fill spec from * @param Fill place to put spec for next fill */ void GetNextFill(TABLE_FILLER *Filler, FILL_SPEC *Fill) { FILL_SWITCH *Next; /* compute the fill assuming no switches will be encountered */ Fill->AngleStart = Filler->AngleStart; Fill->AngleEnd = Filler->AngleEnd; Fill->X = Filler->X; Fill->YStart = Filler->YStart >> 8; Fill->YEnd = Filler->YEnd >> 8; /* update the fill info and the filler for ALL switches at this X value */ Next = &(Filler->Switch[Filler->NextSwitch]); while (Filler->X >= Next->X) { Fill->X = Filler->X = Next->X; if (Next->Type == StartSwitch) { Fill->YStart = Next->Y; Filler->StartDelta = Next->Delta; Filler->YStart = Next->YInit; } else if (Next->Type == EndSwitch) { Fill->YEnd = Next->Y; Filler->EndDelta = Next->Delta; Filler->YEnd = Next->YInit; } else { /* Type must be LastSwitch */ break; } Filler->NextSwitch++; Next = &(Filler->Switch[Filler->NextSwitch]); } /* prepare the filler for the next call to this routine */ Filler->X++; Filler->YStart += Filler->StartDelta; Filler->YEnd += Filler->EndDelta; } /* GetNextFill */ /** * This routine computes a data structure (Filler) * which can be used to fill in a rectangle surrounding * the specified Proto. Results are returned in Filler. * * @param EndPad, SidePad, AnglePad padding to add to proto * @param Proto proto to create a filler for * @param Filler place to put table filler */ void InitTableFiller(float EndPad, float SidePad, float AnglePad, PROTO_STRUCT *Proto, TABLE_FILLER *Filler) #define XS X_SHIFT #define YS Y_SHIFT #define AS ANGLE_SHIFT #define NB NUM_CP_BUCKETS { float Angle; float X, Y, HalfLength; float Cos, Sin; float XAdjust, YAdjust; FPOINT Start, Switch1, Switch2, End; int S1 = 0; int S2 = 1; Angle = Proto->Angle; X = Proto->X; Y = Proto->Y; HalfLength = Proto->Length / 2.0; Filler->AngleStart = CircBucketFor(Angle - AnglePad, AS, NB); Filler->AngleEnd = CircBucketFor(Angle + AnglePad, AS, NB); Filler->NextSwitch = 0; if (fabs(Angle - 0.0) < HV_TOLERANCE || fabs(Angle - 0.5) < HV_TOLERANCE) { /* horizontal proto - handle as special case */ Filler->X = Bucket8For(X - HalfLength - EndPad, XS, NB); Filler->YStart = Bucket16For(Y - SidePad, YS, NB * 256); Filler->YEnd = Bucket16For(Y + SidePad, YS, NB * 256); Filler->StartDelta = 0; Filler->EndDelta = 0; Filler->Switch[0].Type = LastSwitch; Filler->Switch[0].X = Bucket8For(X + HalfLength + EndPad, XS, NB); } else if (fabs(Angle - 0.25) < HV_TOLERANCE || fabs(Angle - 0.75) < HV_TOLERANCE) { /* vertical proto - handle as special case */ Filler->X = Bucket8For(X - SidePad, XS, NB); Filler->YStart = Bucket16For(Y - HalfLength - EndPad, YS, NB * 256); Filler->YEnd = Bucket16For(Y + HalfLength + EndPad, YS, NB * 256); Filler->StartDelta = 0; Filler->EndDelta = 0; Filler->Switch[0].Type = LastSwitch; Filler->Switch[0].X = Bucket8For(X + SidePad, XS, NB); } else { /* diagonal proto */ if ((Angle > 0.0 && Angle < 0.25) || (Angle > 0.5 && Angle < 0.75)) { /* rising diagonal proto */ Angle *= 2.0 * M_PI; Cos = fabs(cos(Angle)); Sin = fabs(sin(Angle)); /* compute the positions of the corners of the acceptance region */ Start.x = X - (HalfLength + EndPad) * Cos - SidePad * Sin; Start.y = Y - (HalfLength + EndPad) * Sin + SidePad * Cos; End.x = 2.0 * X - Start.x; End.y = 2.0 * Y - Start.y; Switch1.x = X - (HalfLength + EndPad) * Cos + SidePad * Sin; Switch1.y = Y - (HalfLength + EndPad) * Sin - SidePad * Cos; Switch2.x = 2.0 * X - Switch1.x; Switch2.y = 2.0 * Y - Switch1.y; if (Switch1.x > Switch2.x) { S1 = 1; S2 = 0; } /* translate into bucket positions and deltas */ Filler->X = Bucket8For(Start.x, XS, NB); Filler->StartDelta = -static_cast((Cos / Sin) * 256); Filler->EndDelta = static_cast((Sin / Cos) * 256); XAdjust = BucketEnd(Filler->X, XS, NB) - Start.x; YAdjust = XAdjust * Cos / Sin; Filler->YStart = Bucket16For(Start.y - YAdjust, YS, NB * 256); YAdjust = XAdjust * Sin / Cos; Filler->YEnd = Bucket16For(Start.y + YAdjust, YS, NB * 256); Filler->Switch[S1].Type = StartSwitch; Filler->Switch[S1].X = Bucket8For(Switch1.x, XS, NB); Filler->Switch[S1].Y = Bucket8For(Switch1.y, YS, NB); XAdjust = Switch1.x - BucketStart(Filler->Switch[S1].X, XS, NB); YAdjust = XAdjust * Sin / Cos; Filler->Switch[S1].YInit = Bucket16For(Switch1.y - YAdjust, YS, NB * 256); Filler->Switch[S1].Delta = Filler->EndDelta; Filler->Switch[S2].Type = EndSwitch; Filler->Switch[S2].X = Bucket8For(Switch2.x, XS, NB); Filler->Switch[S2].Y = Bucket8For(Switch2.y, YS, NB); XAdjust = Switch2.x - BucketStart(Filler->Switch[S2].X, XS, NB); YAdjust = XAdjust * Cos / Sin; Filler->Switch[S2].YInit = Bucket16For(Switch2.y + YAdjust, YS, NB * 256); Filler->Switch[S2].Delta = Filler->StartDelta; Filler->Switch[2].Type = LastSwitch; Filler->Switch[2].X = Bucket8For(End.x, XS, NB); } else { /* falling diagonal proto */ Angle *= 2.0 * M_PI; Cos = fabs(cos(Angle)); Sin = fabs(sin(Angle)); /* compute the positions of the corners of the acceptance region */ Start.x = X - (HalfLength + EndPad) * Cos - SidePad * Sin; Start.y = Y + (HalfLength + EndPad) * Sin - SidePad * Cos; End.x = 2.0 * X - Start.x; End.y = 2.0 * Y - Start.y; Switch1.x = X - (HalfLength + EndPad) * Cos + SidePad * Sin; Switch1.y = Y + (HalfLength + EndPad) * Sin + SidePad * Cos; Switch2.x = 2.0 * X - Switch1.x; Switch2.y = 2.0 * Y - Switch1.y; if (Switch1.x > Switch2.x) { S1 = 1; S2 = 0; } /* translate into bucket positions and deltas */ Filler->X = Bucket8For(Start.x, XS, NB); Filler->StartDelta = static_cast( ClipToRange(-IntCastRounded((Sin / Cos) * 256), INT16_MIN, INT16_MAX)); Filler->EndDelta = static_cast( ClipToRange(IntCastRounded((Cos / Sin) * 256), INT16_MIN, INT16_MAX)); XAdjust = BucketEnd(Filler->X, XS, NB) - Start.x; YAdjust = XAdjust * Sin / Cos; Filler->YStart = Bucket16For(Start.y - YAdjust, YS, NB * 256); YAdjust = XAdjust * Cos / Sin; Filler->YEnd = Bucket16For(Start.y + YAdjust, YS, NB * 256); Filler->Switch[S1].Type = EndSwitch; Filler->Switch[S1].X = Bucket8For(Switch1.x, XS, NB); Filler->Switch[S1].Y = Bucket8For(Switch1.y, YS, NB); XAdjust = Switch1.x - BucketStart(Filler->Switch[S1].X, XS, NB); YAdjust = XAdjust * Sin / Cos; Filler->Switch[S1].YInit = Bucket16For(Switch1.y + YAdjust, YS, NB * 256); Filler->Switch[S1].Delta = Filler->StartDelta; Filler->Switch[S2].Type = StartSwitch; Filler->Switch[S2].X = Bucket8For(Switch2.x, XS, NB); Filler->Switch[S2].Y = Bucket8For(Switch2.y, YS, NB); XAdjust = Switch2.x - BucketStart(Filler->Switch[S2].X, XS, NB); YAdjust = XAdjust * Cos / Sin; Filler->Switch[S2].YInit = Bucket16For(Switch2.y - YAdjust, YS, NB * 256); Filler->Switch[S2].Delta = Filler->EndDelta; Filler->Switch[2].Type = LastSwitch; Filler->Switch[2].X = Bucket8For(End.x, XS, NB); } } } /* InitTableFiller */ /*---------------------------------------------------------------------------*/ #ifndef GRAPHICS_DISABLED /** * This routine renders the specified feature into ShapeList. * @param window to add feature rendering to * @param Feature feature to be rendered * @param color color to use for feature rendering * @return New shape list with rendering of Feature added. * @note Globals: none */ void RenderIntFeature(ScrollView *window, const INT_FEATURE_STRUCT *Feature, ScrollView::Color color) { float X, Y, Dx, Dy, Length; window->Pen(color); assert(Feature != nullptr); assert(color != 0); X = Feature->X; Y = Feature->Y; Length = GetPicoFeatureLength() * 0.7 * INT_CHAR_NORM_RANGE; // The -PI has no significant effect here, but the value of Theta is computed // using BinaryAnglePlusPi in intfx.cpp. Dx = (Length / 2.0) * cos((Feature->Theta / 256.0) * 2.0 * M_PI - M_PI); Dy = (Length / 2.0) * sin((Feature->Theta / 256.0) * 2.0 * M_PI - M_PI); window->SetCursor(X, Y); window->DrawTo(X + Dx, Y + Dy); } /* RenderIntFeature */ /** * This routine extracts the parameters of the specified * proto from the class description and adds a rendering of * the proto onto the ShapeList. * * @param window ScrollView instance * @param Class class that proto is contained in * @param ProtoId id of proto to be rendered * @param color color to render proto in * * Globals: none * * @return New shape list with a rendering of one proto added. */ void RenderIntProto(ScrollView *window, INT_CLASS_STRUCT *Class, PROTO_ID ProtoId, ScrollView::Color color) { INT_PROTO_STRUCT *Proto; int ProtoSetIndex; int ProtoWordIndex; float Length; int Xmin, Xmax, Ymin, Ymax; float X, Y, Dx, Dy; uint32_t ProtoMask; int Bucket; assert(ProtoId >= 0); assert(Class != nullptr); assert(ProtoId < Class->NumProtos); assert(color != 0); window->Pen(color); auto ProtoSet = Class->ProtoSets[SetForProto(ProtoId)]; ProtoSetIndex = IndexForProto(ProtoId); Proto = &(ProtoSet->Protos[ProtoSetIndex]); Length = (Class->ProtoLengths[ProtoId] * GetPicoFeatureLength() * INT_CHAR_NORM_RANGE); ProtoMask = PPrunerMaskFor(ProtoId); ProtoWordIndex = PPrunerWordIndexFor(ProtoId); // find the x and y extent of the proto from the proto pruning table Xmin = Ymin = NUM_PP_BUCKETS; Xmax = Ymax = 0; for (Bucket = 0; Bucket < NUM_PP_BUCKETS; Bucket++) { if (ProtoMask & ProtoSet->ProtoPruner[PRUNER_X][Bucket][ProtoWordIndex]) { UpdateRange(Bucket, &Xmin, &Xmax); } if (ProtoMask & ProtoSet->ProtoPruner[PRUNER_Y][Bucket][ProtoWordIndex]) { UpdateRange(Bucket, &Ymin, &Ymax); } } X = (Xmin + Xmax + 1) / 2.0 * PROTO_PRUNER_SCALE; Y = (Ymin + Ymax + 1) / 2.0 * PROTO_PRUNER_SCALE; // The -PI has no significant effect here, but the value of Theta is computed // using BinaryAnglePlusPi in intfx.cpp. Dx = (Length / 2.0) * cos((Proto->Angle / 256.0) * 2.0 * M_PI - M_PI); Dy = (Length / 2.0) * sin((Proto->Angle / 256.0) * 2.0 * M_PI - M_PI); window->SetCursor(X - Dx, Y - Dy); window->DrawTo(X + Dx, Y + Dy); } /* RenderIntProto */ #endif #ifndef GRAPHICS_DISABLED /** * Initializes the int matcher window if it is not already * initialized. */ void InitIntMatchWindowIfReqd() { if (IntMatchWindow == nullptr) { IntMatchWindow = CreateFeatureSpaceWindow(""IntMatchWindow"", 50, 200); auto *popup_menu = new SVMenuNode(); popup_menu->AddChild(""Debug Adapted classes"", IDA_ADAPTIVE, ""x"", ""Class to debug""); popup_menu->AddChild(""Debug Static classes"", IDA_STATIC, ""x"", ""Class to debug""); popup_menu->AddChild(""Debug Both"", IDA_BOTH, ""x"", ""Class to debug""); popup_menu->AddChild(""Debug Shape Index"", IDA_SHAPE_INDEX, ""0"", ""Index to debug""); popup_menu->BuildMenu(IntMatchWindow, false); } } /** * Initializes the proto display window if it is not already * initialized. */ void InitProtoDisplayWindowIfReqd() { if (ProtoDisplayWindow == nullptr) { ProtoDisplayWindow = CreateFeatureSpaceWindow(""ProtoDisplayWindow"", 550, 200); } } /** * Initializes the feature display window if it is not already * initialized. */ void InitFeatureDisplayWindowIfReqd() { if (FeatureDisplayWindow == nullptr) { FeatureDisplayWindow = CreateFeatureSpaceWindow(""FeatureDisplayWindow"", 50, 700); } } /// Creates a window of the appropriate size for displaying elements /// in feature space. ScrollView *CreateFeatureSpaceWindow(const char *name, int xpos, int ypos) { return new ScrollView(name, xpos, ypos, 520, 520, 260, 260, true); } #endif // !GRAPHICS_DISABLED } // namespace tesseract ",16241,True,2921.0027638600404,median "//выгрузка из ячейки передней или задней в зависимости от флага stY static void unloadingCELL() { if (stY==""3"") //действия производятся с передней ячейкой { vygruzkaKP(); } else if (stY==""1"") //действия производятся с задней ячейкой { vygruzkaKZ(); } } //загрузка в ячейку переднею или заднею в зависимости от флага stY static void loadingCELL() { if (stY==""3"") //действия производятся с передней ячейкой { zagruzkaKP(); } else if (stY==""1"") //действия производятся с задней ячейкой { zagruzkaKZ(); } } //выгрузка из передней ячейки static void vygruzkaKP() { //{""command"":""VKP""} vTaskDelay(180); if (StatusKkr==""free"") { meZ=StatusZ; int Zdw,Zup; boolean vyA=0; //параметры спуска и подъема оси Z зависят от уровня //операция допускается только на этих уровнях т.е. vyA=1 if (meZ==""Z0"") { Zdw=-250; Zup=420; vyA=1; } //отсек выдачи Y3 else if (meZ==""Z1"") { Zdw=-300; Zup=420; vyA=1; } //нет ячейки else if (meZ==""Z2"") { Zdw=-250; Zup=422; vyA=1; } else if (meZ==""Z3"") { Zdw=-250; Zup=410; vyA=1; } if ((KZ0)&&(KX0)) { ovopcl(0); } //операция возможна при закрытом люке выдачи //операция допускается if ((vyA)&&(XUN==0)&&(VD)&&(Bvz)) { OprSt=""vygruzka "" + meZ + StatusX + ""Y3 ... .""; //операция выгрузки из ячейки выполняется снизу вверх Zjump(Zdw); //опускаем Z //выдвигаем Y на Y3pered Y3Block(); vTaskDelay(120); //Y выдвинут Zjump(Zup); //поднимаемся Z вверх цепляем контейнер //работа гусеницы выгружаем контейнер //пока не сработает концевик на каретке движение не более 9сек. unsigned long gustrack=millis(); for(;;) { gusmotor(1); //при сработке cnt2 gusmotor(0) и break; if (cnt2) { gusmotor(0); vTaskDelay(200); if (cnt2) { gusmotor(0); break; }} //при сработке таймера gusmotor(0) и break; if ((millis()-gustrack)>10100) { gusmotor(0); break; } } //задвигаем Y на Y2center Y2Block(); vTaskDelay(120); //Y задвинут //возвращаем Z в исходное положение tempmoveZ=""nazad""; Zcorrect(); OprSt=""vygruzka "" + meZ + StatusX + ""Y3 OK""; stY=""2""; } } } //загрузка в переднею ячейку static void zagruzkaKP() { //{""command"":""ZKP""} vTaskDelay(180); if (StatusKkr==""loaded"") { meZ=StatusZ; int Zdw,Zup; boolean vaA=0; //параметры спуска и подъема оси Z зависят от уровня //операция допускается только на этих уровнях т.е. vaA=1 if (meZ==""Z0"") { Zup=185; Zdw=-415; vaA=1; } //отсек выдачи Y3 else if (meZ==""Z1"") { Zup=185; Zdw=-415; vaA=1; } //нет ячейки else if (meZ==""Z2"") { Zup=200; Zdw=-420; vaA=1; } else if (meZ==""Z3"") { Zup=185; Zdw=-380; vaA=1; } if ((KZ0)&&(KX0)) { ovopcl(0); } //операция возможна при закрытом люке выдачи //операция допускается if ((vaA)&&(XUN==0)&&(VD)&&(Bvz)&&(BPP)) { OprSt=""zagruzka "" + meZ + StatusX + ""Y3 ... .""; //операция загрузки в ячейку выполняется сверху вниз Zjump(Zup); //поднимаем Z //выдвигаем Y на Y3pered Y3Block(); vTaskDelay(120); //Y выдвинут //работа гусеницы загружаем контейнер //движение не более 5сек. unsigned long gustrack=millis(); for(;;) { //при сработки концевиков в передних ячейках gusmotor(0) и break; if ((meZ==""Z0"")&&(Z0Y3)) { gusmotor(0); vTaskDelay(200); if (Z0Y3) { gusmotor(0); break; }} else if ((meZ==""Z2"")&&(Z2Y3)) { gusmotor(0); vTaskDelay(200); if (Z2Y3) { gusmotor(0); break; }} else if ((meZ==""Z3"")&&(Z3Y3)) { gusmotor(0); vTaskDelay(200); if (Z3Y3) { gusmotor(0); break; }} //при сработке таймера gusmotor(0) и break; if ((millis()-gustrack)>7200) { gusmotor(0); break; } gusmotor(2); } //контейнер загружен Zjump(Zdw); //опускаем Z контейнер не цепляет //задвигаем Y на Y2center Y2Block(); vTaskDelay(120); //Y задвинут //возвращаем Z в исходное положение tempmoveZ=""vpered""; if (meZ==""Z0"") { Flzkp=1; } Zcorrect(); Flzkp=0; OprSt=""zagruzka "" + meZ + StatusX + ""Y3 OK""; stY=""2""; } } } //выгрузка из задней ячейки static void vygruzkaKZ() { //{""command"":""VKZ""} vTaskDelay(180); if (StatusKkr==""free"") { meZ=StatusZ; int Zdw,Zup; boolean vyA=0; //параметры спуска и подъема оси Z зависят от уровня //операция допускается только на этих уровнях т.е. vyA=1 if (meZ==""Z0"") { Zdw=-370; Zup=260; vyA=1; } //отсек выдачи else if (meZ==""Z1"") { Zdw=-300; Zup=240; vyA=1; } else if (meZ==""Z2"") { Zdw=-290; Zup=314; vyA=1; } else if (meZ==""Z3"") { Zdw=-280; Zup=344; vyA=1; } //операция допускается if ((vyA)&&(XUN==0)&&(VD)&&(Bpz)) { OprSt=""vygruzka "" + meZ + StatusX + ""Y1 ... .""; //операция выгрузки из ячейки выполняется снизу вверх Zjump(Zdw); //опускаем Z //выдвигаем Y на Y1zad Y1Block(); vTaskDelay(120); //Y выдвинут Zjump(Zup); //поднимаемся Z вверх цепляем контейнер //работа гусеницы выгружаем контейнер //пока не сработает концевик на каретке движение не более 9сек. unsigned long gustrack=millis(); for(;;) { gusmotor(2); //при сработке cnt2 gusmotor(0) и break; if (cnt2) { gusmotor(0); vTaskDelay(200); if (cnt2) { gusmotor(0); break; }} //при сработке таймера gusmotor(0) и break; if ((millis()-gustrack)>9000) { gusmotor(0); break; } } //задвигаем Y на Y2center Y2Block(); vTaskDelay(120); //Y задвинут //возвращаем Z в исходное положение tempmoveZ=""nazad""; Zcorrect(); OprSt=""vygruzka "" + meZ + StatusX + ""Y1 OK""; stY=""2""; } } } //загрузка в заднею ячейку static void zagruzkaKZ() { //{""command"":""ZKZ""} vTaskDelay(180); if (StatusKkr==""loaded"") { meZ=StatusZ; int Zdw,Zup; boolean vaA=0; //параметры спуска и подъема оси Z зависят от уровня //операция допускается только на этих уровнях т.е. vaA=1 if (meZ==""Z0"") { Zup=100; Zdw=-180; vaA=1; } else if (meZ==""Z1"") { Zup=80; Zdw=-620; vaA=1; } else if (meZ==""Z2"") { Zup=110; Zdw=-620; vaA=1; } else if (meZ==""Z3"") { Zup=100; Zdw=-655; vaA=1; } //операция допускается if ((vaA)&&(XUN==0)&&(VD)&&(Bpz)&&(BPZ)) { OprSt=""zagruzka "" + meZ + StatusX + ""Y1 ... .""; //операция загрузки в ячейку выполняется сверху вниз Zjump(Zup); //поднимаем Z //выдвигаем Y на Y1zad Y1Block(); vTaskDelay(120); //Y выдвинут //работа гусеницы загружаем контейнер //движение не более 5сек. unsigned long gustrack=millis(); for(;;) { //при сработки концевиков в задних ячейках gusmotor(0) и break; if ((meZ==""Z0"")&&(Z0Y1)) { gusmotor(0); vTaskDelay(200); if (Z0Y1) { gusmotor(0); break; }} else if ((meZ==""Z1"")&&(Z1Y1)) { gusmotor(0); vTaskDelay(200); if (Z1Y1) { gusmotor(0); break; }} else if ((meZ==""Z2"")&&(Z2Y1)) { gusmotor(0); vTaskDelay(200); if (Z2Y1) { gusmotor(0); break; }} else if ((meZ==""Z3"")&&(Z3Y1)) { gusmotor(0); vTaskDelay(200); if (Z3Y1) { gusmotor(0); break; }} //при сработке таймера gusmotor(0) и break; if ((millis()-gustrack)>6200) { gusmotor(0); break; } gusmotor(1); } //контейнер загружен Zjump(Zdw); //опускаем Z контейнер не цепляет //задвигаем Y на Y2center Y2Block(); vTaskDelay(120); //Y задвинут //возвращаем Z в исходное положение tempmoveZ=""vpered""; if (meZ==""Z0"") { Flzkp=1; } Zcorrect(); Flzkp=0; OprSt=""zagruzka "" + meZ + StatusX + ""Y1 OK""; stY=""2""; } } } //открыть верхний люк static void openVL() {//операция не допускается при нахождении каретки на уровнях Z4 или Z5 if ((!KZ4)||(!KZ5)) { OprSt=""top hatch opening.. .""; vlps(0); vlvz(0); OprSt=""top hatch open OK""; } } //закрыть верхний люк static void closeVL() {//операция не допускается при нахождении каретки на уровнях Z4 или Z5 if ((!KZ4)||(!KZ5)) { OprSt=""top hatch closing.. .""; vlvz(1); vlps(1); OprSt=""top hatch close OK""; } } //подъем и спуск верхнего люка static void vlps(boolean direct) { vTaskDelay(180); unsigned long vltrack; if ((direct)&&(Vld)) //подъем допускается при выдвинутом положении { vltrack=millis(); for(;;) { //при сработке Vlv vlpmotor(0) и break; if (Vlv) { vlpmotor(0); vTaskDelay(200); if (Vlv) { vlpmotor(0); break; }} //при сработке таймера vlpmotor(0) и break; if ((millis()-vltrack)>26000) { vlpmotor(0); break; } vlpmotor(1); } } else if (!direct) //спуск { vltrack=millis(); for(;;) { //при сработке Vln vlpmotor(0) и break; if (Vln) { vlpmotor(0); vTaskDelay(200); if (Vln) { vlpmotor(0); break; }} //при сработке таймера vlpmotor(0) и break; if ((millis()-vltrack)>26000) { vlpmotor(0); break; } vlpmotor(2); } } } //выдвинуть и задвинуть верхний люк static void vlvz(boolean direct) { vTaskDelay(180); unsigned long vltrack; if ((direct)&&(Vln)) //выдвинуть { vltrack=millis(); for(;;) { //при сработке Vld vlzmotor(0) и break; if (Vld) { vlzmotor(0); vTaskDelay(200); if (Vld) { vlzmotor(0); break; }} //при сработке таймера vlzmotor(0) и break; if ((millis()-vltrack)>30000) { vlzmotor(0); break; } vlzmotor(1); } } else if ((!direct)&&(Vln)) //задвинуть { vltrack=millis(); for(;;) { //при сработке Vlz vlzmotor(0) и break; if (Vlz) { vlzmotor(0); vTaskDelay(200); if (Vlz) { vlzmotor(0); break; }} //при сработке таймера vlzmotor(0) и break; if ((millis()-vltrack)>30000) { vlzmotor(0); break; } vlzmotor(2); } } } //открыть и закрыть замок крышки KR0 static void lockKR0(boolean direct) { vTaskDelay(180); unsigned long zmtrack; if (direct) //открыть { zmtrack=millis(); for(;;) { if (KR0o) { motKR0(0); vTaskDelay(200); if (KR0o) { motKR0(0); break; }} if ((millis()-zmtrack)>3500) { motKR0(0); break; } motKR0(1); } } else //закрыть { zmtrack=millis(); for(;;) { if (KR0c) { motKR0(0); vTaskDelay(200); if (KR0c) { motKR0(0); break; }} if ((millis()-zmtrack)>3500) { motKR0(0); break; } motKR0(2); } } } //открыть или закрыть люк отсека выдачи static void ovopcl(boolean direct) { vTaskDelay(180); unsigned long ovtrack; if ((direct)&&(!ovv)) //открыть { OprSt=""bottom hatch opening.. .""; ovsolenoid(1); vTaskDelay(1200); ovsolenoid(0); vTaskDelay(1000); ovsolenoid(1); vTaskDelay(1200); ovsolenoid(0); vTaskDelay(1000); ovsolenoid(1); vTaskDelay(1900); ovtrack=millis(); for(;;) { //при сработке ovv ovmotor(0) и break; if (ovv) { ovmotor(0); vTaskDelay(200); if (ovv) { ovmotor(0); break; }} //при сработке таймера ovmotor(0) и break; if ((millis()-ovtrack)>22000) { ovmotor(0); break; } ovmotor(1); } vTaskDelay(1000); ovsolenoid(0); vTaskDelay(1000); OprSt=""bottom hatch open OK""; } else if ((!direct)&&(!ovn)) //закрыть { OprSt=""bottom hatch closing.. .""; ovsolenoid(1); vTaskDelay(1200); ovsolenoid(0); vTaskDelay(1000); ovsolenoid(1); vTaskDelay(1200); ovsolenoid(0); vTaskDelay(1000); ovsolenoid(1); vTaskDelay(1900); ovtrack=millis(); for(;;) { //при сработке ovn ovmotor(0) и break; if (ovn) { ovmotor(0); vTaskDelay(200); if (ovn) { ovmotor(0); break; }} //при сработке таймера ovmotor(0) и break; if ((millis()-ovtrack)>22000) { ovmotor(0); break; } ovmotor(2); } vTaskDelay(1000); ovsolenoid(0); vTaskDelay(1000); OprSt=""bottom hatch close OK""; } } //установка крышки в зарядку static void CoverInst() { vTaskDelay(180); if ((!KR0n)&&(pKR==""KR0"")&&((cnt1)||(cnt2))) { OprSt=""coverKR0 installed.. .""; vTaskDelay(120); lockKR0(1);//открываем замок Z4Block(); //Z4 уровень крышек lockKR0(0);//закрываем замок tempmoveZ=""nazad""; vTaskDelay(120); Z3Block(); //Z3 уровень Y2Block(); OprSt=""coverKR0 installed OK""; } } //снятие крышки c зарядки //здесь необходима также проверка крышки на контейнере static void CoverUninst() { vTaskDelay(180); if ((KR0n)&&(pKR==""KR0"")&&((cnt1)||(cnt2))) { OprSt=""coverKR0 uninstalled.. .""; vTaskDelay(120); Z4Block(); //Z4 уровень крышек vTaskDelay(120); lockKR0(1); //открываем замок vTaskDelay(120); tempmoveZ=""nazad""; Z3Block(); //Z3 уровень lockKR0(0); //закрываем замок Y2Block(); OprSt=""coverKR0 uninstalled OK""; } } //вставка контейнера в коптер static void contenerUP() { vTaskDelay(180); if ((Vln)&&(Vlz)&&(pDN)&&((cnt1)||(cnt2))) { OprSt=""insert container.. .""; servLockCon(1); vTaskDelay(300); servLockCon(0); //открыть замок контейнера vTaskDelay(910); Y2Block(); vTaskDelay(200); Z5Block(); //Z5 уровень коптера vTaskDelay(200); servLockCon(1); //закрыть замок контейнера vTaskDelay(1500); tempmoveZ=""nazad""; Z3Block(); //Z3 уровень Y2Block(); OprSt=""insert container OK""; } } //снятие контейнера из коптера static void contenerDN() { vTaskDelay(180); if ((Vln)&&(Vlz)&&(pDN)&&(!cnt1)&&(!cnt2)) { OprSt=""removing container.. .""; Y2Block(); vTaskDelay(200); Z5Block(); //Z5 уровень коптера servLockCon(0); //открыть замок контейнера vTaskDelay(1500); tempmoveZ=""nazad""; Z3Block(); //Z3 уровень Y2Block(); vTaskDelay(350); servLockCon(1); OprSt=""removing container OK""; } } //проверка вольт сенсоров крышек static void vVsensTask(void *pvParameters) { vTaskDelay(402); for (;;) { ADCkr0=analogRead(pADCkr0); uint8_t i=0; for (i; i<9; i++) { ADCkr0+=(analogRead(pADCkr0)); vTaskDelay(44); } ADCkr0=ADCkr0/10; //переводим в вольты ADCkr0=ADCkr0*vsensc; if (KR0n) { sprintf(VBkr0, ""VBAT=%.2f"", ADCkr0); } else { sprintf(VBkr0, ""none""); } //sprintf(vdKr3, ""VBATKr3=%.2f"", ADCkr3); vTaskDelay(700); } } //проверка состояния весов static void vScaleTask(void *pvParameters) { vTaskDelay(311); for (;;) { scale.set_scale(calibration_factor); units=scale.get_units(), 10; if (units<0) { units=0.00; } units=units*0.035274; //унции в граммы units=units-360; //не учитываем вес контейнера if (units<0) { units=0.00; } if ((KZ0)&&(KX0)) //отсек выдачи { if (units>2000) { Vm=0; } //запрещенно else { Vm=1; } //разрешенно } else { Vm=1; } //разрешенно outkg=units; //if ((Vo)&&(Vm)) { VD=1; rgbLn(0); } //разрешенно //else { VD=0; rgbLn(1); } //запрещенно vTaskDelay(500); } } //лазерная система контроля объема static void vLaserTask(void *pvParameters) { vTaskDelay(315); unsigned long lzDt1,lzDt2,lzDt3,lzDt4,lzDt5,lzDt6,lzDt7,lzDt8; for (;;) { if ((KZ0)&&(KX0)) //отсек выдачи { digitalWrite(pLaz, HIGH); //вкл лазер vTaskDelay(400); lzDt1=analogRead(pADClz1); lzDt2=analogRead(pADClz2); lzDt3=analogRead(pADClz3); lzDt4=analogRead(pADClz4); lzDt5=analogRead(pADClz5); lzDt6=analogRead(pADClz6); lzDt7=analogRead(pADClz7); lzDt8=analogRead(pADClz8); uint8_t i=0; for (i; i<9; i++) { lzDt1+=(analogRead(pADClz1)); lzDt2+=(analogRead(pADClz2)); lzDt3+=(analogRead(pADClz3)); lzDt4+=(analogRead(pADClz4)); lzDt5+=(analogRead(pADClz5)); lzDt6+=(analogRead(pADClz6)); lzDt7+=(analogRead(pADClz7)); lzDt8+=(analogRead(pADClz8)); vTaskDelay(44); } lzDt1=lzDt1/10; lzDt2=lzDt2/10; lzDt3=lzDt3/10; lzDt4=lzDt4/10; lzDt5=lzDt5/10; lzDt6=lzDt6/10; lzDt7=lzDt7/10; lzDt8=lzDt8/10; //if ( (lzDt1>2800)||(lzDt2>2800)||(lzDt3>2800)||(lzDt4>2800)|| // (lzDt5>2800)||(lzDt6>2800)||(lzDt7>2800)||(lzDt8>2800) ) // { Vo=0; } //запрещенно if ((lzDt1>2800)||(lzDt2>2800)) { Vo=1; } //разрешенно else { Vo=1; } //разрешенно digitalWrite(pLaz, LOW); //выкл лазер vTaskDelay(200); } else { digitalWrite(pLaz, LOW); //выкл лазер Vo=1; //разрешенно //lzDt1=analogRead(pADClz1); //lzDt2=analogRead(pADClz2); //vTaskDelay(200); //Serial.println(lzDt1); //Serial.println(lzDt2); vTaskDelay(800); } //if ((Vo)&&(Vm)) { VD=1; rgbLn(0); } //разрешенно //else { VD=0; rgbLn(1); } //запрещенно } } //счетчик комманд static void cmnum() { cnum+=1; if (cnum>250) { cnum=0; } } //загрузка в отсек выдачи static void loadSlot() { if (pOV) { OprSt=""load slot issue.. .""; zagruzkaKP(); vTaskDelay(1500); ovopcl(1); //открыть отсек выдачи OprSt=""load slot issue OK""; } } //выгрузка из отсека выдачи static void uploadSlot() { if (pOV) { OprSt=""upload slot issue.. .""; vygruzkaKP(); vTaskDelay(1500); OprSt=""upload slot issue OK""; } } //мониторинг активного состояния AcSpec и запуск функций static void vSpecOpr(void *pvParameters) { for (;;) { if ((AcSpec==""vkp"")&&(gSem==0)) { gSem=1; vygruzkaKP(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""vkz"")&&(gSem==0)) { gSem=1; vygruzkaKZ(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""zkp"")&&(gSem==0)) { gSem=1; zagruzkaKP(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""zkz"")&&(gSem==0)) { gSem=1; zagruzkaKZ(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""openVL"")&&(gSem==0)) { gSem=1; openVL(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""closeVL"")&&(gSem==0)) { gSem=1; closeVL(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""vkf"")&&(gSem==0)) { gSem=1; unloadingCELL(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""zkf"")&&(gSem==0)) { gSem=1; loadingCELL(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""ovo"")&&(gSem==0)) { gSem=1; ovopcl(1); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""ovc"")&&(gSem==0)) { gSem=1; ovopcl(0); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""CUninst"")&&(gSem==0)) { gSem=1; CoverUninst(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""CInst"")&&(gSem==0)) { gSem=1; CoverInst(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""CUP"")&&(gSem==0)) { gSem=1; contenerUP(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""CDN"")&&(gSem==0)) { gSem=1; contenerDN(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""loadSlot"")&&(gSem==0)) { gSem=1; loadSlot(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""uploadSlot"")&&(gSem==0)) { gSem=1; uploadSlot(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""cmOpld"")&&(gSem==0)) { gSem=1; cmOpld(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""cmOpud"")&&(gSem==0)) { gSem=1; cmOpud(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""cmOpuntu"")&&(gSem==0)) { gSem=1; cmOpuntu(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""cmOpgetfu"")&&(gSem==0)) { gSem=1; cmOpgetfu(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""cmOcls"")&&(gSem==0)) { gSem=1; cmOcls(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""cmOopn"")&&(gSem==0)) { gSem=1; cmOopn(); AcSpec=""none""; gSem=0; cmnum(); } else if ((AcSpec==""cmOchan"")&&(gSem==0)) { gSem=1; cmOchan(); AcSpec=""none""; gSem=0; cmnum(); } vTaskDelay(120); } }",8148,False,1362.0075253200698,median " // Use these for links to issue and pulls. Note issues and pulls redirect one to // each other on Github, so don't worry too much on using the right prefix. :issue: https://github.com/elastic/beats/issues/ :pull: https://github.com/elastic/beats/pull/ //////////////////////////////////////////////////////////// // Template, add newest changes here === Beats version HEAD https://github.com/elastic/beats/compare/v5.0.0...master[Check the HEAD diff] ==== Breaking changes *Affecting all Beats* *Metricbeat* *Packetbeat* *Topbeat* *Filebeat* *Winlogbeat* ==== Bugfixes *Affecting all Beats* *Metricbeat* - Calculate the fsstat values per mounting point, and not filesystem. {pull}2777[2777] - Fix `system.process.start_time` on Windows. {pull}2848[2848] - Fix `system.process.ppid` on Windows. {issue}2860[2860] - Fix system process metricset for Windows XP and 2003. `cmdline` will be unavailable. {issue}1704[1704] - Fix access denied issues in system process metricset by enabling SeDebugPrivilege on Windows. {issue}1897[1897] - Fix system diskio metricset for Windows XP and 2003. {issue}2885[2885] *Packetbeat* - Fix 'index out of bounds' bug in Packetbeat DNS protocol plugin. {issue}2872[2872] *Topbeat* *Filebeat* - Fix registry cleanup issue when files falling under ignore_older after restart. {issue}2818[2818] *Winlogbeat* ==== Added *Affecting all Beats* - Add add_cloud_metadata processor for collecting cloud provider metadata. {pull}2728[2728] *Metricbeat* - Add experimental filebeat metricset in the beats module. {pull}2297[2297] - Add experimental libbeat metricset in the beats module. {pull}2339[2339] - Add experimental docker module. Provided by Ingensi and @douaejeouit based on dockbeat. - Add username and password config options to the MongoDB module. {pull}2889[2889] - Add system core metricset for Windows. {pull}2883}[2883] *Packetbeat* - Define `client_geoip.location` as geo_point in the mappings to be used by the GeoIP processor in the Ingest Node pipeline. {pull}2795[2795] *Topbeat* *Filebeat* - Add command line option -once to run filebeat only once and then close. {pull}2456[2456] - Only load matching states into prospector to improve state handling {pull}2840[2840] - Reset all states ttl on startup to make sure it is overwritten by new config {pull}2840[2840] *Winlogbeat* - Add `event_logs.batch_read_size` configuration option. {pull}2641[2641] ==== Deprecated *Affecting all Beats* *Metricbeat* *Packetbeat* *Topbeat* *Filebeat* *Winlogbeat* //////////////////////////////////////////////////////////// include::libbeat/docs/release-notes/5.0.0.asciidoc[] [[release-notes-5.0.0-ga]] === Beats version 5.0.0-GA https://github.com/elastic/beats/compare/v5.0.0-rc1...v5.0.0[View commits] The list below covers the changes between 5.0.0-rc1 and 5.0.0 GA only. ==== Bugfixes *Affecting all Beats* - Fix kafka output re-trying batches with too large events. {issue}2735[2735] - Fix kafka output protocol error if `version: 0.10` is configured. {issue}2651[2651] - Fix kafka output connection closed by broker on SASL/PLAIN. {issue}2717[2717] *Metricbeat* - Fix high CPU usage on macOS when encountering processes with long command lines. {issue}2747[2747] - Fix high value of `system.memory.actual.free` and `system.memory.actual.used`. {issue}2653[2653] - Change several `OpenProcess` calls on Windows to request the lowest possible access provilege. {issue}1897[1897] - Fix system.memory.actual.free high value on Windows. {issue}2653[2653] *Filebeat* - Fix issue when clean_removed and clean_inactive were used together that states were not directly removed from the registry. - Fix issue where upgrading a 1.x registry file resulted in duplicate state entries. {pull}2792[2792] ==== Added *Affecting all Beats* - Add beat.version fields to all events. [[release-notes-5.0.0-rc1]] === Beats version 5.0.0-rc1 https://github.com/elastic/beats/compare/v5.0.0-beta1...v5.0.0-rc1[View commits] ==== Breaking changes *Affecting all Beats* - A dynamic mapping rule is added to the default Elasticsearch template to treat strings as keywords by default. {pull}2688[2688] ==== Bugfixes *Affecting all Beats* - Make sure Beats sent always float values when they are defined as float by sending 5.00000 instead of 5. {pull}2627[2627] - Fix ignoring all fields from drop_fields in case the first field is unknown. {pull}2685[2685] - Fix dynamic configuration int/uint to float type conversion. {pull}2698[2698] - Fix primitive types conversion if values are read from environment variables. {pull}2698[2698] *Metricbeat* - Fix default configuration file on Windows to not enabled the `load` metricset. {pull}2632[2632] *Packetbeat* - Fix the `bpf_filter` setting. {issue}2660[2660] *Filebeat* - Fix input buffer on encoding problem. {pull}2416[2416] ==== Deprecated *Affecting all Beats* - Setting `port` has been deprecated in Redis and Logstash outputs. {pull}2620[2620] [[release-notes-5.0.0-beta1]] === Beats version 5.0.0-beta1 https://github.com/elastic/beats/compare/v5.0.0-alpha5...v5.0.0-beta1[View commits] ==== Breaking changes *Affecting all Beats* - Change Elasticsearch output index configuration to be based on format strings. If index has been configured, no date will be appended anymore to the index name. {pull}2119[2119] - Replace `output.kafka.use_type` by `output.kafka.topic` accepting a format string. {pull}2188[2188] - If the path specified by the `-c` flag is not absolute and `-path.config` is not specified, it is considered relative to the current working directory. {pull}2245[2245] - rename `tls` configurations section to `ssl`. {pull}2330[2330] - rename `certificate_key` configuration to `key`. {pull}2330[2330] - replace `tls.insecure` with `ssl.verification_mode` setting. {pull}2330[2330] - replace `tls.min/max_version` with `ssl.supported_protocols` setting requiring full protocol name. {pull}2330[2330] *Metricbeat* - Change field type system.process.cpu.start_time from keyword to date. {issue}1565[1565] - redis/info metricset fields were renamed up according to the naming conventions. *Packetbeat* - Group HTTP fields under `http.request` and `http.response` {pull}2167[2167] - Export `http.request.body` and `http.response.body` when configured under `include_body_for` {pull}2167[2167] - Move `ignore_outgoing` config to `packetbeat.ignore_outgoing` {pull}2393[2393] *Filebeat* - Set close_inactive default to 5 minutes (was 1 hour before) - Set clean_removed and close_removed to true by default ==== Bugfixes *Affecting all Beats* - Fix logstash output handles error twice when asynchronous sending fails. {pull}2441[2441] - Fix Elasticsearch structured error response parsing error. {issue}2229[2229] - Fixed the run script to allow the overriding of the configuration file. {issue}2171[2171] - Fix logstash output crash if no hosts are configured. {issue}2325[2325] - Fix array value support in -E CLI flag. {pull}2521[2521] - Fix merging array values if -c CLI flag is used multiple times. {pull}2521[2521] - Fix beats failing to start due to invalid duplicate key error in configuration file. {pull}2521[2521] - Fix panic on non writable logging directory. {pull}2571[2571] *Metricbeat* - Fix module filters to work properly with drop_event filter. {issue}2249[2249] *Packetbeat* - Fix mapping for some Packetbeat flow metrics that were not marked as being longs. {issue}2177[2177] - Fix handling of messages larger than the maximum message size (10MB). {pull}2470[2470] *Filebeat* - Fix processor failure in Filebeat when using regex, contain, or equals with the message field. {issue}2178[2178] - Fix async publisher sending empty events {pull}2455[2455] - Fix potential issue with multiple harvester per file on large file numbers or slow output {pull}2541[2541] *Winlogbeat* - Fix corrupt registry file that occurs on power loss by disabling file write caching. {issue}2313[2313] ==== Added *Affecting all Beats* - Add script to generate the Kibana index-pattern from fields.yml. {pull}2122[2122] - Enhance Redis output key selection based on format string. {pull}2169[2169] - Configurable Redis `keys` using filters and format strings. {pull}2169[2169] - Add format string support to `output.kafka.topic`. {pull}2188[2188] - Add `output.kafka.topics` for more advanced kafka topic selection per event. {pull}2188[2188] - Add support for Kafka 0.10. {pull}2190[2190] - Add SASL/PLAIN authentication support to kafka output. {pull}2190[2190] - Make Kafka metadata update configurable. {pull}2190[2190] - Add Kafka version setting (optional) enabling kafka broker version support. {pull}2190[2190] - Add Kafka message timestamp if at least version 0.10 is configured. {pull}2190[2190] - Add configurable Kafka event key setting. {pull}2284[2284] - Add settings for configuring the kafka partitioning strategy. {pull}2284[2284] - Add partitioner settings `reachable_only` to ignore partitions not reachable by network. {pull}2284[2284] - Enhance contains condition to work on fields that are arrays of strings. {issue}2237[2237] - Lookup the configuration file relative to the `-path.config` CLI flag. {pull}2245[2245] - Re-write import_dashboards.sh in Golang. {pull}2155[2155] - Update to Go 1.7. {pull}2306[2306] - Log total non-zero internal metrics on shutdown. {pull}2349[2349] - Add support for encrypted private key files by introducing `ssl.key_passphrase` setting. {pull}2330[2330] - Add experimental symlink support with `symlinks` config {pull}2478[2478] - Improve validation of registry file on startup. *Metricbeat* - Use the new scaled_float Elasticsearch type for the percentage values. {pull}2156[2156] - Add experimental cgroup metrics to the system/process MetricSet. {pull}2184[2184] - Added a PostgreSQL module. {pull}2253[2253] - Improve mapping by converting half_float to scaled_float and integers to long. {pull}2430[2430] - Add experimental haproxy module. {pull}2384[2384] - Add Kibana dashboard for cgroups data {pull}2555[2555] *Packetbeat* - Add Cassandra protocol analyzer to Packetbeat. {pull}1959[1959] - Match connections with IPv6 addresses to processes {pull}2254[2254] - Add IP address to -devices command output {pull}2327[2327] - Add configuration option for the maximum message size. Used to be hard-coded to 10 MB. {pull}2470[2470] *Filebeat* - Introduce close_timeout harvester options {issue}1926[1926] - Strip BOM from first message in case of BOM files {issue}2351[2351] - Add harvester_limit option {pull}2417[2417] ==== Deprecated *Affecting all Beats* - Topology map is deprecated. This applies to the settings: refresh_topology_freq, topology_expire, save_topology, host_topology, password_topology, db_topology. [[release-notes-5.0.0-alpha5]] === Beats version 5.0.0-alpha5 https://github.com/elastic/beats/compare/v5.0.0-alpha4...v5.0.0-alpha5[View commits] ==== Breaking changes *Affecting all Beats* - Rename the `filters` section to `processors`. {pull}1944[1944] - Introduce the condition with `when` in the processor configuration. {pull}1949[1949] - The Elasticsearch template is now loaded by default. {pull}1993[1993] - The Redis output `index` setting is renamed to `key`. `index` still works but it's deprecated. {pull}2077[2077] - The undocumented file output `index` setting was removed. Use `filename` instead. {pull}2077[2077] *Metricbeat* - Create a separate metricSet for load under the system module and remove load information from CPU stats. {pull}2101[2101] - Add `system.load.norm.1`, `system.load.norm.5` and `system.load.norm.15`. {pull}2101[2101] - Add threads fields to mysql module. {pull}2484[2484] *Packetbeat* - Set `enabled` ` in `packetbeat.protocols.icmp` configuration to `true` by default. {pull}1988[1988] ==== Bugfixes *Affecting all Beats* - Fix sync publisher `PublishEvents` return value if client is closed concurrently. {pull}2046[2046] *Metricbeat* - Do not send zero values when no value was present in the source. {issue}1972[1972] *Filebeat* - Fix potential data loss between Filebeat restarts, reporting unpublished lines as published. {issue}2041[2041] - Fix open file handler issue. {issue}2028[2028] {pull}2020[2020] - Fix filtering of JSON events when using integers in conditions. {issue}2038[2038] *Winlogbeat* - Fix potential data loss between Winlogbeat restarts, reporting unpublished lines as published. {issue}2041[2041] ==== Added *Affecting all Beats* - Periodically log internal metrics. {pull}1955[1955] - Add enabled setting to all output modules. {pull}1987[1987] - Command line flag `-c` can be used multiple times. {pull}1985[1985] - Add OR/AND/NOT to the condition associated with the processors. {pull}1983[1983] - Add `-E` CLI flag for overwriting single config options via command line. {pull}1986[1986] - Choose the mapping template file based on the Elasticsearch version. {pull}1993[1993] - Check stdout being available when console output is configured. {issue}2035[2035] *Metricbeat* - Add pgid field to process information. {pull} 2021[2021] *Packetbeat* - Add enabled setting to Packetbeat protocols. {pull}1988[1988] - Add enabled setting to Packetbeat network flows configuration. {pull}1988[1988] *Filebeat* - Introduce `close_removed` and `close_renamed` harvester options. {issue}1600[1600] - Introduce `close_eof` harvester option. {issue}1600[1600] - Add `clean_removed` and `clean_inactive` config option. {issue}1600[1600] ==== Deprecated *Filebeat* - Deprecate `close_older` option and replace it with `close_inactive`. {issue}2051[2051] - Deprecate `force_close_files` option and replace it with `close_removed` and `close_renamed`. {issue}1600[1600] [[release-notes-5.0.0-alpha4]] === Beats version 5.0.0-alpha4 https://github.com/elastic/beats/compare/v5.0.0-alpha3...v5.0.0-alpha4[View commits] ==== Breaking changes *Affecting all Beats* - The topology_expire option of the Elasticserach output was removed. {pull}1907[1907] *Filebeat* - Stop following symlink. Symlinks are now ignored: {pull}1686[1686] ==== Bugfixes *Affecting all Beats* - Reset backoff factor on partial ACK. {issue}1803[1803] - Fix beats load balancer deadlock if max_retries: -1 or publish_async is enabled in filebeat. {issue}1829[1829] - Fix logstash output with pipelining mode enabled not reconnecting. {issue}1876[1876] - Empty configuration sections become merge-able with variables containing full path. {pull}1900[1900] - Fix error message about required fields missing not printing the missing field name. {pull}1900[1900] *Metricbeat* - Fix the CPU values returned for each core. {issue}1863[1863] *Packetbeat* - Add missing nil-check to memcached GapInStream handler. {issue}1162[1162] - Fix NFSv4 Operation returning the first found first-class operation available in compound requests. {pull}1821[1821] - Fix TCP overlapping segments not being handled correctly. {pull}1898[1898] *Winlogbeat* - Fix issue with rendering forwarded event log records. {pull}1891[1891] ==== Added *Affecting all Beats* - Improve error message if compiling regular expression from config files fails. {pull}1900[1900] - Compression support in the Elasticsearch output. {pull}1835[1835] *Metricbeat* - Add MongoDB module. {pull}1837[1837] [[release-notes-5.0.0-alpha3]] === Beats version 5.0.0-alpha3 https://github.com/elastic/beats/compare/v5.0.0-alpha2...v5.0.0-alpha3[View commits] ==== Breaking changes *Affecting all Beats* - All configuration settings under `shipper:` are moved to be top level configuration settings. I.e. `shipper.name:` becomes `name:` in the configuration file. {pull}1570[1570] *Topbeat* - Topbeat is replaced by Metricbeat. *Filebeat* - The state for files which fall under ignore_older is not stored anymore. This has the consequence, that if a file which fell under ignore_older is updated, the whole file will be crawled. ==== Bugfixes *Winlogbeat* - Adding missing argument to the ""Stop processing"" log message. {pull}1590[1590] ==== Added *Affecting all Beats* - Add conditions to generic filtering. {pull}1623[1623] *Metricbeat* - First public release, containing the following modules: apache, mysql, nginx, redis, system, and zookeeper. *Filebeat* - The registry format was changed to an array instead of dict. The migration to the new format will happen automatically at the first startup. {pull}1703[1703] ==== Deprecated *Affecting all Beats* - The support for doing GeoIP lookups is deprecated and will be removed in version 6.0. {pull}1601[1601] [[release-notes-5.0.0-alpha2]] === Beats version 5.0.0-alpha2 https://github.com/elastic/beats/compare/v5.0.0-alpha1...v5.0.0-alpha2[View commits] ==== Breaking changes *Affecting all Beats* - On DEB/RPM installations, the binary files are now found under `/usr/share/{{beat_name}}/bin`, not in `/usr/bin`. {pull}1385[1385] - The logs are written by default to self rotating files, instead of syslog. {pull}1371[1371] - Remove deprecated `host` option from elasticsearch, logstash and redis outputs. {pull}1474[1474] *Packetbeat* - Configuration of redis topology support changed. {pull}1353[1353] - Move all Packetbeat configuration options under the packetbeat namespace {issue}1417[1417] *Filebeat* - Default location for the registry file was changed to be `data/registry` from the binary directory, rather than `.filebeat` in the current working directory. This affects installations for zip/tar.gz/source, the location for DEB and RPM packages stays the same. {pull}1373[1373] ==== Bugfixes *Affecting all Beats* - Drain response buffers when pipelining is used by Redis output. {pull}1353[1353] - Unterminated environment variable expressions in config files will now cause an error {pull}1389[1389] - Fix issue with the automatic template loading when Elasticsearch is not available on Beat start. {issue}1321[1321] - Fix bug affecting -cpuprofile, -memprofile, and -httpprof CLI flags {pull}1415[1415] - Fix race when multiple outputs access the same event with logstash output manipulating event {issue}1410[1410] {pull}1428[1428] - Seed random number generator using crypto.rand package. {pull}1503{1503] - Fix beats hanging in -configtest {issue}1213[1213] - Fix kafka log message output {pull}1516[1516] *Filebeat* - Improvements in registrar dealing with file rotation. {pull}1281[1281] - Fix issue with JSON decoding where `@timestamp` or `type` keys with the wrong type could cause Filebeat to crash. {issue}1378[1378] - Fix issue with JSON decoding where values having `null` as values could crash Filebeat. {issue}1466[1466] - Multiline reader normalizing newline to use `\\n`. {pull}1552[1552] *Winlogbeat* - Fix panic when reading messages larger than 32K characters on Windows XP and 2003. {pull}1498[1498] - Fix panic that occurs when reading a large events on Windows Vista and newer. {pull}1499[1499] ==== Added *Affecting all Beats* - Add support for TLS to Redis output. {pull}1353[1353] - Add SOCKS5 proxy support to Redis output. {pull}1353[1353] - Failover and load balancing support in redis output. {pull}1353[1353] - Multiple-worker per host support for redis output. {pull}1353[1353] - Added ability to escape `${x}` in config files to avoid environment variable expansion {pull}1389[1389] - Configuration options and CLI flags for setting the home, data and config paths. {pull}1373[1373] - Configuration options and CLI flags for setting the default logs path. {pull}1437[1437] - Update to Go 1.6.2 {pull}1447[1447] - Add Elasticsearch template files compatible with Elasticsearch 2.x. {pull}1501[1501] - Add scripts for managing the dashboards of a single Beat {pull}1359[1359] *Packetbeat* - Fix compile issues for OpenBSD. {pull}1347[1347] *Topbeat* - Updated elastic/gosigar version so Topbeat can compile on OpenBSD. {pull}1403[1403] [[release-notes-5.0.0-alpha1]] === Beats version 5.0.0-alpha1 https://github.com/elastic/beats/compare/v1.2.0...v5.0.0-alpha1[View commits] ==== Breaking changes *libbeat* - Run function to start a Beat now returns an error instead of directly exiting. {pull}771[771] - The method signature of HandleFlags() was changed to allow returning an error {pull}1249[1249] - Require braces for environment variable expansion in config files {pull}1304[1304] *Packetbeat* - Rename output fields in the dns package. Former flag `recursion_allowed` becomes `recursion_available`. {pull}803[803] Former SOA field `ttl` becomes `minimum`. {pull}803[803] - The fully qualified domain names which are part of output fields values of the dns package now terminate with a dot. {pull}803[803] - Remove the count field from the exported event {pull}1210[1210] *Topbeat* - Rename `proc.cpu.user_p` with `proc.cpu.total_p` as it includes CPU time spent in kernel space {pull}631[631] - Remove `count` field from the exported fields {pull}1207[1207] - Rename `input` top level config option to `topbeat` *Filebeat* - Scalar values in used in the `fields` configuration setting are no longer automatically converted to strings. {pull}1092[1092] - Count field was removed from event as not used in filebeat {issue}778[778] *Winlogbeat* - The `message_inserts` field was replaced with the `event_data` field {issue}1053[1053] - The `category` field was renamed to `task` to better align with the Windows Event Log API naming {issue}1053[1053] - Remove the count field from the exported event {pull}1218[1218] ==== Bugfixes *Affecting all Beats* - Logstash output will not retry events that are not JSON-encodable {pull}927[927] *Packetbeat* - Create a proper BPF filter when ICMP is the only enabled protocol {issue}757[757] - Check column length in pgsql parser. {issue}565[565] - Harden pgsql parser. {issue}565[565] *Topbeat* - Fix issue with `cpu.system_p` being greater than 1 on Windows {pull}1128[1128] *Filebeat* - Stop filebeat if started without any prospectors defined or empty prospectors {pull}644[644] {pull}647[647] - Improve shutdown of crawler and prospector to wait for clean completion {pull}720[720] - Omit `fields` from Filebeat events when null {issue}899[899] *Winlogbeat* ==== Added *Affecting all Beats* - Update builds to Golang version 1.6 - Add option to Elasticsearch output to pass http parameters in index operations {issue}805[805] - Improve Logstash and Elasticsearch backoff behavior. {pull}927[927] - Add experimental Kafka output. {pull}942[942] - Add config file option to configure GOMAXPROCS. {pull}969[969] - Improve shutdown handling in libbeat. {pull}1075[1075] - Add `fields` and `fields_under_root` options under the `shipper` configuration {pull}1092[1092] - Add the ability to use a SOCKS5 proxy with the Logstash output {issue}823[823] - The `-configtest` flag will now print ""Config OK"" to stdout on success {pull}1249[1249] *Packetbeat* - Change the DNS library used throughout the dns package to github.com/miekg/dns. {pull}803[803] - Add support for NFS v3 and v4. {pull}1231[1231] - Add support for EDNS and DNSSEC. {pull}1292[1292] *Topbeat* - Add `username` to processes {pull}845[845] *Filebeat* - Add the ability to set a list of tags for each prospector {pull}1092[1092] - Add JSON decoding support {pull}1143[1143] *Winlogbeat* - Add caching of event metadata handles and the system render context for the wineventlog API {pull}888[888] - Improve config validation by checking for unknown top-level YAML keys. {pull}1100[1100] - Add the ability to set tags, fields, and fields_under_root as options for each event log {pull}1092[1092] - Add additional data to the events published by Winlogbeat. The new fields are `activity_id`, `event_data`, `keywords`, `opcode`, `process_id`, `provider_guid`, `related_activity_id`, `task`, `thread_id`, `user_data`, and `version`. {issue}1053[1053] - Add `event_id`, `level`, and `provider` configuration options for filtering events {pull}1218[1218] - Add `include_xml` configuration option for including the raw XML with the event {pull}1218[1218] ==== Known issues * All Beats can hang or panic on shutdown if the next server in the pipeline (e.g. Elasticsearch or Logstash) is not reachable. {issue}1319[1319] * When running the Beats as a service on Windows, you need to manually load the Elasticsearch mapping template. {issue}1315[1315] * The ES template automatic load doesn't work if Elasticsearch is not available when the Beat is starting. {issue}1321[1321] [[release-notes-1.3.1]] === Beats version 1.3.1 https://github.com/elastic/beats/compare/v1.3.0...v1.3.1[View commits] ==== Bugfixes *Filebeat* - Fix a concurrent bug on filebeat startup with a large number of prospectors defined. {pull}2509[2509] *Packetbeat* - Fix description for the -I CLI flag. {pull}2480[2480] *Winlogbeat* - Fix corrupt registry file that occurs on power loss by disabling file write caching. {issue}2313[2313] [[release-notes-1.3.0]] === Beats version 1.3.0 https://github.com/elastic/beats/compare/v1.2.3...v1.3.0[View commits] ==== Deprecated *Filebeat* - Undocumented support for following symlinks is deprecated. Filebeat will not follow symlinks in version 5.0. {pull}1767[1767] ==== Bugfixes *Affecting all Beats* - Fix beats load balancer deadlock if `max_retries: -1` or `publish_async` is enabled in filebeat. {issue}1829[1829] - Fix output modes backoff counter reset. {issue}1803[1803] {pull}1814[1814] {pull}1818[1818] - Set logstash output default bulk_max_size to 2048. {issue}1662[1662] - Seed random number generator using crypto.rand package. {pull}1503[1503] - Check stdout being available when console output is configured. {issue}2063[2063] *Packetbeat* - Add missing nil-check to memcached GapInStream handler. {issue}1162[1162] - Fix NFSv4 Operation returning the first found first-class operation available in compound requests. {pull}1821[1821] - Fix TCP overlapping segments not being handled correctly. {pull}1917[1917] ==== Added *Affecting all Beats* - Updated to Go 1.7 [[release-notes-1.2.3]] === Beats version 1.2.3 https://github.com/elastic/beats/compare/v1.2.2...v1.2.3[View commits] ==== Bugfixes *Topbeat* - Fix high CPU usage when using filtering under Windows. {pull}1598[1598] *Filebeat* - Fix rotation issue with ignore_older. {issue}1528[1528] *Winlogbeat* - Fix panic when reading messages larger than 32K characters on Windows XP and 2003. {pull}1498[1498] ==== Added *Filebeat* - Prevent file opening for files which reached ignore_older. {pull}1649[1649] [[release-notes-1.2.2]] === Beats version 1.2.2 https://github.com/elastic/beats/compare/v1.2.0...v1.2.2[View commits] ==== Bugfixes *Affecting all Beats* - Fix race when multiple outputs access the same event with Logstash output manipulating event. {issue}1410[1410] - Fix go-daemon (supervisor used in init scripts) hanging when executed over SSH. {issue}1394[1394] *Filebeat* - Improvements in registrar dealing with file rotation. {issue}1281[1281] [[release-notes-1.2.1]] === Beats version 1.2.1 https://github.com/elastic/beats/compare/v1.2.0...v1.2.1[View commits] ==== Breaking changes *Affecting all Beats* - Require braces for environment variable expansion in config files {pull}1304[1304] - Removed deprecation warning for the Redis output. {pull}1282[1282] *Topbeat* - Fixed name of the setting `stats.proc` to `stats.process` in the default configuration file. {pull}1343[1343] - Fix issue with cpu.system_p being greater than 1 on Windows {pull}1128[1128] ==== Added *Topbeat* - Add username to processes {pull}845[845] [[release-notes-1.2.0]] === Beats version 1.2.0 https://github.com/elastic/beats/compare/v1.1.2...v1.2.0[View commits] ==== Breaking changes *Filebeat* - Default config for ignore_older is now infinite instead of 24h, means ignore_older is disabled by default. Use close_older to only close file handlers. ==== Bugfixes *Packetbeat* - Split real_ip_header value when it contains multiple IPs {pull}1241[1241] *Winlogbeat* - Fix invalid `event_id` on Windows XP and Windows 2003 {pull}1227[1227] ==== Added *Affecting all Beats* - Add ability to override configuration settings using environment variables {issue}114[114] - Libbeat now always exits through a single exit method for proper cleanup and control {pull}736[736] - Add ability to create Elasticsearch mapping on startup {pull}639[639] *Topbeat* - Add the command line used to start processes {issue}533[533] *Filebeat* - Add close_older configuration option to complete ignore_older https://github.com/elastic/filebeat/issues/181[181] [[release-notes-1.1.2]] === Beats version 1.1.2 https://github.com/elastic/beats/compare/v1.1.1...v1.1.2[View commits] ==== Bugfixes *Filebeat* - Fix registrar bug for rotated files {pull}1010[1010] [[release-notes-1.1.1]] === Beats version 1.1.1 https://github.com/elastic/beats/compare/v1.1.0...v1.1.1[View commits] ==== Bugfixes *Affecting all Beats* - Fix logstash output loop hanging in infinite loop on too many output errors. {pull}944[944] - Fix critical bug in filebeat and winlogbeat potentially dropping events. {pull}953[953] [[release-notes-1.1.0]] === Beats version 1.1.0 https://github.com/elastic/beats/compare/v1.0.1...v1.1.0[View commits] ==== Bugfixes *Affecting all Beats* - Fix logging issue with file based output where newlines could be misplaced during concurrent logging {pull}650[650] - Reduce memory usage by separate queue sizes for single events and bulk events. {pull}649[649] {issue}516[516] - Set default default bulk_max_size value to 2048 {pull}628[628] *Packetbeat* - Fix setting direction to out and use its value to decide when dropping events if ignore_outgoing is enabled {pull}557[557] - Fix logging issue with file-based output where newlines could be misplaced during concurrent logging {pull}650[650] - Reduce memory usage by having separate queue sizes for single events and bulk events. {pull}649[649] {issue}516[516] - Set default bulk_max_size value to 2048 {pull}628[628] - Fix logstash window size of 1 not increasing. {pull}598[598] *Packetbeat* - Fix the condition that determines whether the direction of the transaction is set to ""outgoing"". Packetbeat uses the direction field to determine which transactions to drop when dropping outgoing transactions. {pull}557[557] - Allow PF_RING sniffer type to be configured using pf_ring or pfring {pull}671[671] *Filebeat* - Set spool_size default value to 2048 {pull}628[628] ==== Added *Affecting all Beats* - Add include_fields and drop_fields as part of generic filtering {pull}1120[1120] - Make logstash output compression level configurable. {pull}630[630] - Some publisher options refactoring in libbeat {pull}684[684] - Move event preprocessor applying GeoIP to packetbeat {pull}772[772] *Packetbeat* - Add support for capturing DNS over TCP network traffic. {pull}486[486] {pull}554[554] *Topbeat* - Group all CPU usage per core statistics and export them optionally if cpu_per_core is configured {pull}496[496] *Filebeat* - Add multiline support for combining multiple related lines into one event. {issue}461[461] - Add `exclude_lines` and `include_lines` options for regexp based line filtering. {pull}430[430] - Add `exclude_files` configuration option. {pull}563[563] - Add experimental option to enable filebeat publisher pipeline to operate asynchonrously {pull}782[782] *Winlogbeat* - First public release of Winlogbeat [[release-notes-1.0.1]] === Beats version 1.0.1 https://github.com/elastic/beats/compare/v1.0.0...v1.0.1[Check 1.0.1 diff] ==== Bugfixes *Filebeat* - Fix force_close_files in case renamed file appeared very fast. https://github.com/elastic/filebeat/pull/302[302] *Packetbeat* - Improve MongoDB message correlation. {issue}377[377] - Improve redis parser performance. {issue}442[422] - Fix panic on nil in redis protocol parser. {issue}384[384] - Fix errors redis parser when messages are split in multiple TCP segments. {issue}402[402] - Fix errors in redis parser when length prefixed strings contain sequences of CRLF. {issue}#402[402] - Fix errors in redis parser when dealing with nested arrays. {issue}402[402] [[release-notes-1.0.0]] === Beats version 1.0.0 https://github.com/elastic/beats/compare/1.0.0-rc2...1.0.0[Check 1.0.0 diff] ==== Breaking changes *Topbeat* - Change proc type to process #138 ==== Bugfixes *Affecting all Beats* - Fix random panic on shutdown by calling shutdown handler only once. elastic/filebeat#204 - Fix credentials are not send when pinging an elasticsearch host. elastic/fileabeat#287 *Filebeat* - Fix problem that harvesters stopped reading after some time and filebeat stopped processing events #257 - Fix line truncating by internal buffers being reused by accident #258 - Set default ignore_older to 24 hours #282 [[release-notes-1.0.0-rc2]] === Beats version 1.0.0-rc2 https://github.com/elastic/beats/compare/1.0.0-rc1...1.0.0-rc2[Check 1.0.0-rc2 diff] ==== Breaking changes *Affecting all Beats* - The `shipper` output field is renamed to `beat.name`. #285 - Use of `enabled` as a configuration option for outputs (elasticsearch, logstash, etc.) has been removed. #264 - Use of `disabled` as a configuration option for tls has been removed. #264 - The `-test` command line flag was renamed to `-configtest`. #264 - Disable geoip by default. To enable it uncomment in config file. #305 *Filebeat* - Removed utf-16be-bom encoding support. Support will be added with fix for #205 - Rename force_close_windows_files to force_close_files and make it available for all platforms. ==== Bugfixes *Affecting all Beats* - Disable logging to stderr after configuration phase. #276 - Set the default file logging path when not set in config. #275 - Fix bug silently dropping records based on current window size. elastic/filebeat#226 - Fix direction field in published events. #300 - Fix elasticsearch structured errors breaking error handling. #309 *Packetbeat* - Packetbeat will now exit if a configuration error is detected. #357 - Fixed an issue handling DNS requests containing no questions. #369 *Topbeat* - Fix leak of Windows handles. #98 - Fix memory leak of process information. #104 *Filebeat* - Filebeat will now exit if a configuration error is detected. #198 - Fix to enable prospector to harvest existing files that are modified. #199 - Improve line reading and encoding to better keep track of file offsets based on encoding. #224 - Set input_type by default to ""log"" ==== Added *Affecting all Beats* - Added `beat.hostname` to contain the hostname where the Beat is running on as returned by the operating system. #285 - Added timestamp for file logging. #291 *Filebeat* - Handling end of line under windows was improved #233 [[release-notes-1.0.0-rc1]] === Beats version 1.0.0-rc1 https://github.com/elastic/beats/compare/1.0.0-beta4...1.0.0-rc1[Check 1.0.0-rc1 diff] ==== Breaking changes *Affecting all Beats* - Rename timestamp field with @timestamp. #237 *Packetbeat* - Rename timestamp field with @timestamp. #343 *Topbeat* - Rename timestamp field with @timestamp for a better integration with Logstash. #80 *Filebeat* - Rename the timestamp field with @timestamp #168 - Rename tail_on_rotate prospector config to tail_files - Removal of line field in event. Line number was not correct and does not add value. #217 ==== Bugfixes *Affecting all Beats* - Use stderr for console log output. #219 - Handle empty event array in publisher. #207 - Respect '*' debug selector in IsDebug. #226 (elastic/packetbeat#339) - Limit number of workers for Elasticsearch output. elastic/packetbeat#226 - On Windows, remove service related error message when running in the console. #242 - Fix waitRetry no configured in single output mode configuration. elastic/filebeat#144 - Use http as the default scheme in the elasticsearch hosts #253 - Respect max bulk size if bulk publisher (collector) is disabled or sync flag is set. - Always evaluate status code from Elasticsearch responses when indexing events. #192 - Use bulk_max_size configuration option instead of bulk_size. #256 - Fix max_retries=0 (no retries) configuration option. #266 - Filename used for file based logging now defaults to beat name. #267 *Packetbeat* - Close file descriptors used to monitor processes. #337 - Remove old RPM spec file. It moved to elastic/beats-packer. #334 *Topbeat* - Don't wait for one period until shutdown #75 *Filebeat* - Omit 'fields' from event JSON when null. #126 - Make offset and line value of type long in elasticsearch template to prevent overflow. #140 - Fix locking files for writing behaviour. #156 - Introduce 'document_type' config option per prospector to define document type for event stored in elasticsearch. #133 - Add 'input_type' field to published events reporting the prospector type being used. #133 - Fix high CPU usage when not connected to Elasticsearch or Logstash. #144 - Fix issue that files were not crawled anymore when encoding was set to something other then plain. #182 ==== Added *Affecting all Beats* - Add Console output plugin. #218 - Add timestamp to log messages #245 - Send @metadata.beat to Logstash instead of @metadata.index to prevent possible name clashes and give user full control over index name used for Elasticsearch - Add logging messages for bulk publishing in case of error #229 - Add option to configure number of parallel workers publishing to Elasticsearch or Logstash. - Set default bulk size for Elasticsearch output to 50. - Set default http timeout for Elasticsearch to 90s. - Improve publish retry if sync flag is set by retrying only up to max bulk size events instead of all events to be published. *Filebeat* - Introduction of backoff, backoff_factor, max_backoff, partial_line_waiting, force_close_windows_files config variables to make crawling more configurable. - All Godeps dependencies were updated to master on 2015-10-21 [#122] - Set default value for ignore_older config to 10 minutes. #164 - Added the fields_under_root setting to optionally store the custom fields top level in the output dictionary. #188 - Add more encodings by using x/text/encodings/htmlindex package to select encoding by name. [[release-notes-1.0.0-beta4]] === Beats version 1.0.0-beta4 https://github.com/elastic/beats/compare/1.0.0-beta3...1.0.0-beta4[Check 1.0.0-beta4 diff] ==== Breaking changes *Affecting all Beats* - Update tls config options naming from dash to underline #162 - Feature/output modes: Introduction of PublishEvent(s) to be used by beats #118 #115 *Packetbeat* - Renamed http module config file option 'strip_authorization' to 'redact_authorization' - Save_topology is set to false by default - Rename elasticsearch index to [packetbeat-]YYYY.MM.DD *Topbeat* - Percentage fields (e.g user_p) are exported as a float between 0 and 1 #34 ==== Bugfixes *Affecting all Beats* - Determine Elasticsearch index for an event based on UTC time #81 - Fixing ES output's defaultDeadTimeout so that it is 60 seconds #103 - ES outputer: fix timestamp conversion #91 - Fix TLS insecure config option #239 - ES outputer: check bulk API per item status code for retransmit on failure. *Packetbeat* - Support for lower-case header names when redacting http authorization headers - Redact proxy-authorization if redact-authorization is set - Fix some multithreading issues #203 - Fix negative response time #216 - Fix memcache TCP connection being nil after dropping stream data. #299 - Add missing DNS protocol configuration to documentation #269 *Topbeat* - Don't divide the reported memory by an extra 1024 #60 ==== Added *Affecting all Beats* - Add logstash output plugin #151 - Integration tests for Beat -> Logstash -> Elasticsearch added #195 #188 #168 #137 #128 #112 - Large updates and improvements to the documentation - Add direction field to publisher output to indicate inbound/outbound transactions #150 - Add tls configuration support to elasticsearch and logstash outputers #139 - All external dependencies were updated to the latest version. Update to Golang 1.5.1 #162 - Guarantee ES index is based in UTC time zone #164 - Cache: optional per element timeout #144 - Make it possible to set hosts in different ways. #135 - Expose more TLS config options #124 - Use the Beat name in the default configuration file path #99 *Packetbeat* - add [.editorconfig file](http://editorconfig.org/) - add (experimental/unsupported?) saltstack files - Sample config file cleanup - Moved common documentation to [libbeat repository](https://github.com/elastic/libbeat) - Update build to go 1.5.1 - Adding device descriptions to the -device output. - Generate coverage for system tests - Move go-daemon dependency to beats-packer - Rename integration tests to system tests - Made the `-devices` option more user friendly in case `sudo` is not used. Issue #296. - Publish expired DNS transactions #301 - Update protocol guide to libbeat changes - Add protocol registration to new protocol guide - Make transaction timeouts configurable #300 - Add direction field to the exported fields #317 *Topbeat* - Document fields in a standardized format (etc/fields.yml) #34 - Updated to use new libbeat Publisher #37 #41 - Update to go 1.5.1 #43 - Updated configuration files with comments for all options #65 - Documentation improvements ==== Deprecated *Affecting all Beats* - Redis output was deprecated #169 #145 - Host and port configuration options are deprecated. They are replaced by the hosts configuration option. #141 ",12515,True,2677.1726954225533,median "[[export-cypher]] == Export to Cypher Script [abstract] -- This section describes procedures that can be used to export data in Cypher format. -- The export to Cypher procedures export data as Cypher statements that can then be used to import the data into another Neo4j instance. [NOTE] ==== When exporting nodes, if a node label does not contain a unique constraint the exporter will add a `UNIQUE IMPORT LABEL` label and `UNIQUE IMPORT ID` property to those nodes to ensure uniqueness of nodes when the export script is executed on a new database. The final step of the export script removes the `UNIQUE IMPORT LABEL` label and `UNIQUE IMPORT ID`, so they won't exist in the new database once the script has finished executing. If a node label does have a unique constraint, the property on which the unique constraint is defined will be used to ensure uniqueness. ==== This section includes: * <> * <> * <> * <> * <> ** <> ** <> ** <> ** <> ** <> // ** <> // ** <> // ** <> // ** <> // ** <> // ** <> [[export-cypher-available-procedures]] === Available Procedures The table below describes the available procedures: // tag::export.cypher[] [separator=¦,opts=header,cols=""1,1m,1m,5""] |=== include::../../../build/generated-documentation/apoc.export.cypher.csv[] |=== // end::export.cypher[] [NOTE] The labels exported are ordered alphabetically. The output of `labels()` function is not sorted, use it in combination with `apoc.coll.sort()`. [[export-cypher-config]] === Configuration parameters The procedures support the following config parameters: .Config parameters [opts=header] |=== | name | type | default | description | format | String | cypher-shell a| Export format. The following values are supported: * `cypher-shell` - for import with Cypher Shell * `neo4j-shell` - for import with Neo4j Shell and partly the `apoc.cypher.runFile` procedure * `plain` - exports plain Cypher without `begin`, `commit`, or `await` commands. For import with Neo4j Browser | cypherFormat | String | create a| Cypher update operation type. The following values are supported: * `create` - only uses the `CREATE` clause * `updateAll` - uses `MERGE` instead of `CREATE` * `addStructure` - uses `MATCH` for nodes and `MERGE` for relationships * `updateStructure` - uses `MERGE` and `MATCH` for nodes and relationships | separateFiles | boolean | false | Export to separate files? This is useful for later use with the `apoc.cypher.runFiles` and `apoc.cypher.runSchemaFiles` procedures. | useOptimizations | Map a| `{type: ""UNWIND_BATCH"", unwindBatchSize: 20}` a| Optimizations to use for Cypher statement generation. `type` supports the following values: * `NONE` - exports the file with `CREATE` statement * `UNWIND_BATCH` - exports the file by batching the entities with the `UNWIND` method as explained in Michael Hunger's article on https://medium.com/neo4j/5-tips-tricks-for-fast-batched-updates-of-graph-structures-with-neo4j-and-cypher-73c7f693c8cc[fast batched writes^]. * `UNWIND_BATCH_PARAMS` - similar to `UNWIND_BATCH`, but also uses parameters where appropriate | awaitForIndexes | Long | 300 | Timeout to use for `db.awaitIndexes` when using `format: ""cypher-shell""` |=== [[export-cypher-file-export]] === Exporting to a file include::enableFileExport.adoc[] [[export-cypher-stream-export]] === Exporting a stream If we don't want to export to a file, we can stream results back by providing a file name of `null`. By default all Cypher statements will be returned in a single row in the `cypherStatements` column. .The following exports the whole database as a single row [source,cypher] ---- CALL apoc.export.cypher.all(null); ---- If we're exporting a large database, we can batch these statements across multiple rows by providing the `streamStatements:true` config and configuring the `batchSize` config. .The following exports the whole database across multiple rows based on batch size [source,cypher] ---- CALL apoc.export.cypher.all(null, { streamStatements: true, batchSize: 100 }); ---- [[export-cypher-examples]] === Examples This section includes examples showing how to use the export to Cypher procedures. These examples are based on a movies dataset, which can be imported by running the following Cypher query: include::createExportGraph.adoc[] The Neo4j Browser visualization below shows the imported graph: image::play-movies.png[title=""Movies Graph Visualization""] [[export-cypher-cypher-shell]] ==== Export to Cypher Shell format By default, the Cypher statements generated by the export to Cypher procedures are in the Cypher Shell format. .The following query exports the whole database to `all.cypher` in the default `cypher-shell` format using the default `UNWIND_BATCH` optimization [source,cypher] ---- // default config populated for illustration CALL apoc.export.cypher.all(""all.cypher"", { format: ""cypher-shell"", useOptimizations: {type: ""UNWIND_BATCH"", unwindBatchSize: 20} }) YIELD file, batches, source, format, nodes, relationships, properties, time, rows, batchSize RETURN file, batches, source, format, nodes, relationships, properties, time, rows, batchSize; ---- .Results [opts=""header""] |=== | file | batches | source | format | nodes | relationships | properties | time | rows | batchSize | ""all.cypher"" | 1 | ""database: nodes(8), rels(7)"" | ""cypher"" | 8 | 7 | 21 | 10 | 15 | 20000 |=== The contents of `all.cypher`, with extra lines added for readability, are shown below: .all.cypher [source,cypher] ---- :begin CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit :begin UNWIND [{_id:0, properties:{tagline:""Welcome to the Real World"", title:""The Matrix"", released:1999}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Movie; UNWIND [{_id:1, properties:{born:1964, name:""Keanu Reeves""}}, {_id:2, properties:{born:1967, name:""Carrie-Anne Moss""}}, {_id:3, properties:{born:1961, name:""Laurence Fishburne""}}, {_id:4, properties:{born:1960, name:""Hugo Weaving""}}, {_id:5, properties:{born:1967, name:""Lilly Wachowski""}}, {_id:6, properties:{born:1965, name:""Lana Wachowski""}}, {_id:7, properties:{born:1952, name:""Joel Silver""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; :commit :begin UNWIND [{start: {_id:1}, end: {_id:0}, properties:{roles:[""Neo""]}}, {start: {_id:2}, end: {_id:0}, properties:{roles:[""Trinity""]}}, {start: {_id:3}, end: {_id:0}, properties:{roles:[""Morpheus""]}}, {start: {_id:4}, end: {_id:0}, properties:{roles:[""Agent Smith""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:ACTED_IN]->(end) SET r += row.properties; UNWIND [{start: {_id:7}, end: {_id:0}, properties:{}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:PRODUCED]->(end) SET r += row.properties; UNWIND [{start: {_id:5}, end: {_id:0}, properties:{}}, {start: {_id:6}, end: {_id:0}, properties:{}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:DIRECTED]->(end) SET r += row.properties; :commit :begin MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 20000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; :commit :begin DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit ---- This Cypher script executes 5 transactions, each surrounded by `:begin` and `:commit` commands. The transactions do the following: . Create a unique constraint on the `UNIQUE IMPORT LABEL` label and `UNIQUE IMPORT ID` property . Import the `Person` and `Movie` nodes . Create `ACTED_IN`, `PRODUCED`, and `DIRECTED` relationships between these nodes . Remove the `UNIQUE IMPORT LABEL` label and `UNIQUE IMPORT ID` property from the nodes . Drop the unique constraint on the `UNIQUE IMPORT LABEL` label and `UNIQUE IMPORT ID` property This script can be executed using the https://neo4j.com/docs/operations-manual/current/tools/cypher-shell/[Cypher Shell^] command line tool. For example, we could import the contents of `all.cypher` into a https://neo4j.com/aura[Neo4j Aura^] database by running the following command: [source,bash] ---- cat all.cypher | ./bin/cypher-shell -a -u neo4j -p --format verbose ---- [NOTE] ==== Don't forget to replace and with the appropriate credentials. ==== If we run this command against an empty database, we'll see the following output: [source,text] ---- 0 rows available after 70 ms, consumed after another 0 ms Added 1 constraints 0 rows available after 16 ms, consumed after another 0 ms Added 2 nodes, Set 8 properties, Added 4 labels 0 rows available after 40 ms, consumed after another 0 ms Added 14 nodes, Set 42 properties, Added 28 labels 0 rows available after 51 ms, consumed after another 0 ms Created 8 relationships, Set 8 properties 0 rows available after 38 ms, consumed after another 0 ms Created 2 relationships 0 rows available after 38 ms, consumed after another 0 ms Created 4 relationships 0 rows available after 20 ms, consumed after another 0 ms Set 16 properties, Removed 16 labels 0 rows available after 3 ms, consumed after another 0 ms Removed 1 constraints ---- .Troubleshooting [NOTE] ==== If you are experimenting with imports that are failing you can add the `--debug` command line parameter, to see which statement was executed last and caused the failure. Also check the memory configuration of your Neo4j instance, you might want to increase the HEAP size to *2–4GB* using the `dbms.memory.heap.max_size=2G` setting in `neo4j.conf`. We can also provide more memory to cypher-shell itself by prefixing the command with: `JAVA_OPTS=-Xmx4G bin/cypher-shell …` ==== If we don't have file system access, or don't want to write to a file for another reason, we can stream back the export statements. .The following query streams back the whole database in the `cypherStatements` column [source,cypher] ---- CALL apoc.export.cypher.all(null, { batchSize: 5, streamStatements: true, format: ""cypher-shell"", useOptimizations: {type: ""UNWIND_BATCH"", unwindBatchSize: 5} }) YIELD nodes, relationships, properties, cypherStatements RETURN nodes, relationships, properties, cypherStatements; ---- .Results [opts=""header""] |=== | nodes | relationships | properties | cypherStatements | 16 | 0 | 34 a| "":begin CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit :begin UNWIND [{_id:0, properties:{tagline:\\""Welcome to the Real World\\"", title:\\""The Matrix\\"", released:1999}}, {_id:1, properties:{tagline:\\""Welcome to the Real World\\"", title:\\""The Matrix\\"", released:1999}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Movie; UNWIND [{_id:35, properties:{born:1967, name:\\""Carrie-Anne Moss\\""}}, {_id:36, properties:{born:1961, name:\\""Laurence Fishburne\\""}}, {_id:37, properties:{born:1965, name:\\""Lana Wachowski\\""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; :commit :begin UNWIND [{_id:38, properties:{born:1964, name:\\""Keanu Reeves\\""}}, {_id:39, properties:{born:1952, name:\\""Joel Silver\\""}}, {_id:40, properties:{born:1960, name:\\""Hugo Weaving\\""}}, {_id:41, properties:{born:1967, name:\\""Lilly Wachowski\\""}}, {_id:42, properties:{born:1967, name:\\""Carrie-Anne Moss\\""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; :commit :begin UNWIND [{_id:43, properties:{born:1965, name:\\""Lana Wachowski\\""}}, {_id:50, properties:{born:1960, name:\\""Hugo Weaving\\""}}, {_id:51, properties:{born:1964, name:\\""Keanu Reeves\\""}}, {_id:57, properties:{born:1967, name:\\""Lilly Wachowski\\""}}, {_id:58, properties:{born:1961, name:\\""Laurence Fishburne\\""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; :commit :begin UNWIND [{_id:59, properties:{born:1952, name:\\""Joel Silver\\""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; :commit "" | 16 | 14 | 42 a| "":begin UNWIND [{start: {_id:35}, end: {_id:0}, properties:{roles:[\\""Trinity\\""]}}, {start: {_id:36}, end: {_id:0}, properties:{roles:[\\""Morpheus\\""]}}, {start: {_id:50}, end: {_id:1}, properties:{roles:[\\""Agent Smith\\""]}}, {start: {_id:40}, end: {_id:0}, properties:{roles:[\\""Agent Smith\\""]}}, {start: {_id:51}, end: {_id:1}, properties:{roles:[\\""Neo\\""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:ACTED_IN]->(end) SET r += row.properties; :commit :begin UNWIND [{start: {_id:42}, end: {_id:1}, properties:{roles:[\\""Trinity\\""]}}, {start: {_id:38}, end: {_id:0}, properties:{roles:[\\""Neo\\""]}}, {start: {_id:58}, end: {_id:1}, properties:{roles:[\\""Morpheus\\""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:ACTED_IN]->(end) SET r += row.properties; UNWIND [{start: {_id:59}, end: {_id:1}, properties:{}}, {start: {_id:39}, end: {_id:0}, properties:{}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:PRODUCED]->(end) SET r += row.properties; :commit :begin UNWIND [{start: {_id:37}, end: {_id:0}, properties:{}}, {start: {_id:57}, end: {_id:0}, properties:{}}, {start: {_id:43}, end: {_id:1}, properties:{}}, {start: {_id:41}, end: {_id:1}, properties:{}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:DIRECTED]->(end) SET r += row.properties; :commit "" | 16 | 14 | 42 a| "":begin MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 5 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; :commit :begin MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 5 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; :commit :begin MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 5 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; :commit :begin MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 5 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; :commit :begin DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit "" |=== We can then copy/paste the content of the `cypherStatements` column (excluding the double quotes) into a Cypher Shell session, or into a local file that we stream into a Cypher Shell session. [[export-cypher-neo4j-browser]] ==== Export to Neo4j Browser friendly format The export to Cypher procedures support the config `format: ""plain""`, which is useful for later import using the https://neo4j.com/developer/neo4j-browser/[Neo4j Browser^]. .The following query exports the whole database to `all-plain.cypher` [source,cypher] ---- CALL apoc.export.cypher.all(""all-plain.cypher"", { format: ""plain"", useOptimizations: {type: ""UNWIND_BATCH"", unwindBatchSize: 20} }) YIELD file, batches, source, format, nodes, relationships, properties, time, rows, batchSize RETURN file, batches, source, format, nodes, relationships, properties, time, rows, batchSize; ---- .Results [opts=""header""] |=== | file | batches | source | format | nodes | relationships | properties | time | rows | batchSize | ""all-plain.cypher"" | 1 | ""database: nodes(8), rels(7)"" | ""cypher"" | 8 | 7 | 21 | 9 | 15 | 20000 |=== The contents of `all-plain.cypher`, with extra lines added for readability, are shown below: .all-plain.cypher [source,cypher] ---- CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; UNWIND [{_id:0, properties:{tagline:""Welcome to the Real World"", title:""The Matrix"", released:1999}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Movie; UNWIND [{_id:1, properties:{born:1964, name:""Keanu Reeves""}}, {_id:2, properties:{born:1967, name:""Carrie-Anne Moss""}}, {_id:3, properties:{born:1961, name:""Laurence Fishburne""}}, {_id:4, properties:{born:1960, name:""Hugo Weaving""}}, {_id:5, properties:{born:1967, name:""Lilly Wachowski""}}, {_id:6, properties:{born:1965, name:""Lana Wachowski""}}, {_id:7, properties:{born:1952, name:""Joel Silver""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; UNWIND [{start: {_id:1}, end: {_id:0}, properties:{roles:[""Neo""]}}, {start: {_id:2}, end: {_id:0}, properties:{roles:[""Trinity""]}}, {start: {_id:3}, end: {_id:0}, properties:{roles:[""Morpheus""]}}, {start: {_id:4}, end: {_id:0}, properties:{roles:[""Agent Smith""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:ACTED_IN]->(end) SET r += row.properties; UNWIND [{start: {_id:7}, end: {_id:0}, properties:{}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:PRODUCED]->(end) SET r += row.properties; UNWIND [{start: {_id:5}, end: {_id:0}, properties:{}}, {start: {_id:6}, end: {_id:0}, properties:{}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:DIRECTED]->(end) SET r += row.properties; MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 20000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; ---- We can then take the `all-plain.cypher` file and drag it onto the Neo4j Browser window. We should then see the following prompt: image::export-cypher-plain-drag.png[title=""Neo4j Browser prompt when we drag a file onto it""] And if we click `Paste in editor`, the contents of the file will appear in the query editor: image::export-cypher-plain-editor.png[title=""Neo4j Browser query editor with the contents of `all-plain.cypher`"", width=""800px""] We can then press the play button next in the editor and the data will be imported. [[export-cypher-different-cypher-format]] ==== Export using different Cypher update formats The export to Cypher procedures generate Cypher statements using the `CREATE`, `MATCH` and `MERGE` clauses. The format is configured by the `cypherFormat` parameter. The following values are supported: * `create` - only uses the `CREATE` clause (default) * `updateAll` - uses `MERGE` instead of `CREATE` * `addStructure` - uses `MATCH` for nodes and `MERGE` for relationships * `updateStructure` - uses `MERGE` and `MATCH` for nodes and relationships If we're exporting a database for the first time we should use the default `create` format, but for subsequent exports the other formats may be more suitable. .The following exports the `ACTED_IN` relationships and surrounding nodes to `export-cypher-format-create.cypher` using the `create` format [source,cypher] ---- MATCH (person)-[r:ACTED_IN]->(movie) WITH collect(DISTINCT person) + collect(DISTINCT movie) AS importNodes, collect(r) AS importRels CALL apoc.export.cypher.data(importNodes, importRels, ""export-cypher-format-create.cypher"", { format: ""plain"", cypherFormat: ""create"" }) YIELD file, batches, source, format, nodes, relationships, properties, time, rows, batchSize RETURN file, batches, source, format, nodes, relationships, properties, time, rows, batchSize; ---- .Results [opts=""header""] |=== | file | batches | source | format | nodes | relationships | properties | time | rows | batchSize | ""export-cypher-format-create.cypher"" | 1 | ""data: nodes(5), rels(4)"" | ""cypher"" | 5 | 4 | 15 | 2 | 9 | 20000 |=== .export-cypher-format-create.cypher [source,cypher] ---- CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; UNWIND [{_id:0, properties:{tagline:""Welcome to the Real World"", title:""The Matrix"", released:1999}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Movie; UNWIND [{_id:7, properties:{born:1967, name:""Carrie-Anne Moss""}}, {_id:80, properties:{born:1960, name:""Hugo Weaving""}}, {_id:27, properties:{born:1964, name:""Keanu Reeves""}}, {_id:44, properties:{born:1961, name:""Laurence Fishburne""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; UNWIND [{start: {_id:27}, end: {_id:0}, properties:{roles:[""Neo""]}}, {start: {_id:7}, end: {_id:0}, properties:{roles:[""Trinity""]}}, {start: {_id:44}, end: {_id:0}, properties:{roles:[""Morpheus""]}}, {start: {_id:80}, end: {_id:0}, properties:{roles:[""Agent Smith""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:ACTED_IN]->(end) SET r += row.properties; MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 20000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; ---- The creation of all graph entities uses the Cypher `CREATE` clause. If those entities may already exist in the destination database, we may choose to use another format. Using `cypherFormat: ""updateAll""` means that the `MERGE` clause will be used instead of `CREATE` when creating entities. .The following exports the `ACTED_IN` relationships and surrounding nodes to `export-cypher-format-create.cypher` using the `updateAll` format [source,cypher] ---- MATCH (person)-[r:ACTED_IN]->(movie) WITH collect(DISTINCT person) + collect(DISTINCT movie) AS importNodes, collect(r) AS importRels CALL apoc.export.cypher.data(importNodes, importRels, ""export-cypher-format-updateAll.cypher"", { format: ""plain"", cypherFormat: ""updateAll"" }) YIELD file, batches, source, format, nodes, relationships, properties, time, rows, batchSize RETURN file, batches, source, format, nodes, relationships, properties, time, rows, batchSize; ---- .Results [opts=""header""] |=== | file | batches | source | format | nodes | relationships | properties | time | rows | batchSize | ""export-cypher-format-updateAll.cypher"" | 1 | ""data: nodes(5), rels(4)"" | ""cypher"" | 5 | 4 | 15 | 8 | 9 | 20000 |=== .export-cypher-format-updateAll.cypher [source,cypher] ---- CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; UNWIND [{_id:0, properties:{tagline:""Welcome to the Real World"", title:""The Matrix"", released:1999}}] AS row MERGE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Movie; UNWIND [{_id:80, properties:{born:1960, name:""Hugo Weaving""}}, {_id:7, properties:{born:1967, name:""Carrie-Anne Moss""}}, {_id:44, properties:{born:1961, name:""Laurence Fishburne""}}, {_id:27, properties:{born:1964, name:""Keanu Reeves""}}] AS row MERGE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; UNWIND [{start: {_id:27}, end: {_id:0}, properties:{roles:[""Neo""]}}, {start: {_id:7}, end: {_id:0}, properties:{roles:[""Trinity""]}}, {start: {_id:44}, end: {_id:0}, properties:{roles:[""Morpheus""]}}, {start: {_id:80}, end: {_id:0}, properties:{roles:[""Agent Smith""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) MERGE (start)-[r:ACTED_IN]->(end) SET r += row.properties; MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 20000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; ---- If we already have the nodes in our destination database, we can use `cypherFormat: ""addStructure""` to create Cypher `CREATE` statements for just the relationships. .The following exports the `ACTED_IN` relationships and surrounding nodes to `export-cypher-format-addStructure.cypher` using the `addStructure` format [source,cypher] ---- MATCH (person)-[r:ACTED_IN]->(movie) WITH collect(DISTINCT person) + collect(DISTINCT movie) AS importNodes, collect(r) AS importRels CALL apoc.export.cypher.data(importNodes, importRels, ""export-cypher-format-addStructure.cypher"", { format: ""plain"", cypherFormat: ""addStructure"" }) YIELD file, batches, source, format, nodes, relationships, properties, time, rows, batchSize RETURN file, batches, source, format, nodes, relationships, properties, time, rows, batchSize; ---- .Results [opts=""header""] |=== | file | batches | source | format | nodes | relationships | properties | time | rows | batchSize | ""export-cypher-format-addStructure.cypher"" | 1 | ""data: nodes(5), rels(4)"" | ""cypher"" | 5 | 4 | 15 | 4 | 9 | 20000 |=== .export-cypher-format-addStructure.cypher [source,cypher] ---- UNWIND [{_id:0, properties:{tagline:""Welcome to the Real World"", title:""The Matrix"", released:1999}}] AS row MERGE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) ON CREATE SET n += row.properties SET n:Movie; UNWIND [{_id:7, properties:{born:1967, name:""Carrie-Anne Moss""}}, {_id:27, properties:{born:1964, name:""Keanu Reeves""}}, {_id:80, properties:{born:1960, name:""Hugo Weaving""}}, {_id:44, properties:{born:1961, name:""Laurence Fishburne""}}] AS row MERGE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) ON CREATE SET n += row.properties SET n:Person; UNWIND [{start: {_id:27}, end: {_id:0}, properties:{roles:[""Neo""]}}, {start: {_id:7}, end: {_id:0}, properties:{roles:[""Trinity""]}}, {start: {_id:44}, end: {_id:0}, properties:{roles:[""Morpheus""]}}, {start: {_id:80}, end: {_id:0}, properties:{roles:[""Agent Smith""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:ACTED_IN]->(end) SET r += row.properties; ---- In this example we're using the `MERGE` clause to create a node if it doesn't already exist, and are only creating properties if the node doesn't already exist. In this example, relationships don't exist in the destination database and need to be created. If those relationships do exist but have properties that need to be updated, we can use `cypherFormat: ""updateStructure""` to create our import script. .The following exports the `ACTED_IN` relationships and surrounding nodes to `export-cypher-format-updateStructure.cypher` using the `updateStructure` format [source,cypher] ---- MATCH (person)-[r:ACTED_IN]->(movie) WITH collect(DISTINCT person) + collect(DISTINCT movie) AS importNodes, collect(r) AS importRels CALL apoc.export.cypher.data(importNodes, importRels, ""export-cypher-format-updateStructure.cypher"", { format: ""plain"", cypherFormat: ""updateStructure"" }) YIELD file, batches, source, format, nodes, relationships, properties, time, rows, batchSize RETURN file, batches, source, format, nodes, relationships, properties, time, rows, batchSize; ---- .Results [opts=""header""] |=== | file | batches | source | format | nodes | relationships | properties | time | rows | batchSize | ""export-cypher-format-updateStructure.cypher"" | 1 | ""data: nodes(5), rels(4)"" | ""cypher"" | 0 | 4 | 4 | 2 | 4 | 20000 |=== .export-cypher-format-updateStructure.cypher [source,cypher] ---- UNWIND [{start: {_id:27}, end: {_id:0}, properties:{roles:[""Neo""]}}, {start: {_id:7}, end: {_id:0}, properties:{roles:[""Trinity""]}}, {start: {_id:44}, end: {_id:0}, properties:{roles:[""Morpheus""]}}, {start: {_id:80}, end: {_id:0}, properties:{roles:[""Agent Smith""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) MERGE (start)-[r:ACTED_IN]->(end) SET r += row.properties; ---- [[export-cypher-multiple-files]] ==== Export to multiple files or columns The export to Cypher procedures all support writing to multiple files or multiple columns. We can enable this mode by passing in the config `separateFiles: true` .The following query exports all the `ACTED_IN` relationships and corresponding nodes into files with an `actedIn` prefix [source,cypher] ---- CALL apoc.export.cypher.query( ""MATCH ()-[r:ACTED_IN]->() RETURN *"", ""actedIn.cypher"", { format: ""cypher-shell"", separateFiles: true }) YIELD file, batches, source, format, nodes, relationships, time, rows, batchSize RETURN file, batches, source, format, nodes, relationships, time, rows, batchSize; ---- .Results [opts=""header""] |=== | file | batches | source | format | nodes | relationships | time | rows | batchSize | ""actedIn.cypher"" | 1 | ""statement: nodes(10), rels(8)"" | ""cypher"" | 10 | 8 | 3 | 18 | 20000 |=== This will result in the following files being created: .Results [opts=""header""] |=== | Name | Size in bytes | Number of lines | actedIn.cleanup.cypher | 234 | 6 | actedIn.nodes.cypher | 893 | 6 | actedIn.relationships.cypher | 757 | 6 | actedIn.schema.cypher | 109 | 3 |=== Each of those files contains one particular part of the graph. Let's have a look at their content: .actedIn.cleanup.cypher [source,cypher] ---- :begin MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 20000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; :commit :begin DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit ---- .actedIn.nodes.cypher [source,cypher] ---- :begin UNWIND [{_id:28, properties:{tagline:""Welcome to the Real World"", title:""The Matrix"", released:1999}}, {_id:37, properties:{tagline:""Welcome to the Real World"", title:""The Matrix"", released:1999}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Movie; UNWIND [{_id:31, properties:{born:1961, name:""Laurence Fishburne""}}, {_id:30, properties:{born:1967, name:""Carrie-Anne Moss""}}, {_id:42, properties:{born:1964, name:""Keanu Reeves""}}, {_id:0, properties:{born:1960, name:""Hugo Weaving""}}, {_id:29, properties:{born:1964, name:""Keanu Reeves""}}, {_id:38, properties:{born:1960, name:""Hugo Weaving""}}, {_id:43, properties:{born:1967, name:""Carrie-Anne Moss""}}, {_id:57, properties:{born:1961, name:""Laurence Fishburne""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; :commit ---- .actedIn.relationships.cypher [source,cypher] ---- :begin UNWIND [{start: {_id:31}, end: {_id:28}, properties:{roles:[""Morpheus""]}}, {start: {_id:42}, end: {_id:37}, properties:{roles:[""Neo""]}}, {start: {_id:38}, end: {_id:37}, properties:{roles:[""Agent Smith""]}}, {start: {_id:0}, end: {_id:28}, properties:{roles:[""Agent Smith""]}}, {start: {_id:29}, end: {_id:28}, properties:{roles:[""Neo""]}}, {start: {_id:43}, end: {_id:37}, properties:{roles:[""Trinity""]}}, {start: {_id:30}, end: {_id:28}, properties:{roles:[""Trinity""]}}, {start: {_id:57}, end: {_id:37}, properties:{roles:[""Morpheus""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:ACTED_IN]->(end) SET r += row.properties; :commit ---- .actedIn.schema.cypher [source,cypher] ---- :begin CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit ---- We can then apply these files to our destination Neo4j instance, either by streaming their contents into Cypher Shell or by using the procedures described in <> We can also use the `separateFiles` when returning a stream of export statements. The results will appear in columns named `nodeStatements`, `relationshipStatements`, `cleanupStatements`, and `schemaStatements` rather than `cypherStatements`. .The following query returns a stream all the `ACTED_IN` relationships and corresponding nodes [source,cypher] ---- CALL apoc.export.cypher.query( ""MATCH ()-[r:ACTED_IN]->() RETURN *"", null, { format: ""cypher-shell"", separateFiles: true }) YIELD nodes, relationships, properties, nodeStatements, relationshipStatements, cleanupStatements, schemaStatements RETURN nodes, relationships, properties, nodeStatements, relationshipStatements, cleanupStatements, schemaStatements; ---- .Results [opts=""header""] |=== | nodes | relationships | properties | nodeStatements | relationshipStatements | cleanupStatements | schemaStatements | 10 | 8 | 30 | "":begin UNWIND [{_id:28, properties:{tagline:\\""Welcome to the Real World\\"", title:\\""The Matrix\\"", released:1999}}, {_id:37, properties:{tagline:\\""Welcome to the Real World\\"", title:\\""The Matrix\\"", released:1999}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Movie; UNWIND [{_id:0, properties:{born:1960, name:\\""Hugo Weaving\\""}}, {_id:42, properties:{born:1964, name:\\""Keanu Reeves\\""}}, {_id:31, properties:{born:1961, name:\\""Laurence Fishburne\\""}}, {_id:29, properties:{born:1964, name:\\""Keanu Reeves\\""}}, {_id:30, properties:{born:1967, name:\\""Carrie-Anne Moss\\""}}, {_id:43, properties:{born:1967, name:\\""Carrie-Anne Moss\\""}}, {_id:38, properties:{born:1960, name:\\""Hugo Weaving\\""}}, {_id:57, properties:{born:1961, name:\\""Laurence Fishburne\\""}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; :commit "" | "":begin UNWIND [{start: {_id:31}, end: {_id:28}, properties:{roles:[\\""Morpheus\\""]}}, {start: {_id:38}, end: {_id:37}, properties:{roles:[\\""Agent Smith\\""]}}, {start: {_id:0}, end: {_id:28}, properties:{roles:[\\""Agent Smith\\""]}}, {start: {_id:30}, end: {_id:28}, properties:{roles:[\\""Trinity\\""]}}, {start: {_id:29}, end: {_id:28}, properties:{roles:[\\""Neo\\""]}}, {start: {_id:43}, end: {_id:37}, properties:{roles:[\\""Trinity\\""]}}, {start: {_id:42}, end: {_id:37}, properties:{roles:[\\""Neo\\""]}}, {start: {_id:57}, end: {_id:37}, properties:{roles:[\\""Morpheus\\""]}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:ACTED_IN]->(end) SET r += row.properties; :commit "" | "":begin MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 20000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; :commit :begin DROP CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit "" | "":begin CREATE CONSTRAINT ON (node:`UNIQUE IMPORT LABEL`) ASSERT (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit "" |=== We can then copy/paste the content of each of these columns (excluding the double quotes) into a Cypher Shell session, or into a local file that we stream into a Cypher Shell session. If we want to export Cypher statements that can be pasted into the Neo4j Browser query editor, we need to use the config `format: ""plain""`, as described in <>. [[export-cypher-examples-roundtrip]] ==== Round trip This example shows how to export data from one Neo4j instance (the source database) and import it into another one (the destination database). .The following exports 100 nodes and relationships from the source database in `plain` format into multiple files [source,cypher] ---- CALL apoc.export.cypher.query( ""match (n)-[r]->(n2) return * limit 100"", ""/tmp/mysubset.cypher"", {format:'plain',separateFiles:true} ) YIELD file, batches, source, format, nodes, relationships, time, rows, batchSize RETURN file, batches, source, format, nodes, relationships, time, rows, batchSize; ---- .Results [opts=""header""] |=== | file | batches | source | format | nodes | relationships | time | rows | batchSize | ""/tmp/mysubset.cypher"" | 1 | ""statement: nodes(16), rels(14)"" | ""cypher"" | 16 | 14 | 9 | 30 | 20000 |=== This should result in 4 files in your directory. [source,shell] ---- ls -1 /tmp/mysubset.* /tmp/mysubset.cleanup.cypher /tmp/mysubset.nodes.cypher /tmp/mysubset.relationships.cypher /tmp/mysubset.schema.cypher ---- Now let's copy those files so they're accessible from our destination database. We'll need to first add the following property to `neo4j.conf`: .neo4j.conf [source,properties] ---- apoc.import.file.enabled=true ---- And now we're going to use procedures from <> to import the data. .The following imports the schema [source,cypher] ---- CALL apoc.cypher.runSchemaFile('/tmp/mysubset.schema.cypher'); ---- .Results [opts=""header""] |=== | row | result | -1 | {constraintsRemoved: 0, indexesRemoved: 0, nodesCreated: 0, rows: 0, propertiesSet: 0, labelsRemoved: 0, relationshipsDeleted: 0, constraintsAdded: 0, nodesDeleted: 0, indexesAdded: 0, labelsAdded: 0, r elationshipsCreated: 0, time: 0} |=== .The following imports the nodes and relationships [source,cypher] ---- CALL apoc.cypher.runFiles(['/tmp/mysubset.nodes.cypher','/tmp/mysubset.relationships.cypher']); ---- .Results [opts=""header""] |=== | row | result | -1 | {constraintsRemoved: 0, indexesRemoved: 0, nodesCreated: 2, rows: 0, propertiesSet: 8, labelsRemoved: 0, relationshipsDeleted: 0, constraintsAdded: 0, nodesDeleted: 0, indexesAdded: 0, labelsAdded: 4, r elationshipsCreated: 0, time: 0} | -1 | {constraintsRemoved: 0, indexesRemoved: 0, nodesCreated: 14, rows: 0, propertiesSet: 42, labelsRemoved: 0, relationshipsDeleted: 0, constraintsAdded: 0, nodesDeleted: 0, indexesAdded: 0, labelsAdded: 28 , relationshipsCreated: 0, time: 0} | -1 | {constraintsRemoved: 0, indexesRemoved: 0, nodesCreated: 0, rows: 0, propertiesSet: 8, labelsRemoved: 0, relationshipsDeleted: 0, constraintsAdded: 0, nodesDeleted: 0, indexesAdded: 0, labelsAdded: 0, r elationshipsCreated: 8, time: 0} | -1 | {constraintsRemoved: 0, indexesRemoved: 0, nodesCreated: 0, rows: 0, propertiesSet: 0, labelsRemoved: 0, relationshipsDeleted: 0, constraintsAdded: 0, nodesDeleted: 0, indexesAdded: 0, labelsAdded: 0, r elationshipsCreated: 2, time: 0} | -1 | {constraintsRemoved: 0, indexesRemoved: 0, nodesCreated: 0, rows: 0, propertiesSet: 0, labelsRemoved: 0, relationshipsDeleted: 0, constraintsAdded: 0, nodesDeleted: 0, indexesAdded: 0, labelsAdded: 0, r elationshipsCreated: 4, time: 0} |=== .The following removes temporary node labels and properties [source,cypher] ---- CALL apoc.cypher.runFile('/tmp/mysubset.cleanup.cypher'); ---- .Results [opts=""header""] |=== | row | result | -1 | {constraintsRemoved: 0, indexesRemoved: 0, nodesCreated: 0, rows: 0, propertiesSet: 16, labelsRemoved: 16, relationshipsDeleted: 0, constraintsAdded: 0, nodesDeleted: 0, indexesAdded: 0, labelsAdded: 0, relationshipsCreated: 0, time: 0} |=== .The following drops the import specific constraint [source,cypher] ---- CALL apoc.cypher.runSchemaFile('/tmp/mysubset.cleanup.cypher'); ---- .Results [opts=""header""] |=== | row | result | -1 | {constraintsRemoved: 1, indexesRemoved: 0, nodesCreated: 0, rows: 0, propertiesSet: 0, labelsRemoved: 0, relationshipsDeleted: 0, constraintsAdded: 0, nodesDeleted: 0, indexesAdded: 0, labelsAdded: 0, r elationshipsCreated: 0, time: 0} |=== The `apoc.cypher.run*` procedures have some optional config: * `{statistics:true/false}` to output a row of update-stats per statement, default is true * `{timeout:1 or 10}` for how long the stream waits for new data, default is 10 Make sure to set the config options in your `neo4j.conf` ",12231,True,2866.4914180467886,median "#include #include #include #include #include #include namespace mssql { constexpr int sql_server_2008_default_time_precision = 16; constexpr int sql_server_2008_default_datetime_precision = 34; constexpr int sql_server_2008_default_timestamp_precision = 27; constexpr int sql_server_2008_default_datetime_scale = 7; static Local get_as_bool(const Local o, const char* v) { const nodeTypeFactory fact; const auto context = fact.isolate->GetCurrentContext(); const auto vp = Nan::New(v).ToLocalChecked(); const auto false_val = Nan::New(false); if (o->IsNull()) { return false_val; } if (!o->IsObject()) { return false_val; } Local as_obj; if (!o->ToObject(context).ToLocal(&as_obj)) { return false_val; } if (as_obj->IsNull()) { return false_val; } Local as_val; if (!as_obj->Get(context, vp).ToLocal(&as_val)) { return false_val; } if (as_val->IsNull()) { return false_val; } return Nan::To(as_val).ToLocalChecked(); } bool sql_type_s_maps_to_tvp(const Local p) { const auto is_user_defined = get_as_bool(p, ""is_user_defined""); if (is_user_defined->IsNull()) return false; const auto as_bool = MutateJS::as_boolean(is_user_defined); return as_bool; } bool BoundDatum::bind(Local& p) { auto res = false; if (sql_type_s_maps_to_tvp(p)) { bind_tvp(p); return true; } if (p->IsArray()) { res = bind_array(p); } else if (p->IsObject()) { res = bind_object(p); } if (!res) res = bind_datum_type(p); return res; } static Local get_as_string(const Local o, const char* v) { const auto key = Nan::New(v).ToLocalChecked(); const auto ss = Nan::Get(Nan::To(o).ToLocalChecked(), key).ToLocalChecked(); if (!ss.IsEmpty()) { return Nan::To(ss).ToLocalChecked(); } return Nan::EmptyString(); } void BoundDatum::bind_null(const Local& p) { reserve_null(1); _indvec[0] = SQL_NULL_DATA; } void BoundDatum::bind_null_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_null(len); for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; } } void BoundDatum::reserve_null(const SQLLEN len) { buffer_len = 0; _indvec.resize(len); js_type = JS_NULL; c_type = SQL_C_CHAR; sql_type = SQL_CHAR; param_size = 1; digits = 0; buffer = nullptr; } void BoundDatum::bind_w_long_var_char(const Local& p) { bind_w_var_char(p); sql_type = SQL_WLONGVARCHAR; param_size = buffer_len; } void BoundDatum::bind_w_var_char(const Local& p) { const auto str_param = Nan::To(p).FromMaybe(Nan::EmptyString()); bind_w_var_char(p, str_param->Length()); } void BoundDatum::bind_char(const Local& p) { bind_var_char(p); } void BoundDatum::bind_var_char(const Local& p) { const auto local = Nan::To(p).FromMaybe(Nan::EmptyString()); SQLULEN precision = local->Length(); if (param_size > 0) precision = min(param_size, precision); bind_var_char(p, static_cast(precision)); } void BoundDatum::reserve_var_char(const size_t precision, const size_t array_len) { js_type = JS_STRING; c_type = SQL_C_CHAR; sql_type = precision > 8000 ? SQL_WLONGVARCHAR : SQL_VARCHAR; if (precision == 4000) { sql_type = SQL_WCHAR; } digits = 0; _indvec[0] = SQL_NULL_DATA; _indvec.resize(array_len); _storage->ReserveChars(max(1, static_cast(array_len * precision))); auto* itr_p = _storage->charvec_ptr->data(); buffer = itr_p; buffer_len = static_cast(precision); param_size = max(buffer_len, static_cast(1)); } void BoundDatum::bind_var_char(const Local& p, const int precision) { reserve_var_char(precision, 1); if (!p->IsNullOrUndefined()) { const auto str_param = Nan::To(p).FromMaybe(Nan::EmptyString()); Nan::Utf8String x(str_param); const auto *x_p = *x; memcpy(_storage->charvec_ptr->data(), x_p, precision); _indvec[0] = precision; } } int get_max_str_len(const Local& p) { auto str_len = 0; const auto arr = Local::Cast(p); const auto len = arr->Length(); for (uint32_t i = 0; i < len; ++i) { auto elem = Nan::Get(arr, i); if (elem.IsEmpty()) continue; auto maybe_value = Nan::To(elem.ToLocalChecked()); const auto str = maybe_value.FromMaybe(Nan::EmptyString()); if (str->Length() > str_len) { str_len = str->Length(); } } return str_len; } void BoundDatum::bind_var_char_array_bcp(const Local& p) { const auto arr = Local::Cast(p); const auto array_len = arr->Length(); _storage->ReserveCharVec(array_len); _indvec.resize(array_len); sql_type = SQLVARCHAR; param_size = SQL_VARLEN_DATA; buffer_len = get_max_str_len(p); auto & vec = *_storage->char_vec_vec_ptr; for (uint32_t i = 0; i < array_len; ++i) { _indvec[i] = SQL_NULL_DATA; auto elem = Nan::Get(arr, i); if (elem.IsEmpty()) continue; const auto local_elem = elem.ToLocalChecked(); if (local_elem->IsNullOrUndefined()) { continue; } auto maybe_value = Nan::To(elem.ToLocalChecked()); const auto str = maybe_value.FromMaybe(Nan::EmptyString()); const auto width = str->Length(); _indvec[i] = width; Nan::Utf8String x(str); const auto *x_p = *x; _indvec[i] = width; const auto store = make_shared(width); store->reserve(width); store->resize(width); vec[i] = store; const auto itr = store->data(); memcpy(&*itr, x_p, width); } } void BoundDatum::bind_var_char_array(const Local& p) { if (is_bcp) { bind_var_char_array_bcp(p); return; } const auto max_str_len = max(1, get_max_str_len(p)); const auto arr = Local::Cast(p); const auto array_len = arr->Length(); reserve_var_char(max_str_len, array_len); auto itr = _storage->charvec_ptr->begin(); for (uint32_t i = 0; i < array_len; ++i) { _indvec[i] = SQL_NULL_DATA; auto elem = Nan::Get(arr, i); if (elem.IsEmpty()) continue; auto maybe_value = Nan::To(elem.ToLocalChecked()); const auto str = maybe_value.FromMaybe(Nan::EmptyString()); const auto width = str->Length(); _indvec[i] = width; Nan::Utf8String x(str); const auto *x_p = *x; memcpy(&*itr, x_p, max_str_len); itr += max_str_len; } } void BoundDatum::reserve_w_var_char_array(const size_t max_str_len, const size_t array_len) { js_type = JS_STRING; c_type = SQL_C_WCHAR; sql_type = max_str_len > 2000 && max_str_len < 4000 ? SQL_WLONGVARCHAR : SQL_WVARCHAR; constexpr auto size = sizeof(uint16_t); _indvec.resize(array_len); _storage->ReserveUint16(array_len * max_str_len); buffer = _storage->uint16vec_ptr->data(); buffer_len = static_cast(max_str_len * size); if (max_str_len >= 4000) { param_size = 0; } else { param_size = max(buffer_len, static_cast(1)); } } void BoundDatum::bind_w_var_char_array_bcp(const Local& p) { const auto arr = Local::Cast(p); const auto array_len = arr->Length(); _storage->ReserveUint16Vec(array_len); _indvec.resize(array_len); sql_type = SQLNCHAR; param_size = SQL_VARLEN_DATA; buffer_len = get_max_str_len(p) + 1; bcp_terminator = reinterpret_cast(L""""); bcp_terminator_len = sizeof(WCHAR); auto & vec = *_storage->uint16_vec_vec_ptr; for (uint32_t i = 0; i < array_len; ++i) { _indvec[i] = SQL_NULL_DATA; auto elem = Nan::Get(arr, i); if (elem.IsEmpty()) continue; const auto local_elem = elem.ToLocalChecked(); if (local_elem->IsNullOrUndefined()) { continue; } auto maybe_value = Nan::To(local_elem); const auto str = maybe_value.FromMaybe(Nan::EmptyString()); const auto len = str->Length(); constexpr auto size = sizeof(uint16_t); const auto store = make_shared(len); store->reserve(len); store->resize(len); vec[i] = store; const auto itr = store->data(); const auto width = len * size; _indvec[i] = static_cast(width); const size_t strlen = static_cast(str->Length()) * 2; Nan::DecodeWrite(reinterpret_cast(&*itr), strlen, str, Nan::UCS2); store->push_back(0); } } void BoundDatum::bind_w_var_char_array(const Local& p) { if (is_bcp) { bind_w_var_char_array_bcp(p); return; } const auto max_str_len = max(1, get_max_str_len(p)); const auto arr = Local::Cast(p); const auto array_len = arr->Length(); reserve_w_var_char_array(max_str_len, array_len); auto* const base = _storage->uint16vec_ptr->data(); for (uint32_t i = 0; i < array_len; ++i) { constexpr auto size = sizeof(uint16_t); auto* const itr = base + static_cast(max_str_len ) * i; _indvec[i] = SQL_NULL_DATA; auto elem = Nan::Get(arr, i); if (elem.IsEmpty()) continue; const auto local_elem = elem.ToLocalChecked(); if (local_elem->IsNullOrUndefined()) continue; auto maybe_value = Nan::To(local_elem); const auto str = maybe_value.FromMaybe(Nan::EmptyString()); const auto width = str->Length() * size; _indvec[i] = static_cast(width); const auto strlen = static_cast(str->Length()) * 2; Nan::DecodeWrite(reinterpret_cast(&*itr), strlen, str, Nan::UCS2); } } void BoundDatum::bind_w_var_char(const Local& p, const int precision) { const size_t max_str_len = max(1, precision); reserve_w_var_char_array(max_str_len, 1); _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { constexpr auto size = sizeof(uint16_t); const auto str_param = Nan::To(p).FromMaybe(Nan::EmptyString()); auto* const first_p = _storage->uint16vec_ptr->data(); DecodeWrite(reinterpret_cast(first_p), static_cast(str_param->Length()) * 2, str_param, Nan::UCS2); buffer_len = static_cast(precision) * static_cast(size); if (precision >= 4000) { param_size = 0; } else { param_size = max(buffer_len, static_cast(1)); } _indvec[0] = buffer_len; } } size_t get_max_object_len(const Local& p) { size_t obj_len = 0; const auto arr = Local::Cast(p); const auto len = arr->Length(); for (uint32_t i = 0; i < len; ++i) { auto elem = Nan::Get(arr, i); if (elem.IsEmpty()) continue; const auto local = elem.ToLocalChecked(); if (local->IsNullOrUndefined()) continue; auto maybe_value = Nan::To(local); if (maybe_value.IsEmpty()) continue; const auto local_instance = maybe_value.ToLocalChecked(); const auto width = node::Buffer::Length(local_instance); if (width > obj_len) obj_len = width; } return obj_len; } void BoundDatum::bind_long_var_binary(Local& p) { bind_var_binary(p); sql_type = SQL_LONGVARBINARY; } void BoundDatum::reserve_var_binary_array(const size_t max_obj_len, const size_t array_len) { js_type = JS_BUFFER; c_type = SQL_C_BINARY; sql_type = max_obj_len > 2000 ? SQL_LONGVARBINARY : SQL_VARBINARY; digits = 0; constexpr auto size = sizeof(uint8_t); _storage->ReserveChars(array_len * max_obj_len); _indvec.resize(array_len); buffer = _storage->charvec_ptr->data(); buffer_len = static_cast(max_obj_len) * static_cast(size); param_size = max_obj_len; } /* *const auto r = SQLBindParameter(*_statement, current_param, datum.param_type, datum.c_type, datum.sql_type, datum.param_size, datum.digits, datum.buffer, datum.buffer_len, datum.get_ind_vec().data()); retcode = SQLBindParameter( hstmt, // Statement handle current_param 1, // Parameter Number param_type SQL_PARAM_INPUT, // Input/Output Type (always INPUT for TVP) c_type SQL_C_DEFAULT, // C - Type (always this for a TVP) sql_type SQL_SS_TABLE, // SQL Type (always this for a TVP) param_size MAX_ARRAY_SIZE, // For a TVP this is max rows we will use digits 0, // For a TVP this is always 0 buffer TVPTableName, // For a TVP this is the type name of the // TVP, and also a token returned by // SQLParamData. buffer_len SQL_NTS, // For a TVP this is the length of the type // name or SQL_NTS. &lTVPRowsUsed); // For a TVP this is the number of rows // actually available. */ static int get_row_count(Local& p) { auto rows = 1; auto maybe_object = Nan::To(p); if (maybe_object.IsEmpty()) return -1; const auto local = maybe_object.ToLocalChecked(); auto maybe_get = Nan::Get(local, Nan::New(""row_count"").FromMaybe(Nan::EmptyString())); if (maybe_get.IsEmpty()) return rows; const auto int32 = Nan::To(maybe_get.ToLocalChecked()); rows = int32.FromMaybe(1); return rows; } wstring wide_from_js_string(const Local s) { wstring_convert> converter; Nan::Utf8String x(s); const auto *x_p = *x; const string narrow = x_p; auto wide = converter.from_bytes(narrow); return wide; } void BoundDatum::bind_tvp(Local& p) { wstring_convert> converter; // string narrow = converter.to_bytes(wide_utf16_source_string); // fprintf(stderr, ""bind tvp\\n""); is_tvp = true; param_type = SQL_PARAM_INPUT; c_type = SQL_C_DEFAULT; sql_type = SQL_SS_TABLE; const auto rows = get_row_count(p); const auto type_id_str = get_as_string(p, ""type_id""); const auto schema_str = get_as_string(p, ""schema""); if (!schema_str->IsNullOrUndefined()) { _storage->schema = wide_from_js_string(schema_str); } _indvec.resize(1); const size_t precision = type_id_str->Length(); _storage->ReserveChars(precision + 1); _storage->ReserveUint16(precision + 1); auto* itr_p = _storage->charvec_ptr->data(); Nan::Utf8String x(type_id_str); const auto *x_p = *x; memcpy(itr_p, x_p, precision); //type_id_str->WriteUtf8(fact.isolate, itr_p, precision); const string narrow = _storage->charvec_ptr->data(); const auto type_name = converter.from_bytes(narrow); const auto type_name_vec = wstr2wcvec(type_name); constexpr auto size = sizeof(type_name_vec[0]); memcpy(_storage->uint16vec_ptr->data(), type_name_vec.data(), precision * size); buffer = _storage->uint16vec_ptr->data(); buffer_len = static_cast(precision) * static_cast(size); param_size = rows; // max no of rows. _indvec[0] = rows; // no of rows. digits = 0; } void BoundDatum::bind_var_binary(Local& p) { Local o; _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { o = p.As(); } const auto valid = !p->IsNullOrUndefined() && !o->IsNullOrUndefined(); const auto obj_len = valid ? node::Buffer::Length(o) : 0; reserve_var_binary_array(obj_len, 1); if (valid) { const auto itr = _storage->charvec_ptr->begin(); const auto* const ptr = node::Buffer::Data(o); _indvec[0] = static_cast(obj_len); memcpy(&*itr, ptr, obj_len); } } void BoundDatum::bind_var_binary_array_bcp(const Local& p) { const auto arr = Local::Cast(p); const auto array_len = arr->Length(); _storage->ReserveCharVec(array_len); _indvec.resize(array_len); sql_type = SQLVARBINARY; param_size = SQL_VARLEN_DATA; buffer_len = static_cast(get_max_object_len(p)); auto & vec = *_storage->char_vec_vec_ptr; for (uint32_t i = 0; i < array_len; ++i) { _indvec[i] = SQL_NULL_DATA; auto elem = Nan::Get(arr, i); if (elem.IsEmpty()) continue; const auto local_elem = elem.ToLocalChecked(); if (local_elem->IsNullOrUndefined()) { continue; } auto maybe_value = Nan::To(local_elem); if (maybe_value.IsEmpty()) continue; const auto local_instance = maybe_value.ToLocalChecked(); if (local_instance->IsNullOrUndefined()) continue; const auto* const ptr = node::Buffer::Data(local_instance); const auto obj_len = node::Buffer::Length(local_instance); _indvec[i] = static_cast(obj_len); const auto store = make_shared(obj_len); store->reserve(obj_len); store->resize(obj_len); vec[i] = store; const auto itr = store->data(); memcpy(&*itr, ptr, obj_len); } } void BoundDatum::bind_var_binary_array(const Local& p) { if (is_bcp) { bind_var_binary_array_bcp(p); return; } const auto arr = Local::Cast(p); const auto array_len = arr->Length(); const auto max_obj_len = get_max_object_len(p); reserve_var_binary_array(max_obj_len, array_len); auto* const base = _storage->charvec_ptr->data(); for (uint32_t i = 0; i < array_len; ++i) { auto* const itr = base + (max_obj_len * i); _indvec[i] = SQL_NULL_DATA; auto elem = Nan::Get(arr, i); if (elem.IsEmpty()) continue; const auto toLocal = elem.ToLocalChecked(); if (toLocal->IsNullOrUndefined()) continue; auto maybe_value = Nan::To(toLocal); if (maybe_value.IsEmpty()) continue; const auto local_instance = maybe_value.ToLocalChecked(); if (local_instance->IsNullOrUndefined()) continue; const auto* const ptr = node::Buffer::Data(local_instance); const auto obj_len = node::Buffer::Length(local_instance); _indvec[i] = static_cast(obj_len); memcpy(&*itr, ptr, obj_len); } } void BoundDatum::bind_boolean(const Local& p) { reserve_boolean(1); auto& vec = *_storage->charvec_ptr; _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { const auto v = MutateJS::as_boolean(p); vec[0] = !v ? 0 : 1; _indvec[0] = 0; } } void BoundDatum::bind_boolean_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_boolean(len); auto& vec = *_storage->charvec_ptr; for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; const auto elem = Nan::Get(arr, i).ToLocalChecked(); if (!elem->IsNullOrUndefined()) { const auto v = MutateJS::as_boolean(elem); const auto b = !v ? 0 : 1; vec[i] = static_cast(b); _indvec[i] = is_bcp ? sizeof(int8_t) : 0; } } } void BoundDatum::reserve_boolean(const SQLLEN len) { constexpr auto size = sizeof(char); buffer_len = static_cast(len) * static_cast(size); _storage->ReserveChars(len); _indvec.resize(len); js_type = JS_BOOLEAN; c_type = SQL_C_BIT; sql_type = SQL_BIT; buffer = _storage->charvec_ptr->data(); param_size = size; digits = 0; if (is_bcp) { sql_type = SQLBIT; param_size = sizeof(DBBIT); } } void BoundDatum::bind_numeric(const Local& p) { reserve_numeric(1); sql_type = SQL_NUMERIC; _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { const auto local = Nan::To(p).ToLocalChecked(); const auto d = local->Value(); auto& vec = *_storage->numeric_ptr; auto& ns = vec[0]; encode_numeric_struct(d, static_cast(param_size), digits, ns); param_size = ns.precision; digits = static_cast(ns.scale); _indvec[0] = sizeof(SQL_NUMERIC_STRUCT); } } void BoundDatum::bind_numeric_array(const Local& p) { const auto arr = Local::Cast(p); const int len = arr->Length(); reserve_numeric(len); auto& vec = *_storage->numeric_ptr; for (auto i = 0; i < len; ++i) { auto& ns = vec[i]; _indvec[i] = SQL_NULL_DATA; const auto elem = Nan::Get(arr, i).ToLocalChecked(); if (!elem->IsNullOrUndefined()) { const auto num = Nan::To(elem).ToLocalChecked(); const auto d = num->Value(); encode_numeric_struct(d, static_cast(param_size), 0, ns); param_size = max(static_cast(param_size), static_cast(ns.precision)); digits = 0; _indvec[i] = sizeof(SQL_NUMERIC_STRUCT); } } } void BoundDatum::reserve_numeric(const SQLLEN len) { definedPrecision = true; buffer_len = len * sizeof(SQL_NUMERIC_STRUCT); _storage->ReserveNumerics(len); _indvec.resize(len); js_type = JS_NUMBER; c_type = SQL_C_NUMERIC; sql_type = SQL_NUMERIC; buffer = _storage->numeric_ptr->data(); if (is_bcp) { sql_type = SQLNUMERICN; param_size = sizeof(SQL_NUMERIC_STRUCT); } } void BoundDatum::bind_tiny_int(const Local& p) { bind_int32(p); sql_type = SQL_TINYINT; } void BoundDatum::bind_small_int(const Local& p) { bind_int32(p); sql_type = SQL_SMALLINT; } void BoundDatum::bind_int32(const Local& p) { reserve_int32(1); _indvec[0] = SQL_NULL_DATA; auto& vec = *_storage->int32vec_ptr; vec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { const auto local = Nan::To(p).FromMaybe(Nan::New(0)); const auto d = local->Value(); vec[0] = d; _indvec[0] = 0; } } void BoundDatum::bind_int32_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_int32(len); auto& vec = *_storage->int32vec_ptr; for (unsigned int i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; auto maybe_elem = Nan::Get(arr, i); if (!maybe_elem.IsEmpty()) { const auto local_elem = maybe_elem.ToLocalChecked(); if (local_elem->IsNullOrUndefined()) continue; const auto local = Nan::To(local_elem).FromMaybe(Nan::New(0)); vec[i] = local->Value(); _indvec[i] = is_bcp ? sizeof(int32_t) : 0; } } } void BoundDatum::reserve_int32(const SQLLEN len) { constexpr auto size = sizeof(int32_t); buffer_len = len * static_cast(size); _storage->ReserveInt32(len); _indvec.resize(len); js_type = JS_INT; c_type = SQL_C_SLONG; sql_type = SQL_INTEGER; buffer = _storage->int32vec_ptr->data(); param_size = size; digits = 0; if (is_bcp) { sql_type = SQLINT4; param_size = sizeof(DBINT); } } void BoundDatum::bind_uint32(const Local& p) { reserve_uint32(1); auto& vec = *_storage->uint32vec_ptr; _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { const auto local = Nan::To(p).FromMaybe(Nan::New(0)); vec[0] = local->Value(); _indvec[0] = 0; } } void BoundDatum::bind_uint32_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_uint32(len); auto& vec = *_storage->uint32vec_ptr; for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; auto maybe_elem = Nan::Get(arr, i); if (!maybe_elem.IsEmpty()) { const auto local_elem = maybe_elem.ToLocalChecked(); if (local_elem->IsNullOrUndefined()) continue; const auto local = Nan::To(local_elem).FromMaybe(Nan::New(0)); vec[i] = local->Value(); _indvec[i] = 0; } } } void BoundDatum::reserve_uint32(const SQLLEN len) { constexpr auto size = sizeof(uint32_t); buffer_len = static_cast(len * size); _storage->ReserveUInt32(len); _indvec.resize(len); js_type = JS_UINT; c_type = SQL_C_ULONG; sql_type = SQL_BIGINT; buffer = _storage->uint32vec_ptr->data(); param_size = size; digits = 0; } void BoundDatum::bind_date(const Local& p) { reserve_date(1); auto& vec = *_storage->datevec_ptr; // Since JS dates have no timezone context, all dates are assumed to be UTC _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { const auto d = Local::Cast(p); auto& dt = vec[0]; const auto local = Nan::To(d).ToLocalChecked() ; const auto ms = local->Value() - offset * 60000; const TimestampColumn sql_date(-1, ms); sql_date.ToDateStruct(dt); _indvec[0] = sizeof(SQL_DATE_STRUCT); } } void BoundDatum::bind_date_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_date(len); auto& vec = *_storage->datevec_ptr; for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; const auto elem = Nan::Get(arr, i).ToLocalChecked(); if (!elem->IsNullOrUndefined()) { const auto d = Local::Cast(elem); auto& dt = vec[i]; const auto local = Nan::To(d).ToLocalChecked() ; const auto ms = local->Value() - offset * 60000; const TimestampColumn sql_date(-1, ms); sql_date.ToDateStruct(dt); _indvec[i] = sizeof(SQL_DATE_STRUCT); } } } void BoundDatum::reserve_date(SQLLEN len) { buffer_len = sizeof(SQL_DATE_STRUCT); _storage->ReserveDate(len); _indvec.resize(len); // Since JS dates have no timezone context, all dates are assumed to be UTC js_type = JS_DATE; c_type = SQL_C_TYPE_DATE; // TODO: Determine proper SQL type based on version of server we're talking to sql_type = SQL_TYPE_DATE; buffer = _storage->datevec_ptr->data(); // TODO: Determine proper precision and size based on version of server we're talking to if (param_size <= 0) param_size = sql_server_2008_default_datetime_precision; digits = sql_server_2008_default_datetime_scale; if (is_bcp) { param_size = sizeof(SQL_DATE_STRUCT); sql_type = SQLDATEN; } } void BoundDatum::bind_time_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_time(len); auto& vec = *_storage->time2vec_ptr; for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; const auto elem = Nan::Get(arr, i).ToLocalChecked(); if (!elem->IsNullOrUndefined()) { // dates in JS are stored internally as ms count from Jan 1, 1970 const auto d = Local::Cast(elem); auto& time2 = vec[i]; const auto local = Nan::To(d).ToLocalChecked() ; const auto ms = local->Value() - offset * 60000; const TimestampColumn sql_date(-1, ms); sql_date.ToTime2Struct(time2); _indvec[i] = sizeof(SQL_SS_TIME2_STRUCT); } } } void BoundDatum::bind_time(const Local& p) { reserve_time(1); // Since JS dates have no timezone context, all dates are assumed to be UTC _indvec[0] = SQL_NULL_DATA; auto& vec = *_storage->time2vec_ptr; if (!p->IsNullOrUndefined()) { const auto d = Local::Cast(p); auto& time2 = vec[0]; const auto local = Nan::To(d).ToLocalChecked() ; const auto ms = local->Value() - offset * 60000; const TimestampColumn sql_date(-1, ms); sql_date.ToTime2Struct(time2); _indvec[0] = sizeof(SQL_SS_TIME2_STRUCT); } } void BoundDatum::reserve_time(const SQLLEN len) { buffer_len = static_cast(len * sizeof(SQL_SS_TIME2_STRUCT)); _storage->Reservetime2(len); _indvec.resize(len); // Since JS dates have no timezone context, all dates are assumed to be UTC js_type = JS_DATE; c_type = SQL_C_BINARY; // TODO: Determine proper SQL type based on version of server we're talking to sql_type = SQL_SS_TIME2; buffer = _storage->time2vec_ptr->data(); // TODO: Determine proper precision and size based on version of server we're talking to param_size = sql_server_2008_default_time_precision; if (digits <= 0) digits = sql_server_2008_default_datetime_scale; if (is_bcp) { sql_type = SQLTIMEN; param_size = sizeof(SQL_SS_TIME2_STRUCT); } } void BoundDatum::bind_time_stamp(const Local& p) { reserve_time_stamp(1); _indvec[0] = SQL_NULL_DATA; auto& vec = *_storage->timestampvec_ptr; if (!p->IsNullOrUndefined()) { // dates in JS are stored internally as ms count from Jan 1, 1970 const auto d = Local::Cast(p); auto& ts = vec[0]; const auto local = Nan::To(d).ToLocalChecked() ; const auto ms = local->Value() - offset * 60000; const TimestampColumn sql_date(-1, ms); sql_date.to_timestamp_struct(ts); _indvec[0] = buffer_len; } } void BoundDatum::bind_time_stamp_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_time_stamp(len); auto& vec = *_storage->timestampvec_ptr; for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; const auto elem = Nan::Get(arr, i).ToLocalChecked(); if (!elem->IsNullOrUndefined()) { // dates in JS are stored internally as ms count from Jan 1, 1970 const auto d = Local::Cast(elem); auto& ts = vec[i]; const auto local = Nan::To(d).ToLocalChecked() ; const auto ms = local->Value() - offset * 60000; const TimestampColumn sql_date(-1, ms); sql_date.to_timestamp_struct(ts); _indvec[i] = sizeof(SQL_TIMESTAMP_STRUCT); } } } void BoundDatum::reserve_time_stamp(const SQLLEN len) { buffer_len = static_cast(len) * static_cast(sizeof(SQL_TIMESTAMP_STRUCT)); _storage->ReserveTimestamp(len); _indvec.resize(len); // Since JS dates have no timezone context, all dates are assumed to be UTC js_type = JS_DATE; c_type = SQL_C_TIMESTAMP; // TODO: Determine proper SQL type based on version of server we're talking to sql_type = SQL_TYPE_TIMESTAMP; buffer = _storage->timestampvec_ptr->data(); // TODO: Determine proper precision and size based on version of server we're talking to param_size = sql_server_2008_default_timestamp_precision; if (digits <= 0) digits = sql_server_2008_default_datetime_scale; if (is_bcp) { sql_type = SQLDATETIME2N; param_size = sizeof(SQL_TIMESTAMP_STRUCT); } } void BoundDatum::bind_time_stamp_offset(const Local& p) { reserve_time_stamp_offset(1); // Since JS dates have no timezone context, all dates are assumed to be UTC _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { const auto date_object = Local::Cast(p); assert(!date_object.IsEmpty()); // dates in JS are stored internally as ms count from Jan 1, 1970 const auto local = Nan::To(date_object).ToLocalChecked(); auto& ts = (*_storage->timestampoffsetvec_ptr)[0]; const TimestampColumn sql_date(-1, local->Value(), 0, offset); sql_date.to_timestamp_offset(ts); _indvec[0] = buffer_len; } } void BoundDatum::reserve_time_stamp_offset(SQLLEN len) { buffer_len = sizeof(SQL_SS_TIMESTAMPOFFSET_STRUCT); _storage->timestampoffsetvec_ptr = make_shared>(len); _indvec.resize(len); // Since JS dates have no timezone context, all dates are assumed to be UTC js_type = JS_DATE; c_type = SQL_C_BINARY; // TODO: Determine proper SQL type based on version of server we're talking to sql_type = SQL_SS_TIMESTAMPOFFSET; buffer = _storage->timestampoffsetvec_ptr->data(); // TODO: Determine proper precision and size based on version of server we're talking to param_size = sql_server_2008_default_datetime_precision; if (digits <= 0) digits = sql_server_2008_default_datetime_scale; if (is_bcp) { sql_type = SQLDATETIMEOFFSETN; param_size = sizeof(SQL_SS_TIMESTAMPOFFSET_STRUCT); } } void BoundDatum::bind_time_stamp_offset_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_time_stamp_offset(len); auto& vec = *_storage->timestampoffsetvec_ptr; buffer_len = sizeof(SQL_SS_TIMESTAMPOFFSET_STRUCT); for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; const auto elem = Nan::Get(arr, i).ToLocalChecked(); if (!elem->IsNullOrUndefined()) { _indvec[i] = sizeof(SQL_SS_TIMESTAMPOFFSET_STRUCT); const auto d = Local::Cast(elem); auto& ts = vec[i]; const auto local = Nan::To(d).ToLocalChecked(); TimestampColumn sql_date(-1, local->Value(), 0, offset); sql_date.to_timestamp_offset(ts); } } } void BoundDatum::bind_integer(const Local& p) { reserve_integer(1); auto& vec = *_storage->int64vec_ptr; _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { const auto local = Nan::To(p).ToLocalChecked(); vec[0] = static_cast(local->Value()); _indvec[0] = 0; } } void BoundDatum::reserve_integer(const SQLLEN len) { constexpr auto size = sizeof(int64_t); _storage->ReserveInt64(len); _indvec.resize(len); js_type = JS_NUMBER; c_type = SQL_C_SBIGINT; sql_type = SQL_BIGINT; buffer = _storage->int64vec_ptr->data(); buffer_len = static_cast(size) * len; param_size = size; digits = 0; if (is_bcp) { sql_type = SQLINT8; param_size = sizeof(int64_t); } } void BoundDatum::bind_integer_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_integer(len); auto& vec = *_storage->int64vec_ptr; for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; const auto elem = Nan::Get(arr, i).ToLocalChecked(); if (!elem->IsNullOrUndefined()) { _indvec[i] = 0; const auto v = Nan::To(elem).ToChecked(); vec[i] = v; } } } void BoundDatum::bind_float(const Local& p) { bind_double(p); sql_type = SQL_FLOAT; } void BoundDatum::bind_real(const Local& p) { bind_double(p); sql_type = SQL_REAL; } void BoundDatum::bind_double(const Local& p) { reserve_double(1); auto& vec = *_storage->doublevec_ptr; _indvec[0] = SQL_NULL_DATA; if (!p->IsNullOrUndefined()) { const auto v = Nan::To(p).ToChecked(); vec[0] = v; _indvec[0] = 0; } } void BoundDatum::reserve_double(const SQLLEN len) { constexpr auto size = sizeof(double); _storage->ReserveDouble(len); _indvec.resize(len); js_type = JS_NUMBER; c_type = SQL_C_DOUBLE; sql_type = SQL_DOUBLE; buffer = _storage->doublevec_ptr->data(); buffer_len = static_cast(size) * len; param_size = size; digits = 0; if (is_bcp) { sql_type = SQLFLT8; param_size = sizeof(double); } } void BoundDatum::bind_double_array(const Local& p) { const auto arr = Local::Cast(p); const auto len = arr->Length(); reserve_double(len); auto& vec = *_storage->doublevec_ptr; for (uint32_t i = 0; i < len; ++i) { _indvec[i] = SQL_NULL_DATA; auto maybe = Nan::Get(arr, i); if (maybe.IsEmpty()) continue; const auto local_elem = maybe.ToLocalChecked(); if (local_elem->IsNullOrUndefined()) continue; const auto v = Nan::To(local_elem).ToChecked(); vec[i] = v; if (is_bcp) { _indvec[i] = sizeof(double); } else { _indvec[i] = 0; } } } void BoundDatum::bind_number(const Local& p) { // numbers can be either integers or doubles. We attempt to determine which it is through a simple // cast and equality check const nodeTypeFactory fact; const auto context = fact.isolate->GetCurrentContext(); const auto maybe = p->ToNumber(context); Local local; if (maybe.ToLocal(&local)) { const auto d = static_cast(local->Value()); if (d == floor(d) && d >= static_cast(numeric_limits::min()) && d <= static_cast(numeric_limits::max())) { bind_integer(p); } else { bind_double(p); } } } void BoundDatum::bind_number_array(const Local& pp) { const nodeTypeFactory fact; const auto context = fact.isolate->GetCurrentContext(); const auto arr = Local::Cast(pp); const auto maybe_elem = arr->Get(context, 0); Local p; if (maybe_elem.ToLocal(&p)) { const auto maybe = p->ToNumber(context); Local local; if (maybe.ToLocal(&local)) { const auto d = static_cast(local->Value()); if (d == floor(d) && d >= static_cast(numeric_limits::min()) && d <= static_cast(numeric_limits::max())) { bind_integer_array(pp); } else { bind_double_array(pp); } } } } bool BoundDatum::bind(const Local o, const char* if_str, const uint16_t type) { auto val = Nan::Get(o, Nan::New(if_str).ToLocalChecked()).ToLocalChecked(); if (!val->IsUndefined()) { param_type = type; return bind_datum_type(val); } return false; } bool is_numeric(const wstring& v) { const auto res = v == L""numeric"" || v == L""decimal"" || v == L""smallmoney"" || v == L""money"" || v == L""float"" || v == L""real""; return res; } bool is_int(const wstring& v) { const auto res = v == L""smallint"" || v == L""int"" || v == L""bigint"" || v == L""tinyint""; return res; } bool is_string(const wstring& v) { const auto res = v == L""char"" || v == L""text"" || v == L""varchar""; return res; } bool is_binary(const wstring& v) { const auto res = v == L""binary""; return res; } bool is_bit(const wstring& v) { const auto res = v == L""bit""; return res; } bool is_date(const wstring& v) { const auto res = v == L""date"" || v == L""datetimeoffset"" || v == L""datetime2"" || v == L""smalldatetime"" || v == L""datetime"" || v == L""time""; return res; } bool sql_type_s_maps_to_numeric(const Local p) { const auto str = get_as_string(p, ""type_id""); const auto v = FromV8String(str); const auto res = is_numeric(v); return res; } bool sql_type_s_maps_to_u_int32(const Local p) { const auto str = get_as_string(p, ""type_id""); const auto v = FromV8String(str); const auto res = v == L""sbigint""; return res; } bool sql_type_s_maps_to_int32(const Local p) { const auto str = get_as_string(p, ""type_id""); const auto v = FromV8String(str); const auto res = is_int(v); return res; } bool sql_type_s_maps_to_string(const Local p) { const auto str = get_as_string(p, ""type_id""); const auto v = FromV8String(str); const auto res = is_string(v); return res; } bool sql_type_s_maps_to_boolean(const Local p) { const auto str = get_as_string(p, ""type_id""); const auto v = FromV8String(str); const auto res = is_bit(v); return res; } bool sql_type_s_maps_to_date(const Local p) { const auto str = get_as_string(p, ""type_id""); const auto v = FromV8String(str); const auto res = is_date(v); return res; } bool BoundDatum::bind_datum_type(Local& p) { const nodeTypeFactory fact; const auto context = fact.isolate->GetCurrentContext(); if (p->IsNull()) { bind_null(p); } else if (p->IsString()) { bind_w_var_char(p); } else if (p->IsBoolean()) { bind_boolean(p); } else if (p->IsInt32()) { bind_int32(p); } else if (p->IsUint32()) { bind_uint32(p); } else if (p->IsNumber()) { const auto maybe = p->ToNumber(context); Local local; if (maybe.ToLocal(&local)) { const auto d = local->Value(); if (isnan(d) || !isfinite(d)) { err = const_cast(""Invalid number parameter""); return false; } bind_number(p); } } else if (p->IsDate()) { bind_time_stamp_offset(p); } else if (p->IsObject() && node::Buffer::HasInstance(p)) { bind_var_binary(p); } else if (sql_type_s_maps_to_tvp(p)) { bind_tvp(p); } else { err = const_cast(""Invalid parameter type""); return false; } return true; } Local reserve_output_param(const Local p, const int size) { Local pval; const nodeTypeFactory fact; if (sql_type_s_maps_to_int32(p) || sql_type_s_maps_to_boolean(p)) { pval = fact.new_int32(0); } else if (sql_type_s_maps_to_u_int32(p)) { pval = Nan::New(0); } else if (sql_type_s_maps_to_numeric(p)) { pval = Nan::New(0.0); } else if (sql_type_s_maps_to_date(p)) { pval = fact.new_date(); } else if (sql_type_s_maps_to_string(p)) { vector b; b.resize(static_cast(size) + 1); pval = fact.new_string(b.data(), size + 1); } else { pval = fact.new_buffer(size); } return pval; } inline Local get(const char * key,Local local_object ) { return Nan::Get(local_object, Nan::New(key).ToLocalChecked()).ToLocalChecked(); } bool BoundDatum::proc_bind(Local& p, Local& v) { const auto context = Nan::GetCurrentContext(); const auto maybe_is_output = v->ToInteger(context); Local is_output; if (!maybe_is_output.ToLocal(&is_output)) { return false; } Local pval; const auto maybe_object = p->ToObject(context); Local local_object; if (!maybe_object.ToLocal(&local_object)) { return false; } const auto maybe_size = get(""max_length"", local_object)->Int32Value(context); auto size = 0; if (!maybe_size.To(&size)) { return false; } Local as_object; if (p->ToObject(context).ToLocal(&as_object)) { pval = get(""val"", as_object); } else { pval = Nan::Null(); } auto is_output_i = 0; if (!is_output->Int32Value(context).To(&is_output_i)) { return false; } if (is_output_i != 0) { if (pval->IsNull()) { param_type = SQL_PARAM_OUTPUT; pval = reserve_output_param(p, size); } else { param_type = SQL_PARAM_INPUT_OUTPUT; } } else { param_type = SQL_PARAM_INPUT; } return bind_datum_type(pval); } void BoundDatum::assign_precision(Local& pv) { const auto context = Nan::GetCurrentContext(); const auto precision = get(""precision"", pv); if (!precision->IsUndefined()) { const auto maybe_param_size = precision->Int32Value(context); param_size = maybe_param_size.FromMaybe(0); } const auto bcp = get(""bcp"", pv); if (!bcp->IsUndefined()) { is_bcp = Nan::To(bcp).ToChecked(); if (is_bcp) { const auto table_name_str = get_as_string(pv, ""table_name""); if (!table_name_str->IsNullOrUndefined()) { _storage->table = wide_from_js_string(table_name_str); } const auto position = get(""ordinal_position"", pv); if (!position->IsUndefined()) { const auto maybe_offset = position->Int32Value(context); ordinal_position = static_cast(maybe_offset.FromMaybe(0)); } } } const auto scale = get(""scale"", pv); if (!scale->IsUndefined()) { const auto maybe_digits = scale->Int32Value(context); digits = static_cast(maybe_digits.FromMaybe(0)); } const auto off = get(""offset"", pv); if (!off->IsUndefined()) { const auto maybe_offset = off->Int32Value(context); offset = static_cast(maybe_offset.FromMaybe(0)); } } void BoundDatum::sql_longvarbinary(Local pp) { if (pp->IsArray()) { bind_var_binary_array(pp); } else { bind_long_var_binary(pp); } } void BoundDatum::sql_integer(const Local pp) { if (pp->IsArray()) { bind_int32_array(pp); } else { bind_int32(pp); } } void BoundDatum::sql_wvarchar(const Local pp) { if (pp->IsArray()) { bind_w_var_char_array(pp); } else { bind_w_var_char(pp); } } void BoundDatum::sql_wlongvarchar(const Local pp) { if (pp->IsArray()) { bind_w_var_char_array(pp); } else { bind_w_long_var_char(pp); } } void BoundDatum::sql_bit(const Local pp) { if (pp->IsArray()) { bind_boolean_array(pp); } else { bind_boolean(pp); } } void BoundDatum::sql_bigint(const Local pp) { if (pp->IsArray()) { bind_integer_array(pp); } else { bind_integer(pp); } } void BoundDatum::sql_double(const Local pp) { if (pp->IsArray()) { bind_double_array(pp); } else { bind_double(pp); } } void BoundDatum::sql_float(const Local pp) { if (pp->IsArray()) { bind_double_array(pp); if (!is_bcp) { sql_type = SQL_FLOAT; } } else { bind_float(pp); } } void BoundDatum::sql_real(const Local pp) { if (pp->IsArray()) { bind_double_array(pp); if (!is_bcp) { sql_type = SQL_REAL; } } else { bind_real(pp); } } void BoundDatum::sql_tinyint(const Local pp) { if (pp->IsArray()) { bind_int32_array(pp); if (!is_bcp) { sql_type = SQL_TINYINT; } } else { bind_tiny_int(pp); } } void BoundDatum::sql_smallint(const Local pp) { if (pp->IsArray()) { bind_int32_array(pp); if (!is_bcp) { sql_type = SQL_SMALLINT; } } else { bind_small_int(pp); } } void BoundDatum::sql_numeric(const Local pp) { if (pp->IsArray()) { if (is_bcp) { bind_numeric_array(pp); } else { bind_double_array(pp); } } else { bind_numeric(pp); } } void BoundDatum::sql_char(const Local pp) { if (pp->IsArray()) { bind_w_var_char_array(pp); } else { bind_char(pp); } } void BoundDatum::sql_varchar(const Local pp) { if (pp->IsArray()) { if (is_bcp) { bind_var_char_array(pp); } else { bind_w_var_char_array(pp); } } else { bind_w_var_char(pp); } } void BoundDatum::sql_ss_time2(const Local pp) { if (pp->IsArray()) { bind_time_array(pp); } else { bind_time(pp); } } void BoundDatum::sql_type_date(const Local pp) { if (pp->IsArray()) { bind_date_array(pp); } else { bind_date(pp); } } void BoundDatum::sql_type_timestamp(const Local pp) { if (pp->IsArray()) { bind_time_stamp_array(pp); } else { bind_time_stamp(pp); } } void BoundDatum::sql_ss_timestampoffset(const Local pp) { if (pp->IsArray()) { bind_time_stamp_offset_array(pp); } else { bind_time_stamp_offset(pp); } } void BoundDatum::sql_varbinary(Local pp) { if (pp->IsArray()) { bind_var_binary_array(pp); } else { if (pp->IsNull() || (pp->IsObject() && node::Buffer::HasInstance(pp))) { bind_var_binary(pp); } else { err = const_cast(""Invalid parameter type""); } } } bool BoundDatum::user_bind(Local& p, Local& v) { const nodeTypeFactory fact; const auto context = fact.isolate->GetCurrentContext(); const auto maybe_sql_type = v->Int32Value(fact.isolate->GetCurrentContext()); const auto local_sql_type = maybe_sql_type.FromMaybe(0); if (local_sql_type == 0) return false; sql_type = static_cast(local_sql_type); param_type = SQL_PARAM_INPUT; const auto maybe_local = p->ToObject(context); Local as_local; if (!maybe_local.ToLocal(&as_local)) { return false; } const auto pp = get(""value"", as_local); assign_precision(as_local); switch (sql_type) { case SQL_LONGVARBINARY: sql_longvarbinary(pp); break; case SQL_VARBINARY: { sql_varbinary(pp); if (err) return false; } break; case SQL_INTEGER: sql_integer(pp); break; case SQL_VARCHAR: sql_varchar(pp); break; case SQL_WVARCHAR: sql_wvarchar(pp); break; case SQL_WLONGVARCHAR: sql_wlongvarchar(pp); break; case SQL_BIT: sql_bit(pp); break; case SQL_BIGINT: sql_bigint(pp); break; case SQL_DOUBLE: sql_double(pp); break; case SQL_FLOAT: sql_float(pp); break; case SQL_REAL: sql_real(pp); break; case SQL_TINYINT: sql_tinyint(pp); break; case SQL_SMALLINT: sql_smallint(pp); break; case SQL_NUMERIC: sql_numeric(pp); break; case SQL_CHAR: sql_char(pp); break; case SQL_SS_TIME2: sql_ss_time2(pp); break; case SQL_TYPE_DATE: sql_type_date(pp); break; case SQL_TYPE_TIMESTAMP: sql_type_timestamp(pp); break; case SQL_SS_TIMESTAMPOFFSET: sql_ss_timestampoffset(pp); break; case SQL_UNKNOWN_TYPE: default: return false; } return true; } bool BoundDatum::bind_object(Local& p) { // fprintf(stderr, ""bind obj\\n""); const nodeTypeFactory fact; const auto context = fact.isolate->GetCurrentContext(); const auto maybe_object = p->ToObject(context); Local po; if (!maybe_object.ToLocal(&po)) { return false; } auto v = get(""is_output"", po); if (!v->IsUndefined()) { return proc_bind(p, v); } v = get(""sql_type"", po); if (!v->IsUndefined()) { return user_bind(p, v); } const auto n = get_as_string(p, ""name""); if (!n->IsUndefined()) { name = wide_from_js_string(n); auto pp = get(""value"", po); return bind_datum_type(pp); } return false; } bool BoundDatum::bind_array(Local& pp) { const auto arr = Local::Cast(pp); nodeTypeCounter counts; for (uint32_t i = 0; i < arr->Length(); ++i) { auto p = Nan::Get(arr, i); const auto l = p.ToLocalChecked(); counts.Decode(l); } if (counts.boolCount != 0) { bind_boolean_array(pp); } else if (counts.stringCount != 0) { bind_w_var_char_array(pp); } else if (counts.dateCount != 0) { bind_time_stamp_offset_array(pp); } else if (counts.bufferCount != 0) { bind_var_binary_array(pp); } else if (counts.getoutBoundsCount() > 0) { err = const_cast(""Invalid number parameter""); return false; } else if (counts.numberCount > 0 || (counts.int64Count > 0 && counts.int32Count > 0)) { bind_double_array(pp); } else if (counts.int64Count > 0) { bind_integer_array(pp); } else if (counts.int32Count != 0) { bind_int32_array(pp); } else if (counts.uint32Count != 0) { bind_uint32_array(pp); } else if (counts.nullCount == static_cast(arr->Length())) { bind_null_array(pp); } else { err = const_cast(""Invalid parameter type""); return false; } return true; } Local BoundDatum::unbind_null() { const nodeTypeFactory fact; return fact.null(); } Local BoundDatum::unbind_string() const { const auto s = Nan::New(_storage->uint16vec_ptr->data()).ToLocalChecked(); return s; } Local BoundDatum::unbind_double() const { const auto& vec = *_storage->doublevec_ptr; const auto s = Nan::New(vec[0]); return s; } Local BoundDatum::unbind_boolean() const { const auto& vec = *_storage->uint16vec_ptr; const auto s = Nan::New(vec[0] != 0); return s; } Local BoundDatum::unbind_int32() const { const auto& vec = *_storage->int32vec_ptr; const auto s = Nan::New(vec[0]); return s; } Local BoundDatum::unbind_uint32() const { const auto& vec = *_storage->uint32vec_ptr; const auto s = Nan::New(vec[0]); return s; } Local BoundDatum::unbind_number() const { Local v; if (sql_type == SQL_C_DOUBLE) { v = unbind_double(); } else { const nodeTypeFactory fact; const auto& vec = *_storage->int64vec_ptr; v = fact.new_int64(vec[0]); } return v; } Local BoundDatum::unbind_date() const { const auto& vec = *_storage->timestampoffsetvec_ptr; TimestampColumn tsc(-1, vec[0]); return tsc.ToValue(); } void BoundDatum::reserve_column_type(const SQLSMALLINT type, const size_t len, const size_t row_count) { switch (type) { case SQL_SS_VARIANT: reserve_w_var_char_array(len, row_count); break; case SQL_CHAR: case SQL_VARCHAR: case SQL_LONGVARCHAR: case SQL_WCHAR: case SQL_WVARCHAR: case SQL_WLONGVARCHAR: case SQL_SS_XML: case SQL_GUID: reserve_w_var_char_array(len + 1, row_count); break; case SQL_BIT: reserve_boolean(static_cast(row_count)); break; case SQL_SMALLINT: case SQL_TINYINT: case SQL_INTEGER: case SQL_C_SLONG: case SQL_C_SSHORT: case SQL_C_STINYINT: case SQL_C_ULONG: case SQL_C_USHORT: case SQL_C_UTINYINT: case SQL_BIGINT: reserve_integer(static_cast(row_count)); break; case SQL_DECIMAL: case SQL_NUMERIC: case SQL_REAL: case SQL_FLOAT: case SQL_DOUBLE: reserve_double(static_cast(row_count)); break; case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: case SQL_SS_UDT: reserve_var_binary_array(len, row_count); break; case SQL_SS_TIMESTAMPOFFSET: reserve_time_stamp_offset(static_cast(row_count)); break; case SQL_TYPE_TIME: case SQL_SS_TIME2: reserve_time(static_cast(row_count)); break; case SQL_TIMESTAMP: case SQL_DATETIME: case SQL_TYPE_TIMESTAMP: case SQL_TYPE_DATE: reserve_time_stamp(static_cast(row_count)); break; default: reserve_w_var_char_array(len, row_count); break; } } Local BoundDatum::unbind() const { Local v; switch (js_type) { case JS_STRING: v = unbind_string(); break; case JS_BOOLEAN: v = unbind_boolean(); break; case JS_INT: v = unbind_int32(); break; case JS_UINT: v = unbind_uint32(); break; case JS_DATE: v = unbind_double(); break; case JS_NUMBER: v = unbind_number(); break; default: v = unbind_null(); break; } return v; } } ",16153,True,3421.88276195845,median " /// **************************************************************************** /// \\file GoTender.cpp /// /// \\brief main code /// /// \\details GoTender /// /// \\author Christoph Capiaghi, Anne Liebold /// /// \\version 1.0 /// /// \\date 20170825 /// /// \\copyright Licensed under the Apache License, Version 2.0 (the ""License""); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// http://www.apache.org/licenses/LICENSE-2.0 /// /// \\pre /// /// \\bug /// /// \\warning /// /// \\todo - Testing /// // **************************************************************************** // Includes ******************************************************************* #include // SD Card Library (not used yet) // Own Includes: #include ""Config.h"" // Configuration, true false statement #include ""ButtonHandler.h"" // Read out Buttons #include ""Startup.h"" // Startup sequence #include ""PinMapping.h"" // All Pin Definitons #include ""Display.h"" // Display Handler #include ""Potentiometers.h"" // Read out Potentiometers Meat and Oven #include ""Controller.h"" // Controls the run state //#include ""Countimer.h"" // Counter von GitHub //#include ""TimerThree.h"" // für PWM Signal //#include ""FlexiTimer2.h"" // für PWM Signal // Private types ************************************************************** /// \\brief Used States /// \\details States for the main state machine TBD typedef enum stm_state_e { STM_STATE_STARTUP, /// Reserved and implemented for later: EEPROM loading STM_TIME_AND_DATE, /// Set Hour, min, day, month and year (optional state) STM_STATE_SETTINGS, /// Set Temperatures, smoker, timer yes or no STM_STATE_SET_TIMER, /// Set Timer (optional state) STM_STATE_SUMMARY, /// Shows all values. Clearance for start STM_STATE_RUN, /// Runs the Oven STM_STATE_FINISHED, /// Meal finished STM_STATE_ERROR, /// Starts LED Test (small LEDs, red and green) } stm_state_t; typedef unsigned char stm_bool_t; //TBD /// \\brief Used SubStates /// \\details States for the settings state machine typedef enum stm_substate_e { STM_SUBSTATE_SET_TIME, /// RTC Time and Date STM_SUBSTATE_SET_TEMPERATURE_OVEN, /// Set temperature STM_SUBSTATE_SET_TEMPERATURE_MEAT, STM_SUBSTATE_SET_SMOKER, /// Enable or disable smoker STM_SUBSTATE_SET_TIMER, /// thet clock STM_SUBSTATE_DONE, /// Next main state } stm_substate_t; /// \\brief Used SubStates time /// \\details States for the settings state machine typedef enum stm_substate_time_e { STM_SUBSTATE_SET_HOUR, /// RTC Hour STM_SUBSTATE_SET_MIN, /// RTC Min STM_SUBSTATE_SET_HOUR_TIMER, /// RTC Hour TIMER STM_SUBSTATE_SET_MIN_TIMER, /// RTC Min TIMER STM_SUBSTATE_SET_DAY, /// RTC Day STM_SUBSTATE_SET_MONTH, /// RTC Month STM_SUBSTATE_SET_YEAR, /// RTC YEAR } stm_substate_time_t; typedef enum stm_subState_control_e { STM_SUBSTATE_HEATING, /// Temperature < SetTemperature - LOWER_BOUND STM_SUBSTATE_PULSING, /// Temperature < SetTemperature + UPPER_BOUND STM_SUBSTATE_OFF, /// Temperature > UPPER_BOUND STM_SUBSTATE_WAIT /// Cooling down till temperature < SetTemperature - LOWER_BOUND } stm_subState_control_t; #define UPPER_LEVEL_TEMP ( 4 ) // SET_POINT + UPPER_LEVEL_TEMP #define LOWER_LEVEL_TEMP ( 5 ) // SET_POINT - LOWER_LEVEL_TEMP #define HEATER_ON_TIME_S ( 35 ) // in seconds #define HEATER_OFF_TIME_S ( 8*60 ) // #define SMOKER_ON_TIME_S ( 40 ) // #define SMOKER_OFF_TIME_S ( 7*60 ) // #define MAX_SMOKER_TIME_S ( 80 ) // Safety system: Smoker is maximum 80 seconds allowed #define NUM_OF_SMOKER_CYCLES_BUTTON ( 1 ) // After pressing the button, 1 smoker cycle is executed uint8_t numOfSmokerCycles = 7; // Predefined vaule for number of smoker cycle. Switch override this value with NUM_OF_SMOKER_CYCLES_BUTTON. uint8_t currentNumOfSmokerCycles = 0; // used to determine how many pulses the smoker does uint16_t maxSmokerTimeS = 0; uint16_t pulsingCounterS = 0; uint16_t pulsingCounterSmokerS = 0; uint16_t LowerLevelHeater = 0; uint16_t UpperLevelHeater = 0; bool first = true; // Temperature profile // HEATER OFF // ------------------------------------------------------ setPoint + UPPER_LEVEL_TEMP // PULSING: 40 s on / 5 min off AND SMOKER CONTROL // ------------------------------------------------------ setPoint // PULSING: 40 s on / 5 min off AND SMOKER CONTROL // ------------------------------------------------------ setPoint - LOWER_LEVEL_TEMP // HEATER ON // Private constants ********************************************************** const char SOFTWARE_VERSION[10] = ""V1.0""; #define UART_SPEED ( 115200 ) #define MAX_TEMPERATURE_OVEN ( 240 ) #define MAX_TEMPERATURE_MEAT ( 240 ) // Private macros ************************************************************* // Static variables *********************************************************** static stm_state_t stm_actState; // Actual State variable static stm_state_t stm_newState; // New State variable static stm_bool_t stm_entryFlag; // Flag for handling the entry action static stm_bool_t stm_exitFlag; // Flag for handling the exit action static stm_bool_t stm_sub_entryFlag; static stm_substate_t stm_SubState; static stm_substate_time_t stm_SubState_time; static stm_subState_control_t stm_subState_control; // Private function prototypes *********************************************** // Private functions ********************************************************** static uint16_t value = 0; static uint8_t nextState = 0; static uint16_t oldValue = 0; static bool timerSet = false; static bool sysOkay = true; // ISR ********************************************************** // ---------------------------------------------------------------------------- /// \\brief Timer 3 interrupt /// \\detail For measurement: Every 1 s an interrupt /// \\warning /// \\return /// \\todo /// uint8_t sysTick; ISR(TIMER3_COMPA_vect) { sysTick = 1; } /// \\brief Timer 4 interrupt /// \\detail For measurement: Every 100 ms an interrupt /// \\warning /// \\return /// \\todo /// uint8_t sysTickFast; ISR(TIMER4_COMPA_vect) { sysTickFast = 1; } // Initialization ********************************************************** // The setup function runs once when you press reset or power the board void setup() { // Timer for Controller // Init timer 3, interrupts every second TCCR3A = 0; TCCR3B = 0xc; // CTC mode, prescaler = 256+ (clk/256 (From prescaler) OCR3A = 62500; // 16 MHz / 256 = 62500 gives exactly one second (2 Output Compare Regis TIMSK3 |= 0x02; // Enable output compare match ints // Init timer 4, interrupts every 100 ms TCCR4A = 0; TCCR4B = 0xc; OCR4A = 6250; // 16 MHz / 256 = 62500 gives exactly one second (2 Output Compare Register) -> 6250: 100 ms TIMSK4 |= 0x02; // Enable output compare match ints sei(); // Enable interrupts // Initialize LEDs pinMode(GREEN_LED_PIN, OUTPUT); pinMode(RED_LED_PIN, OUTPUT); pinMode(YELLOW_LED_PIN, OUTPUT); // Initialize Buttons initButton(); // Initialize Relais pinMode(RELAIS_HEATER, OUTPUT); pinMode(RELAIS_SMOKER, OUTPUT); // Initialize Serial Port Serial.begin( UART_SPEED ); // Initialize state machine stm_entryFlag = TRUE; stm_sub_entryFlag = TRUE; stm_exitFlag = FALSE; stm_newState = STM_STATE_STARTUP; stm_actState = STM_STATE_STARTUP; // Initialize Display initDisplay(); // wait for MAX chip to stabilize delay(500); } // Loop ********************************************************** // The loop function runs over and over again forever void loop() { // if(getButtonStateSmoker()) //{ //} updateButtonHandler(); switch (stm_actState) { //============================================================================== // STM_STATE_STARTUP //============================================================================== case STM_STATE_STARTUP: /// - Path 1 \\n /// Startup: /// Initialize Thermocouples /// Check for Errors // Entry action if (stm_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""Entered STM_STATE_STARTUP"")); #endif displayTitle(""Go Tender""); displayCommand(""Checking Sys""); Serial.print(""Software Version: ""); Serial.println(SOFTWARE_VERSION); delay(800); // Startup if(startup()) { Serial.println(F(""Startup ok"")); displayCommand(""Sys ok""); } else { Serial.println(F(""Startup not ok"")); displayCommand(""Sys not ok""); // TBD: Do something } delay(2000); displayTitle(""Welcome""); delay(2000); clearButtonAllFlags(); displayCommand(""Set Time?""); displayCommandSmall1(""Set Time: Press Enter""); displayCommandSmall2(""Next: Press Down""); displayDate(); stm_entryFlag = FALSE; } displayTemperatures(); if(getButtonStateEnter()) { stm_newState = STM_TIME_AND_DATE; stm_exitFlag = TRUE; } if(getButtonStateDown()) { stm_newState = STM_STATE_SETTINGS; stm_exitFlag = TRUE; } // Exit if (stm_exitFlag == TRUE) { // do exit action clearButtonAllFlags(); stm_exitFlag = FALSE; stm_actState = stm_newState; stm_entryFlag = TRUE; } break; //============================================================================== // STM_TIME_AND_DATE //============================================================================== case STM_TIME_AND_DATE: // Entry action if (stm_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""Entered STM_TIME_AND_DATE"")); #endif stm_SubState_time = STM_SUBSTATE_SET_HOUR; value = 0; clearButtonAllFlags(); stm_entryFlag = FALSE; } switch(stm_SubState_time) { case STM_SUBSTATE_SET_HOUR: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_HOUR"")); #endif displayTitle(""SET_HOUR""); testDisplayOutput(value); stm_sub_entryFlag = FALSE; } if(value > 23) value = 0; // Show value on display // Display only, if the value changes if (value != oldValue) { #ifdef DEBUG Serial.print(""Time hour: ""); Serial.println( value ); #endif testDisplayOutput(value); oldValue = value; } if(nextState == 1) { #ifdef DEBUG Serial.print(""Time hour SET: ""); Serial.println( value ); #endif setTimeHour(value); value = 1; nextState = 0; stm_sub_entryFlag = TRUE; stm_SubState_time = STM_SUBSTATE_SET_MIN; } break; case STM_SUBSTATE_SET_MIN: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_MIN"")); #endif displayTitle(""SET_MIN""); testDisplayOutput(value); stm_sub_entryFlag = FALSE; } if(value > 59) value = 0; // Show value on display // Display only, if the value changes if (value != oldValue) { #ifdef DEBUG Serial.print(""Time min: ""); Serial.println( value ); #endif testDisplayOutput(value); oldValue = value; } if(nextState == 1) { #ifdef DEBUG Serial.print(""Time min SET: ""); Serial.println( value ); #endif setTimeMin(value); value = 1; nextState = 0; stm_sub_entryFlag = TRUE; stm_SubState_time = STM_SUBSTATE_SET_DAY; } break; case STM_SUBSTATE_SET_DAY: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_DAY"")); #endif displayTitle(""SET_DAY""); testDisplayOutput(value); stm_sub_entryFlag = FALSE; } if(value > 31) value = 1; // Display only, if the value changes if (value != oldValue) { #ifdef DEBUG Serial.print(""Day: ""); Serial.println( value ); #endif testDisplayOutput(value); oldValue = value; } if(nextState == 1) { #ifdef DEBUG Serial.print(""Day SET: ""); Serial.println( value ); #endif setTimeDay(value); value = 1; nextState = 0; stm_sub_entryFlag = TRUE; stm_SubState_time = STM_SUBSTATE_SET_MONTH; } break; case STM_SUBSTATE_SET_MONTH: // Show value on display if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_MONTH"")); #endif displayTitle(""SET_MONTH""); testDisplayOutput(value); stm_sub_entryFlag = FALSE; } if(value > 12) value = 0; // Display only, if the value changes if (value != oldValue) { #ifdef DEBUG Serial.print(""Month: ""); Serial.println( value ); #endif testDisplayOutput(value); oldValue = value; } if(nextState == 1) { #ifdef DEBUG Serial.print(""Month SET: ""); Serial.println( value ); #endif setTimeMonth(value); value = 2017; nextState = 0; stm_sub_entryFlag = TRUE; stm_SubState_time = STM_SUBSTATE_SET_YEAR; } break; case STM_SUBSTATE_SET_YEAR: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_YEAR"")); #endif displayTitle(""SET_YEAR""); testDisplayOutput(value); stm_sub_entryFlag = FALSE; } // Show value on display // Display only, if the value changes if (value != oldValue) { #ifdef DEBUG Serial.print(""Year: ""); Serial.println( value ); #endif testDisplayOutput(value); oldValue = value; } if(nextState == 1) { #ifdef DEBUG Serial.print(""Year SET: ""); Serial.println( value ); #endif setTimeYear(value); nextState = 0; stm_sub_entryFlag = TRUE; stm_exitFlag = TRUE; stm_newState = STM_STATE_SETTINGS; } break; } if(getButtonStateUp()) { value++; } if(getButtonStateEnter()) { nextState = 1; } if(getButtonStateDown()) { value--; } // Exit if (stm_exitFlag == TRUE) { // do exit action clearButtonAllFlags(); stm_exitFlag = FALSE; stm_actState = stm_newState; stm_entryFlag = TRUE; } break; //============================================================================== // STM_STATE_SETTINGS //============================================================================== case STM_STATE_SETTINGS: /// - Path 2 \\n /// Settings: Time, Oven Temperature, meat temperature, smoker on / off // Entry action if (stm_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""Entered STM_STATE_SETTINGS"")); #endif stm_SubState = STM_SUBSTATE_SET_TEMPERATURE_OVEN; clearButtonAllFlags(); stm_entryFlag = FALSE; } //============================================================================== // SUB STATES SETTINGS // State machine with Time, Temperature, Finished switch (stm_SubState) { case STM_SUBSTATE_SET_TEMPERATURE_OVEN: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_TEMPERATURE_OVEN"")); #endif displayTitle(""TEMP OVEN""); testDisplayOutput(value); stm_sub_entryFlag = FALSE; } value = getPotentiometerOvenVal(); // Display only, if the value changes if (value != oldValue) { #ifdef DEBUG Serial.print(""Temp Oven: ""); Serial.println( value ); #endif testDisplayOutput(value); oldValue = value; } if(getButtonStateEnter()) { #ifdef DEBUG Serial.print(""Temp Oven SET: ""); Serial.println( value ); #endif setTemperatureOvenSetPoint( value ); //TBD : Tests. Warning: Sets double value stm_sub_entryFlag = TRUE; stm_SubState = STM_SUBSTATE_SET_TEMPERATURE_MEAT; } break; case STM_SUBSTATE_SET_TEMPERATURE_MEAT: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_TEMPERATURE_MEAT"")); #endif displayTitle(""TEMP MEAT""); testDisplayOutput( value ); stm_sub_entryFlag = FALSE; } value = getPotentiometerMeatVal(); // Display only, if the value changes if (value != oldValue) { #ifdef DEBUG Serial.print(""Temp Meat: ""); Serial.println( value ); #endif testDisplayOutput(value); oldValue = value; } if(getButtonStateEnter()) { #ifdef DEBUG Serial.print(""Temp Meat SET: ""); Serial.println( value ); #endif stm_sub_entryFlag = TRUE; setTemperatureMeatSetPoint( value ); //TBD : Tests. Warning: Sets double value stm_SubState = STM_SUBSTATE_SET_SMOKER; } break; case STM_SUBSTATE_SET_SMOKER: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_SMOKER"")); #endif displayTitle(""Set Smoker""); displayCommandSmall1(""Smoker Yes: Press Enter""); displayCommandSmall2(""Smoker No: Press Down""); stm_sub_entryFlag = FALSE; } if(getButtonStateEnter()) { armSmoker( true ); currentNumOfSmokerCycles = 0; pulsingCounterSmokerS = 0; stm_sub_entryFlag = TRUE; stm_SubState = STM_SUBSTATE_SET_TIMER; } if(getButtonStateDown()) { armSmoker( false ); stm_sub_entryFlag = TRUE; stm_SubState = STM_SUBSTATE_SET_TIMER; } break; case STM_SUBSTATE_SET_TIMER: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_TIMER"")); #endif displayTitle(""Timer""); displayCommandSmall1(""Set Timer: Press Enter""); displayCommandSmall2(""Next: Press Down""); displaySmokerState(); clearButtonAllFlags(); stm_sub_entryFlag = FALSE; } if(getButtonStateEnter()) { timerSet = true; // Yes, timer is set stm_newState = STM_STATE_SET_TIMER; stm_sub_entryFlag = TRUE; stm_SubState = STM_SUBSTATE_DONE; stm_exitFlag = TRUE; } if(getButtonStateDown()) { timerSet = false; // No, timer is disabled. Do not use timer setTimerHour(0); setTimerMin(0); stm_newState = STM_STATE_SUMMARY; stm_sub_entryFlag = TRUE; stm_SubState = STM_SUBSTATE_DONE; stm_exitFlag = TRUE; } break; } //============================================================================== // END SUBSTATES SETTINGS // Exit if (stm_exitFlag == TRUE) { // do exit action clearButtonAllFlags(); stm_exitFlag = FALSE; stm_actState = stm_newState; stm_entryFlag = TRUE; } break; //============================================================================== // STM_STATE_SET_TIMER //============================================================================== case STM_STATE_SET_TIMER: /// - Path 3 \\n /// Sets timer // Entry action if (stm_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""Entered STM_STATE_SET_TIMER"")); #endif timerSet = true; // Yes, timer is set stm_SubState_time = STM_SUBSTATE_SET_HOUR_TIMER; nextState = 0; value = 0; stm_entryFlag = FALSE; clearButtonAllFlags(); } switch(stm_SubState_time) { case STM_SUBSTATE_SET_HOUR_TIMER: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_HOUR_TIMER"")); #endif displayTitle(""SET_HOUR""); testDisplayOutput(value); stm_sub_entryFlag = FALSE; } if(value > 23) value = 0; // Show value on display // Display only, if the value changes if (value != oldValue) { testDisplayOutput(value); oldValue = value; } if(nextState == 1) { setTimerHour(value); value = 1; nextState = 0; stm_sub_entryFlag = TRUE; stm_SubState_time = STM_SUBSTATE_SET_MIN_TIMER; } break; case STM_SUBSTATE_SET_MIN_TIMER: if(stm_sub_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_SET_MIN"")); #endif displayTitle(""SET_MIN""); testDisplayOutput(value); stm_sub_entryFlag = FALSE; } if(value > 59) value = 0; // Show value on display // Display only, if the value changes if (value != oldValue) { testDisplayOutput(value); oldValue = value; } if(nextState == 1) { setTimerMin(value); nextState = 0; stm_sub_entryFlag = TRUE; stm_exitFlag = TRUE; stm_newState = STM_STATE_SUMMARY; } break; } if(getButtonStateUp()) { value++; } if(getButtonStateEnter()) { nextState = 1; } if(getButtonStateDown()) { value--; } #ifdef DEBUG Serial.print(""Value: ""); Serial.println(value); #endif if (stm_exitFlag == TRUE) { // do exit action clearButtonAllFlags(); stm_exitFlag = FALSE; stm_actState = stm_newState; stm_entryFlag = TRUE; } break; //============================================================================== // STM_STATE_SUMMARY //============================================================================== case STM_STATE_SUMMARY: // Entry action if (stm_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""Entered STM_STATE_SUMMARY"")); #endif displayTitle(""Summary""); displayCommand(""Check Input""); displayCommandSmall1(""GoTender Start: Press Enter""); displayCommandSmall2(""Again: Press Up""); displayRefresh(); stm_entryFlag = FALSE; } displayTemperatures(); if(getButtonStateUp()) { stm_newState = STM_STATE_SETTINGS; stm_exitFlag = TRUE; } if(getButtonStateEnter()) { stm_exitFlag = TRUE; first = true; stm_subState_control = STM_SUBSTATE_HEATING; stm_newState = STM_STATE_RUN; } // Exit if (stm_exitFlag == TRUE) { // do exit action clearButtonAllFlags(); stm_exitFlag = FALSE; stm_actState = stm_newState; stm_entryFlag = TRUE; } break; //============================================================================== // STM_STATE_RUN //============================================================================== case STM_STATE_RUN: /// - Path 4 \\n /// Settings: Oven Temperature, meat temperature, smoker on / off // Entry action if (stm_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""Entered STM_STATE_RUN"")); #endif displayTitle(""RUN""); displayRefresh(); pulsingCounterS = 0; // Hyster UpperLevelHeater = getTemperatureOvenSetPoint() + UPPER_LEVEL_TEMP; LowerLevelHeater = getTemperatureOvenSetPoint() - LOWER_LEVEL_TEMP; // Timer set? if ( timerSet ) { startTimer(); // Reads actual time and calculates end time Serial.println(F(""Starts Timer"")); } stm_entryFlag = FALSE; } // Timer expired? if ( timerSet ) { if ( timerExpired() ) { stm_newState = STM_STATE_FINISHED; stm_exitFlag = TRUE; #ifdef DEBUG Serial.println(F(""TIMER EXPIRED"")); #endif } } // LOOP displayTemperatures(); // Every second if ( sysTick ) { if ( getSmokerState() ) { maxSmokerTimeS++; } else { maxSmokerTimeS = 0; } sysTick = 0; switch(stm_subState_control) { // Low temperature: Switch heater on, smoker is off. case STM_SUBSTATE_HEATING: if ( first ) { displayCommandSmall1(""Heater On""); displayCommandSmall2(""Smoker Off""); startHeater( true ); startSmoker( false ); Serial.println(F(""SWITCH HEATER ON"")); Serial.println(F(""SWITCH SMOKER OFF"")); first = false; #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_HEATING"")); #endif } // Exit Condition if ( getTemperatureOven() > LowerLevelHeater ) { first = true; stm_subState_control = STM_SUBSTATE_PULSING; } break; // 40 s on, 5 min off case STM_SUBSTATE_PULSING: switch( pulsingCounterS ) { case 0: // Start startHeater( true ); Serial.println(F(""HEATER ON"")); displayCommandSmall1(""Pulse On""); pulsingCounterS++; #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_PULSING: Pulse On"")); #endif break; case HEATER_ON_TIME_S: // On time expired, switch off startHeater( false ); Serial.println(F(""HEATER OFF"")); displayCommandSmall1(""Pulse Off""); pulsingCounterS++; #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_PULSING: Pulse Off"")); #endif break; case ( HEATER_OFF_TIME_S + HEATER_ON_TIME_S ): pulsingCounterS = 0; break; default: pulsingCounterS++; break; } // Exit Condition if ( getTemperatureOven() > UpperLevelHeater ) { pulsingCounterS = 0; stm_subState_control = STM_SUBSTATE_OFF; } if ( getTemperatureOven() < LowerLevelHeater ) { pulsingCounterS = 0; stm_subState_control = STM_SUBSTATE_HEATING; } break; case STM_SUBSTATE_OFF: startHeater( false ); Serial.println(F(""HEATER OFF"")); displayCommandSmall1(""Heater Stop""); #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_OFF: Heater off"")); #endif stm_subState_control = STM_SUBSTATE_WAIT; break; case STM_SUBSTATE_WAIT: #ifdef DEBUG Serial.println(F(""STM_SUBSTATE_WAIT: All off"")); #endif // Exit if ( getTemperatureOven() <= LowerLevelHeater ) { stm_subState_control = STM_SUBSTATE_PULSING; } break; default: displayCommandSmall1(""ERROR""); displayCommandSmall2(""DEFAULT""); Serial.println(F(""STM_SUBSTATE_DEFAULT"")); Serial.println(F(""ERROR"")); break; } // Smoke: Only if heater off, smoker armed and x times per Intervall if ( !getHeaterState() && getArmSmokerState() ) { if ( pulsingCounterS != 0 ) { if ( currentNumOfSmokerCycles < numOfSmokerCycles ) { #ifdef DEBUG Serial.print( ""Smoker Time: ""); Serial.println( pulsingCounterSmokerS ); #endif #ifdef DEBUG Serial.print( ""Smoker Cycle: ""); Serial.print( (currentNumOfSmokerCycles + 1) ); Serial.print("" / ""); Serial.println( numOfSmokerCycles ); #endif if ( pulsingCounterSmokerS == 0) // Smoker On { startSmoker( true ); Serial.println(F(""SWITCH SMOKER ON"")); displayCommandSmall2(""Smoker Start""); pulsingCounterSmokerS++; } else if ( pulsingCounterSmokerS == SMOKER_ON_TIME_S ) // On time expired, switch off { startSmoker( false ); Serial.println(F(""SWITCH SMOKER OFF"")); displayCommandSmall2(""Smoker Stop""); pulsingCounterSmokerS++; } else if ( pulsingCounterSmokerS == ( SMOKER_ON_TIME_S + SMOKER_OFF_TIME_S ) ) { pulsingCounterSmokerS = 0; currentNumOfSmokerCycles++; } else { pulsingCounterSmokerS++; } } else if ( currentNumOfSmokerCycles == numOfSmokerCycles) { startSmoker( false ); Serial.println(F(""SWITCH SMOKER OFF"")); displayCommandSmall2(""Smoker finished""); #ifdef DEBUG Serial.println(F(""Smoker finished"")); #endif currentNumOfSmokerCycles++; } else { startSmoker( false ); } } } else { startSmoker( false ); } } if( getButtonStateUp() ) { stm_newState = STM_STATE_SETTINGS; stm_sub_entryFlag = TRUE; stm_exitFlag = TRUE; } if( getButtonStateEnter() ) { stm_newState = STM_STATE_FINISHED; stm_sub_entryFlag = TRUE; stm_exitFlag = TRUE; } if( getButtonStateDown() ) { stm_newState = STM_STATE_SET_TIMER; stm_sub_entryFlag = TRUE; stm_exitFlag = TRUE; } if ( getButtonStateSmoker() ) { currentNumOfSmokerCycles = 0; pulsingCounterSmokerS = 0; numOfSmokerCycles = NUM_OF_SMOKER_CYCLES_BUTTON; armSmoker( true ); Serial.println(F(""ButtonStateSmoker"")); // pulsingCounterS = 0; // TBD: Wenn du willst, dass der Smoker sofort wieder startet, diese Zeile auskommentieren. } // Meat temperature reached if( getTemperatureMeat() >= getTemperatureMeatSetPoint() ) { Serial.println(F(""Reached Meat SetPoint"")); stm_newState = STM_STATE_FINISHED; stm_exitFlag = TRUE; } // Exit if (stm_exitFlag == TRUE) { // do exit action clearButtonAllFlags(); startHeater( false ); // Switch off Heater startSmoker( false ); // Switch off Smoker Serial.println(F(""SWITCH SMOKER OFF"")); Serial.println(F(""SWITCH HEATER OFF"")); stm_exitFlag = FALSE; stm_actState = stm_newState; stm_entryFlag = TRUE; } break; //============================================================================== // STM_STATE_FINISHED //============================================================================== case STM_STATE_FINISHED: /// - Path 5 \\n /// Settings: Oven Temperature, meat temperature, smoker on / off if (stm_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""Entered STM_STATE_FINISHED"")); #endif displayTitle(""FINISHED""); displayCommand(""GoTender Stop""); stm_entryFlag = FALSE; } if(getButtonStateUp()) { stm_newState = STM_STATE_SETTINGS; stm_exitFlag = TRUE; } if(getButtonStateEnter()) { } if(getButtonStateDown()) { } // Exit if (stm_exitFlag == TRUE) { // do exit action clearButtonAllFlags(); stm_exitFlag = FALSE; stm_actState = stm_newState; stm_entryFlag = TRUE; } break; //============================================================================== // STM_STATE_ERROR //============================================================================== case STM_STATE_ERROR: /// - Path 6 \\n /// Error Handler if (stm_entryFlag == TRUE) { #ifdef DEBUG Serial.println(F(""Entered STM_STATE_ERROR"")); #endif sysOkay = false; displayTitle(""!!!ERROR!!!""); stm_entryFlag = FALSE; } break; //============================================================================== // DEFAULT //============================================================================== default: //Error: Change to Error state #ifdef DEBUG Serial.println(F(""Entered default"")); #endif stm_actState = STM_STATE_ERROR; break; } //============================================================================== // Safety system //============================================================================== if ( getTemperatureOven() > MAX_TEMPERATURE_OVEN) sysOkay = false; // Overtemperature Oven if ( getTemperatureMeat() > MAX_TEMPERATURE_MEAT) sysOkay = false; // Overtemperature Meat if ( getHeaterState() && getSmokerState() ) sysOkay = false; // Heater and Smoker both on if ( maxSmokerTimeS >= MAX_SMOKER_TIME_S ) sysOkay = false; // Smoker too long in ON state // Safety: If system is not okay -> Disable heaters if ( !sysOkay ) { emergencyOff(); displayTitle(""EMERGENCY""); displayCommand(""GoTender Stop""); digitalWrite(RED_LED_PIN, HIGH); } //============================================================================== // Display time and timer //============================================================================== if ( sysTickFast ) // TBD Testing { sysTickFast = 0; displayTime(); displayTimer(); if (getHeaterState() ) { digitalWrite(GREEN_LED_PIN, HIGH); } else { digitalWrite(GREEN_LED_PIN, LOW); } if( getSmokerState() ) { digitalWrite(YELLOW_LED_PIN, HIGH); } else { digitalWrite(YELLOW_LED_PIN, LOW); } } } ",8143,False,1764.768149718344,median "Template Guide Apache Roller Weblogger Version 6.0.0 July 2019 [arabic] . {blank} + == Overview This document is a Template Guide to the Apache Roller Weblogger, the Java-based and open source weblog server that is produced by the Apache Roller project of the Apache Software Foundation. [arabic] . {blank} [arabic] .. {blank} + === Copyright and trademark information The contents of this document are subject to the terms of the Apache Software License. All trademarks within this document belong to legitimate owners. [arabic] . {blank} [arabic] .. {blank} + === Feedback Please direct any comments or suggestions about this document to: dev@roller.apache.org [arabic] . {blank} [arabic] .. {blank} + === Acknowledgments The general format of this document was based on the documentation template used by http://www.OpenOffice.org/[OpenOffice.org]. [arabic] . {blank} == Introduction If you know a little about HTML and CSS, then you’ll find that it’s easy to customize the appearance, layout and content of your Roller-based weblog. You can change the appearance of any of your weblog’s pages and add as many new pages as you want. Any Roller user can do it through Roller’s web-based interface and it’s all done with Roller’s simple and easy-to-use template language. In this guide, we’ll tell you how. We’ll start by explaining how Roller’s weblog template system works then we’ll provide a reference to the objects and macros that you can use in your templates. NOTE: If you have only AUTHOR or LIMITED permissions within a weblog then you won’t have access to the Preferences->Theme or Preferences->Templates pages and you won’t be able to change or customize your theme. You need to have ADMIN permission within a weblog to be able to do the things described in this guide. NOTE: It is possible for a Roller site administrator to disable theme customization. So if you do have ADMIN permission in your weblog and you still don’t see the Preferences->Templates page, perhaps your Roller site does not allow customization. == The Roller template system Each Roller weblog is defined by a set of page templates, which you can edit to customize the content, layout and appearance of your weblog. === Page templates When you create a new Roller weblog you must pick a theme to define the new weblog’s appearance and layout. A theme is just a small set of templates, where each template contains HTML code, template language expressions and macros. What’s a template? A template for an HTML web page is simply an HTML web page with some Velocity code embedded inside. For example, this is a valid Roller template, with one Velocity expression: My blog is named *$model.weblog.name* The string ``$model.weblog.name'' is a template language expression and when Roller displays the template, that expression will be replaced with the name of the weblog. Note that *$model* is something special. Roller makes a set of objects, known as _models_, available to page templates. In the example above, we see only the $model object, but here are others. You’ll learn more about models in Section 4 and Section 5 provides a complete reference. === The Velocity template language The simple template language that we use inside Roller page templates is called Velocity. It’s designed to be simple and easy for even non-programmers, but it’s also a simple programming language. You can set variables, use if-else conditional logic and create loops. For example, this Roller page template will list the categories available in your weblog except for the one named Music: My blog is named *$model.weblog.name*. These are my categories:
#foreach ($cat in $model.weblog.categories) #if ($cat.name != ``Music'') **$cat.name**
*#end* #end Velocity also supports the concepts of _macros_. A macro is essentially a Velocity method call. We use them in Roller to generate HTML. For example, as illustrated below, to display a bookmark folder you first retrieve if from the weblog and second pass it to the _#showBookmarkLinksList()_ macro to display it as an HTML _
    _ list.

    Blogroll

    #set($rootFolder = latexmath:[$ \\#set($]rootFolder = $model.weblog.getBookmarkFolder(``/'')) #showBookmarkLinksList($rootFolder) You’ll learn more about macros in Section 4 and Section 7 provides a complete reference to the standard Roller macros. If you want more information on Velocity, see http://wiki.apache.org/velocity/. Now that we’ve covered the basic concepts of page templates and the Velocity template language, let’s dig into the details of editing templates. == Editing and creating page templates After you’ve used Roller *Preferences->Themes* page to customize your weblog theme, you can edit and create page templates through the *Preferences->Templates* page. We’ll show you how to do that, but first you need to understand how the required pages, found in every theme, work together to display a weblog. Every theme is different, but all themes must have two required pages – pages that you cannot rename or delete. These are the *Weblog* template, which defines the main page of your blog, and the *_day* template, which defines how each day’s worth of blog entries is displayed on your main page. Some themes also have a required page named *_css* which defines the CSS style code used by the weblog. First, let’s look at a simple Weblog template. === The Weblog template Below is a simple Weblog page that displays all of the data that weblog typically contains including recent entries with paging to past entries, category link, feed links, a calendar and feed auto-discovery. Check the annotations for more detail. Listing 1: a typical Weblog template **latexmath:[$model.weblog.name** : **$]model.weblogPage.name** *#1* *#showAutodiscoveryLinks($model.weblog) #2* **#3**

    **$model.weblog.name**

    *#4*

    **$model.weblog.description**

    *#set($rootCategory = $model.weblog.getWeblogCategory(``nil'')) #5* ** #showWeblogCategoryLinksList($rootCategory false false)**
    *#set($pager = $model.getWeblogEntriesPager()) #6*
    #if ($model.results)#7 #showWeblogSearchAgainForm($model.weblog) #showNextPrevSearchControl($pager) #else #showNextPrevEntriesControl($pager) #8 #end
    #showWeblogEntriesPager($pager) #9 #if ($model.permalink) #10 #showWeblogEntryComments($entry) #showWeblogEntryCommentForm($entry) #end

    Calendar

    *#showWeblogEntryCalendar($model.weblog ``nil'') #11*

    Feeds

    *#showAtomFeedsList($model.weblog) #12*

    Search

    *#showWeblogSearchForm($model.weblog false) #13*

    Links

    *#set($defaultFolder = $model.weblog.getBookmarkFolder(``/'')) #14* *#showBookmarkLinksList($defaultFolder) *

    Navigation

    *#showPageMenu($model.weblog) #15* *#showAuthorMenu(true) #16*

    Referrers

    *#set($refs = $model.weblog.getTodaysReferrers()) #17* *#showReferrersList($refs 30 20) *
    The above template includes a good mix of Velocity expressions and statements. There’s a lot going on, so let’s explain it in detail. Here’s the point-by-point breakdown. [arabic] . {blank} [arabic] .. {blank} [arabic] ... *HTML title* For the HTML title we use the weblog’s name, a colon and the name of the page template that is currently being displayed. ... *Auto-discovery links* The __#showAutodiscoveryLinks() __macro adds the HTML __ elements required for RSS and Atom feed auto-discovery as well as RSD for weblog clients. ... *Include CSS styles* Here we use the include the theme’s *_css* template directly in the page, right inside a pair of _""; webServerIndex += headEnd(); webServerIndex += bodyBegin(); webServerIndex += ""
    \\r\\n""; webServerIndex += ""\\r\\n""; webServerIndex += ""
    \\r\\n""; webServerIndex += ""

    Return to Config

    \\r\\n""; webServerIndex += bodyEnd(); webServerIndex += htmlEnd(); /* Set ""/"" URL and handleRoot func */ webServer.on(""/"", handleRoot); /* Set ""/config"" URL and handleConfig func */ webServer.on(""/config"", handleConfig); /* Set handleNotFound func */ webServer.onNotFound(handleNotFound); /* Set ""/upload"" URL */ webServer.on(""/upload"", HTTP_GET, [](){ if (wmConfig.fullSecurity || wmConfig.configSecurity) { if (!webServer.authenticate(wmConfig.webAdminLogin, wmConfig.webAdminPassword)) return webServer.requestAuthentication(); } webServer.sendHeader(""Connection"", ""close""); webServer.sendHeader(""Access-Control-Allow-Origin"", ""*""); webServer.send(200, ""text/html"", webServerIndex); }); /* Set ""/update"" URL */ webServer.on(""/update"", HTTP_POST, [](){ webServer.sendHeader(""Connection"", ""close""); webServer.sendHeader(""Access-Control-Allow-Origin"", ""*""); webServer.send(200, ""text/plain"", (Update.hasError())?""FAIL"":""OK""); ESP.restart(); },[](){ HTTPUpload& upload = webServer.upload(); if(upload.status == UPLOAD_FILE_START){ Serial.setDebugOutput(true); WiFiUDP::stopAll(); Serial.printf(""Update: %s\\n"", upload.filename.c_str()); uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; if(!Update.begin(maxSketchSpace)){//start with max available size Update.printError(Serial); } } else if(upload.status == UPLOAD_FILE_WRITE){ if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){ Update.printError(Serial); } } else if(upload.status == UPLOAD_FILE_END){ if(Update.end(true)){ //true to set the size to the current progress Serial.printf(""Update Success: %u\\nRebooting...\\n"", upload.totalSize); } else { Update.printError(Serial); } Serial.setDebugOutput(false); } yield(); }); webServer.begin(); } String htmlBegin() { String s = ""\\r\\n""; s += ""\\r\\n""; return s; } String htmlEnd() { String s = ""\\r\\n""; return s; } String headBegin() { String s = ""\\r\\n""; return s; } String headEnd() { String s = ""\\r\\n""; return s; } String metaBegin() { String s = ""\\r\\n""; s += ""\\r\\n""; return s; } String titleBegEnd(){ String s = """"; s += PLATFORM; s += "". ""; s += MODULE_NAME; s += ""\\r\\n""; return s; } String bodyBegin() { String s = ""\\r\\n""; return s; } String bodyEnd() { String s = ""\\r\\n""; return s; } String styleBegEnd() { String s = """"; return s; } String htmlLogo() { String s = ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; s += """"; s += WEB_WATERMETER_FIRST_NAME; s += ""\\r\\n""; s += """"; s += WEB_WATERMETER_LAST_NAME; s += ""\\r\\n""; s += ""\\r\\n""; s += ""

    \\r\\n""; s += ""

    ""; s += PLATFORM; s += ""

    \\r\\n""; s += ""

    ""; s += ""Version ""; s += MODULE_VERSION; s += ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""

    ""; s += ""

    Free memory: ""; s += ESP.getFreeHeap(); s += "" bytes

    \\r\\n""; s += ""

    Uptime: ""; s += localUptime(); s += ""

    \\r\\n""; s += ""

    "" + returnVccStr() + "". "" + returnRssiStr() + ""

    ""; s += ""

    Local time: ""; s += localTimeStr(); s += ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; return s; } void handleRoot() { String fract, s; if (firstStart) { handleConfig(); return; } if (wmConfig.fullSecurity) { if (!webServer.authenticate(wmConfig.webAdminLogin, wmConfig.webAdminPassword)) return webServer.requestAuthentication(); } s = htmlBegin(); s += headBegin(); s += metaBegin(); s += """"; s += titleBegEnd(); s += styleBegEnd(); s += headEnd(); s += bodyBegin(); s += ""\\r\\n""; s += ""
    \\r\\n""; s += htmlLogo(); s += ""
    \\r\\n""; /* s += ""

    456.789

    \\r\\n""; s += ""

    123.456

    \\r\\n"";*/ s += ""

    ""; s += wmConfig.coldWater/1000; s += "".""; fract = wmConfig.coldWater%1000; if (fract.length() == 2) fract = ""0"" + fract; else if (fract.length() == 1) fract = ""00"" + fract; s += fract; s += ""

    \\r\\n""; s += ""

    ""; s += wmConfig.hotWater/1000; s += "".""; fract = wmConfig.hotWater%1000; if (fract.length() == 2) fract = ""0"" + fract; else if (fract.length() == 1) fract = ""00"" + fract; s += fract; s += ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += bodyEnd(); s += htmlEnd(); webServer.send(200, ""text/html"", s); } void handleConfig() { String s; if (wmConfig.fullSecurity || wmConfig.configSecurity) { if (!webServer.authenticate(wmConfig.webAdminLogin, wmConfig.webAdminPassword)) return webServer.requestAuthentication(); } s = htmlBegin(); s += headBegin(); s += metaBegin(); s += titleBegEnd(); s += styleBegEnd(); s += headEnd(); s += bodyBegin(); s += ""\\r\\n""; s += ""
    \\r\\n""; s += htmlLogo(); s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""

    Admin auth settings:

    \\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; else s += "">\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; else s += "">\\r\\n""; s += ""\\r\\n""; s += ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""

    WiFi options:

    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; else s += "">\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; else s += "">\\r\\n""; s += ""\\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""

    MQTT settings:

    \\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""

    NTP settings:

    \\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""

    WaterMeter module settings:

    \\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""
    \\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""\\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""

    \\r\\n""; s += ""

    Main\\r\\n""; /* s += ""Set Time\\r\\n"";*/ s += ""Update Firmware

    \\r\\n""; s += ""

    \\r\\n""; s += ""
    \\r\\n""; s += ""
    \\r\\n""; s += ""\\r\\n""; s += ""


    \\r\\n""; s += bodyEnd(); s += htmlEnd(); webServer.send(200, ""text/html"", s); } void parssingSettings() { _config config; String s = """"; bool newSave = false; clearConfig(&config); for (unsigned int i=0; i org.apache.camel camel-debezium-postgres x.x.x ---- == URI format --------------------------- debezium-postgres:name[?options] --------------------------- // component-configure options: START == Configuring Options Camel components are configured on two separate levels: - component level - endpoint level === Configuring Component Options The component level is the highest level which holds general and common configurations that are inherited by the endpoints. For example a component may have security settings, credentials for authentication, urls for network connection and so forth. Some components only have a few options, and others may have many. Because components typically have pre configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all. Configuring components can be done with the xref:latest@manual::component-dsl.adoc[Component DSL], in a configuration file (application.properties|yaml), or directly with Java code. === Configuring Endpoint Options Where you find yourself configuring the most is on endpoints, as endpoints often have many options, which allows you to configure what you need the endpoint to do. The options are also categorized into whether the endpoint is used as consumer (from) or as a producer (to), or used for both. Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the xref:latest@manual::Endpoint-dsl.adoc[Endpoint DSL] as a _type safe_ way of configuring endpoints. A good practice when configuring options is to use xref:latest@manual::using-propertyplaceholder.adoc[Property Placeholders], which allows to not hardcode urls, port numbers, sensitive information, and other settings. In other words placeholders allows to externalize the configuration from your code, and gives more flexibility and reuse. The following two sections lists all the options, firstly for the component followed by the endpoint. // component-configure options: END // component options: START == Component Options The Debezium PostgresSQL Connector component supports 89 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *additionalProperties* (common) | Additional properties for debezium components in case they can't be set directly on the camel configurations (e.g: setting Kafka Connect properties needed by Debezium engine, for example setting KafkaOffsetBackingStore), the properties have to be prefixed with additionalProperties.. E.g: additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=\\http://localhost:8811/avro | | Map | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *configuration* (consumer) | Allow pre-configured Configurations to be set. | | PostgresConnectorEmbeddedDebeziumConfiguration | *internalKeyConverter* (consumer) | The Converter class that should be used to serialize and deserialize key data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *internalValueConverter* (consumer) | The Converter class that should be used to serialize and deserialize value data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *offsetCommitPolicy* (consumer) | The name of the Java class of the commit policy. It defines when offsets commit has to be triggered based on the number of events processed and the time elapsed since the last commit. This class must implement the interface 'OffsetCommitPolicy'. The default is a periodic commit policy based upon time intervals. | io.debezium.embedded.spi.OffsetCommitPolicy.PeriodicCommitOffsetPolicy | String | *offsetCommitTimeoutMs* (consumer) | Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt. The default is 5 seconds. | 5s | long | *offsetFlushIntervalMs* (consumer) | Interval at which to try committing offsets. The default is 1 minute. | 60s | long | *offsetStorage* (consumer) | The name of the Java class that is responsible for persistence of connector offsets. | org.apache.kafka.connect.storage.FileOffsetBackingStore | String | *offsetStorageFileName* (consumer) | Path to file where offsets are to be stored. Required when offset.storage is set to the FileOffsetBackingStore. | | String | *offsetStoragePartitions* (consumer) | The number of partitions used when creating the offset storage topic. Required when offset.storage is set to the 'KafkaOffsetBackingStore'. | | int | *offsetStorageReplicationFactor* (consumer) | Replication factor used when creating the offset storage topic. Required when offset.storage is set to the KafkaOffsetBackingStore | | int | *offsetStorageTopic* (consumer) | The name of the Kafka topic where offsets are to be stored. Required when offset.storage is set to the KafkaOffsetBackingStore. | | String | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *binaryHandlingMode* (postgres) | Specify how binary (blob, binary, etc.) columns should be represented in change events, including:'bytes' represents binary data as byte array (default)'base64' represents binary data as base64-encoded string'hex' represents binary data as hex-encoded (base16) string | bytes | String | *columnBlacklist* (postgres) | Regular expressions matching columns to exclude from change events (deprecated, use column.exclude.list instead) | | String | *columnExcludeList* (postgres) | Regular expressions matching columns to exclude from change events | | String | *columnIncludeList* (postgres) | Regular expressions matching columns to include in change events | | String | *columnPropagateSourceType* (postgres) | A comma-separated list of regular expressions matching fully-qualified names of columns that adds the columns original type and original length as parameters to the corresponding field schemas in the emitted change records. | | String | *columnWhitelist* (postgres) | Regular expressions matching columns to include in change events (deprecated, use column.include.list instead) | | String | *converters* (postgres) | Optional list of custom converters that would be used instead of default ones. The converters are defined using '.type' config option and configured using options '.' | | String | *databaseDbname* (postgres) | The name of the database the connector should be monitoring | | String | *databaseHistoryFileFilename* (postgres) | The path to the file that will be used to record the database history | | String | *databaseHostname* (postgres) | Resolvable hostname or IP address of the database server. | | String | *databaseInitialStatements* (postgres) | A semicolon separated list of SQL statements to be executed when a JDBC connection to the database is established. Note that the connector may establish JDBC connections at its own discretion, so this should typically be used for configurationof session parameters only, but not for executing DML statements. Use doubled semicolon (';;') to use a semicolon as a character and not as a delimiter. | | String | *databasePassword* (postgres) | *Required* Password of the database user to be used when connecting to the database. | | String | *databasePort* (postgres) | Port of the database server. | 5432 | int | *databaseServerName* (postgres) | *Required* Unique name that identifies the database server and all recorded offsets, and that is used as a prefix for all schemas and topics. Each distinct installation should have a separate namespace and be monitored by at most one Debezium connector. | | String | *databaseSslcert* (postgres) | File containing the SSL Certificate for the client. See the Postgres SSL docs for further information | | String | *databaseSslfactory* (postgres) | A name of class to that creates SSL Sockets. Use org.postgresql.ssl.NonValidatingFactory to disable SSL validation in development environments | | String | *databaseSslkey* (postgres) | File containing the SSL private key for the client. See the Postgres SSL docs for further information | | String | *databaseSslmode* (postgres) | Whether to use an encrypted connection to Postgres. Options include'disable' (the default) to use an unencrypted connection; 'require' to use a secure (encrypted) connection, and fail if one cannot be established; 'verify-ca' like 'required' but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates, or fail if no valid matching CA certificates are found; or'verify-full' like 'verify-ca' but additionally verify that the server certificate matches the host to which the connection is attempted. | disable | String | *databaseSslpassword* (postgres) | Password to access the client private key from the file specified by 'database.sslkey'. See the Postgres SSL docs for further information | | String | *databaseSslrootcert* (postgres) | File containing the root certificate(s) against which the server is validated. See the Postgres JDBC SSL docs for further information | | String | *databaseTcpkeepalive* (postgres) | Enable or disable TCP keep-alive probe to avoid dropping TCP connection | true | boolean | *databaseUser* (postgres) | Name of the database user to be used when connecting to the database. | | String | *datatypePropagateSourceType* (postgres) | A comma-separated list of regular expressions matching the database-specific data type names that adds the data type's original type and original length as parameters to the corresponding field schemas in the emitted change records. | | String | *decimalHandlingMode* (postgres) | Specify how DECIMAL and NUMERIC columns should be represented in change events, including:'precise' (the default) uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'string' uses string to represent values; 'double' represents values using Java's 'double', which may not offer the precision but will be far easier to use in consumers. | precise | String | *eventProcessingFailureHandling{zwsp}Mode* (postgres) | Specify how failures during processing of events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its position is raised, causing the connector to be stopped; 'warn' the problematic event and its position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *heartbeatActionQuery* (postgres) | The query executed with every heartbeat. | | String | *heartbeatIntervalMs* (postgres) | Length of an interval in milli-seconds in in which the connector periodically sends heartbeat messages to a heartbeat topic. Use 0 to disable heartbeat messages. Disabled by default. | 0ms | int | *heartbeatTopicsPrefix* (postgres) | The prefix that is used to name heartbeat topics.Defaults to __debezium-heartbeat. | __debezium-heartbeat | String | *hstoreHandlingMode* (postgres) | Specify how HSTORE columns should be represented in change events, including:'json' represents values as string-ified JSON (default)'map' represents values as a key/value map | json | String | *includeUnknownDatatypes* (postgres) | Specify whether the fields of data type not supported by Debezium should be processed:'false' (the default) omits the fields; 'true' converts the field into an implementation dependent binary representation. | false | boolean | *incrementalSnapshotChunkSize* (postgres) | The maximum size of chunk for incremental snapshotting | 1024 | int | *intervalHandlingMode* (postgres) | Specify how INTERVAL columns should be represented in change events, including:'string' represents values as an exact ISO formatted string'numeric' (default) represents values using the inexact conversion into microseconds | numeric | String | *maxBatchSize* (postgres) | Maximum size of each batch of source records. Defaults to 2048. | 2048 | int | *maxQueueSize* (postgres) | Maximum size of the queue for change events read from the database log but not yet recorded or forwarded. Defaults to 8192, and should always be larger than the maximum batch size. | 8192 | int | *maxQueueSizeInBytes* (postgres) | Maximum size of the queue in bytes for change events read from the database log but not yet recorded or forwarded. Defaults to 0. Mean the feature is not enabled | 0 | long | *messageKeyColumns* (postgres) | A semicolon-separated list of expressions that match fully-qualified tables and column(s) to be used as message key. Each expression must match the pattern ':',where the table names could be defined as (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on the specific connector,and the key columns are a comma-separated list of columns representing the custom key. For any table without an explicit key configuration the table's primary key column(s) will be used as message key.Example: dbserver1.inventory.orderlines:orderId,orderLineId;dbserver1.inventory.orders:id | | String | *pluginName* (postgres) | The name of the Postgres logical decoding plugin installed on the server. Supported values are 'decoderbufs', 'wal2json', 'pgoutput', 'wal2json_streaming', 'wal2json_rds' and 'wal2json_rds_streaming'. Defaults to 'decoderbufs'. | decoderbufs | String | *pollIntervalMs* (postgres) | Time to wait for new change events to appear after receiving no events, given in milliseconds. Defaults to 500 ms. | 500ms | long | *provideTransactionMetadata* (postgres) | Enables transaction metadata extraction together with event counting | false | boolean | *publicationAutocreateMode* (postgres) | Applies only when streaming changes using pgoutput.Determine how creation of a publication should work, the default is all_tables.DISABLED - The connector will not attempt to create a publication at all. The expectation is that the user has created the publication up-front. If the publication isn't found to exist upon startup, the connector will throw an exception and stop.ALL_TABLES - If no publication exists, the connector will create a new publication for all tables. Note this requires that the configured user has access. If the publication already exists, it will be used. i.e CREATE PUBLICATION FOR ALL TABLES;FILTERED - If no publication exists, the connector will create a new publication for all those tables matchingthe current filter configuration (see table/database include/exclude list properties). If the publication already exists, it will be used. i.e CREATE PUBLICATION FOR TABLE | all_tables | String | *publicationName* (postgres) | The name of the Postgres 10 publication used for streaming changes from a plugin.Defaults to 'dbz_publication' | dbz_publication | String | *queryFetchSize* (postgres) | The maximum number of records that should be loaded into memory while streaming. A value of 0 uses the default JDBC fetch size. | 0 | int | *retriableRestartConnectorWait{zwsp}Ms* (postgres) | Time to wait before restarting connector after retriable exception occurs. Defaults to 10000ms. | 10s | long | *sanitizeFieldNames* (postgres) | Whether field names will be sanitized to Avro naming conventions | false | boolean | *schemaBlacklist* (postgres) | The schemas for which events must not be captured (deprecated, use schema.exclude.list instead) | | String | *schemaExcludeList* (postgres) | The schemas for which events must not be captured | | String | *schemaIncludeList* (postgres) | The schemas for which events should be captured | | String | *schemaRefreshMode* (postgres) | Specify the conditions that trigger a refresh of the in-memory schema for a table. 'columns_diff' (the default) is the safest mode, ensuring the in-memory schema stays in-sync with the database table's schema at all times. 'columns_diff_exclude_unchanged_toast' instructs the connector to refresh the in-memory schema cache if there is a discrepancy between it and the schema derived from the incoming message, unless unchanged TOASTable data fully accounts for the discrepancy. This setting can improve connector performance significantly if there are frequently-updated tables that have TOASTed data that are rarely part of these updates. However, it is possible for the in-memory schema to become outdated if TOASTable columns are dropped from the table. | columns_diff | String | *schemaWhitelist* (postgres) | The schemas for which events should be captured (deprecated, use schema.include.list instead) | | String | *signalDataCollection* (postgres) | The name of the data collection that is used to send signals/commands to Debezium. Signaling is disabled when not set. | | String | *skippedOperations* (postgres) | The comma-separated list of operations to skip during streaming, defined as: 'c' for inserts/create; 'u' for updates; 'd' for deletes. By default, no operations will be skipped. | | String | *slotDropOnStop* (postgres) | Whether or not to drop the logical replication slot when the connector finishes orderlyBy default the replication is kept so that on restart progress can resume from the last recorded location | false | boolean | *slotMaxRetries* (postgres) | How many times to retry connecting to a replication slot when an attempt fails. | 6 | int | *slotName* (postgres) | The name of the Postgres logical decoding slot created for streaming changes from a plugin.Defaults to 'debezium | debezium | String | *slotRetryDelayMs* (postgres) | Time to wait between retry attempts when the connector fails to connect to a replication slot, given in milliseconds. Defaults to 10 seconds (10,000 ms). | 10s | long | *slotStreamParams* (postgres) | Any optional parameters used by logical decoding plugin. Semi-colon separated. E.g. 'add-tables=public.table,public.table2;include-lsn=true' | | String | *snapshotCustomClass* (postgres) | When 'snapshot.mode' is set as custom, this setting must be set to specify a fully qualified class name to load (via the default class loader).This class must implement the 'Snapshotter' interface and is called on each app boot to determine whether to do a snapshot and how to build queries. | | String | *snapshotDelayMs* (postgres) | A delay period before a snapshot will begin, given in milliseconds. Defaults to 0 ms. | 0ms | long | *snapshotFetchSize* (postgres) | The maximum number of records that should be loaded into memory while performing a snapshot | | int | *snapshotIncludeCollectionList* (postgres) | this setting must be set to specify a list of tables/collections whose snapshot must be taken on creating or restarting the connector. | | String | *snapshotLockTimeoutMs* (postgres) | The maximum number of millis to wait for table locks at the beginning of a snapshot. If locks cannot be acquired in this time frame, the snapshot will be aborted. Defaults to 10 seconds | 10s | long | *snapshotMaxThreads* (postgres) | The maximum number of threads used to perform the snapshot. Defaults to 1. | 1 | int | *snapshotMode* (postgres) | The criteria for running a snapshot upon startup of the connector. Options include: 'always' to specify that the connector run a snapshot each time it starts up; 'initial' (the default) to specify the connector can run a snapshot only when no offsets are available for the logical server name; 'initial_only' same as 'initial' except the connector should stop after completing the snapshot and before it would normally start emitting changes;'never' to specify the connector should never run a snapshot and that upon first startup the connector should read from the last position (LSN) recorded by the server; and'exported' deprecated, use 'initial' instead; 'custom' to specify a custom class with 'snapshot.custom_class' which will be loaded and used to determine the snapshot, see docs for more details. | initial | String | *snapshotSelectStatement{zwsp}Overrides* (postgres) | This property contains a comma-separated list of fully-qualified tables (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on thespecific connectors. Select statements for the individual tables are specified in further configuration properties, one for each table, identified by the id 'snapshot.select.statement.overrides.DB_NAME.TABLE_NAME' or 'snapshot.select.statement.overrides.SCHEMA_NAME.TABLE_NAME', respectively. The value of those properties is the select statement to use when retrieving data from the specific table during snapshotting. A possible use case for large append-only tables is setting a specific point where to start (resume) snapshotting, in case a previous snapshotting was interrupted. | | String | *sourceStructVersion* (postgres) | A version of the format of the publicly visible source part in the message | v2 | String | *statusUpdateIntervalMs* (postgres) | Frequency for sending replication connection status updates to the server, given in milliseconds. Defaults to 10 seconds (10,000 ms). | 10s | int | *tableBlacklist* (postgres) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring (deprecated, use table.exclude.list instead) | | String | *tableExcludeList* (postgres) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring | | String | *tableIgnoreBuiltin* (postgres) | Flag specifying whether built-in tables should be ignored. | true | boolean | *tableIncludeList* (postgres) | The tables for which changes are to be captured | | String | *tableWhitelist* (postgres) | The tables for which changes are to be captured (deprecated, use table.include.list instead) | | String | *timePrecisionMode* (postgres) | Time, date, and timestamps can be represented with different kinds of precisions, including:'adaptive' (the default) bases the precision of time, date, and timestamp values on the database column's precision; 'adaptive_time_microseconds' like 'adaptive' mode, but TIME fields always use microseconds precision;'connect' always represents time, date, and timestamp values using Kafka Connect's built-in representations for Time, Date, and Timestamp, which uses millisecond precision regardless of the database columns' precision . | adaptive | String | *toastedValuePlaceholder* (postgres) | Specify the constant that will be provided by Debezium to indicate that the original value is a toasted value not provided by the database. If starts with 'hex:' prefix it is expected that the rest of the string repesents hexadecimally encoded octets. | __debezium_unavailable_value | String | *tombstonesOnDelete* (postgres) | Whether delete operations should be represented by a delete event and a subsquenttombstone event (true) or only by a delete event (false). Emitting the tombstone event (the default behavior) allows Kafka to completely delete all events pertaining to the given key once the source record got deleted. | false | boolean | *xminFetchIntervalMs* (postgres) | Specify how often (in ms) the xmin will be fetched from the replication slot. This xmin value is exposed by the slot which gives a lower bound of where a new replication slot could start from. The lower the value, the more likely this value is to be the current 'true' value, but the bigger the performance cost. The bigger the value, the less likely this value is to be the current 'true' value, but the lower the performance penalty. The default is set to 0 ms, which disables tracking xmin. | 0ms | long |=== // component options: END // endpoint options: START == Endpoint Options The Debezium PostgresSQL Connector endpoint is configured using URI syntax: ---- debezium-postgres:name ---- with the following path and query parameters: === Path Parameters (1 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *name* | *Required* Unique name for the connector. Attempting to register again with the same name will fail. | | String |=== === Query Parameters (89 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *additionalProperties* (common) | Additional properties for debezium components in case they can't be set directly on the camel configurations (e.g: setting Kafka Connect properties needed by Debezium engine, for example setting KafkaOffsetBackingStore), the properties have to be prefixed with additionalProperties.. E.g: additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=\\http://localhost:8811/avro | | Map | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *internalKeyConverter* (consumer) | The Converter class that should be used to serialize and deserialize key data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *internalValueConverter* (consumer) | The Converter class that should be used to serialize and deserialize value data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *offsetCommitPolicy* (consumer) | The name of the Java class of the commit policy. It defines when offsets commit has to be triggered based on the number of events processed and the time elapsed since the last commit. This class must implement the interface 'OffsetCommitPolicy'. The default is a periodic commit policy based upon time intervals. | io.debezium.embedded.spi.OffsetCommitPolicy.PeriodicCommitOffsetPolicy | String | *offsetCommitTimeoutMs* (consumer) | Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt. The default is 5 seconds. | 5s | long | *offsetFlushIntervalMs* (consumer) | Interval at which to try committing offsets. The default is 1 minute. | 60s | long | *offsetStorage* (consumer) | The name of the Java class that is responsible for persistence of connector offsets. | org.apache.kafka.connect.storage.FileOffsetBackingStore | String | *offsetStorageFileName* (consumer) | Path to file where offsets are to be stored. Required when offset.storage is set to the FileOffsetBackingStore. | | String | *offsetStoragePartitions* (consumer) | The number of partitions used when creating the offset storage topic. Required when offset.storage is set to the 'KafkaOffsetBackingStore'. | | int | *offsetStorageReplicationFactor* (consumer) | Replication factor used when creating the offset storage topic. Required when offset.storage is set to the KafkaOffsetBackingStore | | int | *offsetStorageTopic* (consumer) | The name of the Kafka topic where offsets are to be stored. Required when offset.storage is set to the KafkaOffsetBackingStore. | | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *binaryHandlingMode* (postgres) | Specify how binary (blob, binary, etc.) columns should be represented in change events, including:'bytes' represents binary data as byte array (default)'base64' represents binary data as base64-encoded string'hex' represents binary data as hex-encoded (base16) string | bytes | String | *columnBlacklist* (postgres) | Regular expressions matching columns to exclude from change events (deprecated, use column.exclude.list instead) | | String | *columnExcludeList* (postgres) | Regular expressions matching columns to exclude from change events | | String | *columnIncludeList* (postgres) | Regular expressions matching columns to include in change events | | String | *columnPropagateSourceType* (postgres) | A comma-separated list of regular expressions matching fully-qualified names of columns that adds the columns original type and original length as parameters to the corresponding field schemas in the emitted change records. | | String | *columnWhitelist* (postgres) | Regular expressions matching columns to include in change events (deprecated, use column.include.list instead) | | String | *converters* (postgres) | Optional list of custom converters that would be used instead of default ones. The converters are defined using '.type' config option and configured using options '.' | | String | *databaseDbname* (postgres) | The name of the database the connector should be monitoring | | String | *databaseHistoryFileFilename* (postgres) | The path to the file that will be used to record the database history | | String | *databaseHostname* (postgres) | Resolvable hostname or IP address of the database server. | | String | *databaseInitialStatements* (postgres) | A semicolon separated list of SQL statements to be executed when a JDBC connection to the database is established. Note that the connector may establish JDBC connections at its own discretion, so this should typically be used for configurationof session parameters only, but not for executing DML statements. Use doubled semicolon (';;') to use a semicolon as a character and not as a delimiter. | | String | *databasePassword* (postgres) | *Required* Password of the database user to be used when connecting to the database. | | String | *databasePort* (postgres) | Port of the database server. | 5432 | int | *databaseServerName* (postgres) | *Required* Unique name that identifies the database server and all recorded offsets, and that is used as a prefix for all schemas and topics. Each distinct installation should have a separate namespace and be monitored by at most one Debezium connector. | | String | *databaseSslcert* (postgres) | File containing the SSL Certificate for the client. See the Postgres SSL docs for further information | | String | *databaseSslfactory* (postgres) | A name of class to that creates SSL Sockets. Use org.postgresql.ssl.NonValidatingFactory to disable SSL validation in development environments | | String | *databaseSslkey* (postgres) | File containing the SSL private key for the client. See the Postgres SSL docs for further information | | String | *databaseSslmode* (postgres) | Whether to use an encrypted connection to Postgres. Options include'disable' (the default) to use an unencrypted connection; 'require' to use a secure (encrypted) connection, and fail if one cannot be established; 'verify-ca' like 'required' but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates, or fail if no valid matching CA certificates are found; or'verify-full' like 'verify-ca' but additionally verify that the server certificate matches the host to which the connection is attempted. | disable | String | *databaseSslpassword* (postgres) | Password to access the client private key from the file specified by 'database.sslkey'. See the Postgres SSL docs for further information | | String | *databaseSslrootcert* (postgres) | File containing the root certificate(s) against which the server is validated. See the Postgres JDBC SSL docs for further information | | String | *databaseTcpkeepalive* (postgres) | Enable or disable TCP keep-alive probe to avoid dropping TCP connection | true | boolean | *databaseUser* (postgres) | Name of the database user to be used when connecting to the database. | | String | *datatypePropagateSourceType* (postgres) | A comma-separated list of regular expressions matching the database-specific data type names that adds the data type's original type and original length as parameters to the corresponding field schemas in the emitted change records. | | String | *decimalHandlingMode* (postgres) | Specify how DECIMAL and NUMERIC columns should be represented in change events, including:'precise' (the default) uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'string' uses string to represent values; 'double' represents values using Java's 'double', which may not offer the precision but will be far easier to use in consumers. | precise | String | *eventProcessingFailureHandling{zwsp}Mode* (postgres) | Specify how failures during processing of events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its position is raised, causing the connector to be stopped; 'warn' the problematic event and its position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *heartbeatActionQuery* (postgres) | The query executed with every heartbeat. | | String | *heartbeatIntervalMs* (postgres) | Length of an interval in milli-seconds in in which the connector periodically sends heartbeat messages to a heartbeat topic. Use 0 to disable heartbeat messages. Disabled by default. | 0ms | int | *heartbeatTopicsPrefix* (postgres) | The prefix that is used to name heartbeat topics.Defaults to __debezium-heartbeat. | __debezium-heartbeat | String | *hstoreHandlingMode* (postgres) | Specify how HSTORE columns should be represented in change events, including:'json' represents values as string-ified JSON (default)'map' represents values as a key/value map | json | String | *includeUnknownDatatypes* (postgres) | Specify whether the fields of data type not supported by Debezium should be processed:'false' (the default) omits the fields; 'true' converts the field into an implementation dependent binary representation. | false | boolean | *incrementalSnapshotChunkSize* (postgres) | The maximum size of chunk for incremental snapshotting | 1024 | int | *intervalHandlingMode* (postgres) | Specify how INTERVAL columns should be represented in change events, including:'string' represents values as an exact ISO formatted string'numeric' (default) represents values using the inexact conversion into microseconds | numeric | String | *maxBatchSize* (postgres) | Maximum size of each batch of source records. Defaults to 2048. | 2048 | int | *maxQueueSize* (postgres) | Maximum size of the queue for change events read from the database log but not yet recorded or forwarded. Defaults to 8192, and should always be larger than the maximum batch size. | 8192 | int | *maxQueueSizeInBytes* (postgres) | Maximum size of the queue in bytes for change events read from the database log but not yet recorded or forwarded. Defaults to 0. Mean the feature is not enabled | 0 | long | *messageKeyColumns* (postgres) | A semicolon-separated list of expressions that match fully-qualified tables and column(s) to be used as message key. Each expression must match the pattern ':',where the table names could be defined as (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on the specific connector,and the key columns are a comma-separated list of columns representing the custom key. For any table without an explicit key configuration the table's primary key column(s) will be used as message key.Example: dbserver1.inventory.orderlines:orderId,orderLineId;dbserver1.inventory.orders:id | | String | *pluginName* (postgres) | The name of the Postgres logical decoding plugin installed on the server. Supported values are 'decoderbufs', 'wal2json', 'pgoutput', 'wal2json_streaming', 'wal2json_rds' and 'wal2json_rds_streaming'. Defaults to 'decoderbufs'. | decoderbufs | String | *pollIntervalMs* (postgres) | Time to wait for new change events to appear after receiving no events, given in milliseconds. Defaults to 500 ms. | 500ms | long | *provideTransactionMetadata* (postgres) | Enables transaction metadata extraction together with event counting | false | boolean | *publicationAutocreateMode* (postgres) | Applies only when streaming changes using pgoutput.Determine how creation of a publication should work, the default is all_tables.DISABLED - The connector will not attempt to create a publication at all. The expectation is that the user has created the publication up-front. If the publication isn't found to exist upon startup, the connector will throw an exception and stop.ALL_TABLES - If no publication exists, the connector will create a new publication for all tables. Note this requires that the configured user has access. If the publication already exists, it will be used. i.e CREATE PUBLICATION FOR ALL TABLES;FILTERED - If no publication exists, the connector will create a new publication for all those tables matchingthe current filter configuration (see table/database include/exclude list properties). If the publication already exists, it will be used. i.e CREATE PUBLICATION FOR TABLE | all_tables | String | *publicationName* (postgres) | The name of the Postgres 10 publication used for streaming changes from a plugin.Defaults to 'dbz_publication' | dbz_publication | String | *queryFetchSize* (postgres) | The maximum number of records that should be loaded into memory while streaming. A value of 0 uses the default JDBC fetch size. | 0 | int | *retriableRestartConnectorWait{zwsp}Ms* (postgres) | Time to wait before restarting connector after retriable exception occurs. Defaults to 10000ms. | 10s | long | *sanitizeFieldNames* (postgres) | Whether field names will be sanitized to Avro naming conventions | false | boolean | *schemaBlacklist* (postgres) | The schemas for which events must not be captured (deprecated, use schema.exclude.list instead) | | String | *schemaExcludeList* (postgres) | The schemas for which events must not be captured | | String | *schemaIncludeList* (postgres) | The schemas for which events should be captured | | String | *schemaRefreshMode* (postgres) | Specify the conditions that trigger a refresh of the in-memory schema for a table. 'columns_diff' (the default) is the safest mode, ensuring the in-memory schema stays in-sync with the database table's schema at all times. 'columns_diff_exclude_unchanged_toast' instructs the connector to refresh the in-memory schema cache if there is a discrepancy between it and the schema derived from the incoming message, unless unchanged TOASTable data fully accounts for the discrepancy. This setting can improve connector performance significantly if there are frequently-updated tables that have TOASTed data that are rarely part of these updates. However, it is possible for the in-memory schema to become outdated if TOASTable columns are dropped from the table. | columns_diff | String | *schemaWhitelist* (postgres) | The schemas for which events should be captured (deprecated, use schema.include.list instead) | | String | *signalDataCollection* (postgres) | The name of the data collection that is used to send signals/commands to Debezium. Signaling is disabled when not set. | | String | *skippedOperations* (postgres) | The comma-separated list of operations to skip during streaming, defined as: 'c' for inserts/create; 'u' for updates; 'd' for deletes. By default, no operations will be skipped. | | String | *slotDropOnStop* (postgres) | Whether or not to drop the logical replication slot when the connector finishes orderlyBy default the replication is kept so that on restart progress can resume from the last recorded location | false | boolean | *slotMaxRetries* (postgres) | How many times to retry connecting to a replication slot when an attempt fails. | 6 | int | *slotName* (postgres) | The name of the Postgres logical decoding slot created for streaming changes from a plugin.Defaults to 'debezium | debezium | String | *slotRetryDelayMs* (postgres) | Time to wait between retry attempts when the connector fails to connect to a replication slot, given in milliseconds. Defaults to 10 seconds (10,000 ms). | 10s | long | *slotStreamParams* (postgres) | Any optional parameters used by logical decoding plugin. Semi-colon separated. E.g. 'add-tables=public.table,public.table2;include-lsn=true' | | String | *snapshotCustomClass* (postgres) | When 'snapshot.mode' is set as custom, this setting must be set to specify a fully qualified class name to load (via the default class loader).This class must implement the 'Snapshotter' interface and is called on each app boot to determine whether to do a snapshot and how to build queries. | | String | *snapshotDelayMs* (postgres) | A delay period before a snapshot will begin, given in milliseconds. Defaults to 0 ms. | 0ms | long | *snapshotFetchSize* (postgres) | The maximum number of records that should be loaded into memory while performing a snapshot | | int | *snapshotIncludeCollectionList* (postgres) | this setting must be set to specify a list of tables/collections whose snapshot must be taken on creating or restarting the connector. | | String | *snapshotLockTimeoutMs* (postgres) | The maximum number of millis to wait for table locks at the beginning of a snapshot. If locks cannot be acquired in this time frame, the snapshot will be aborted. Defaults to 10 seconds | 10s | long | *snapshotMaxThreads* (postgres) | The maximum number of threads used to perform the snapshot. Defaults to 1. | 1 | int | *snapshotMode* (postgres) | The criteria for running a snapshot upon startup of the connector. Options include: 'always' to specify that the connector run a snapshot each time it starts up; 'initial' (the default) to specify the connector can run a snapshot only when no offsets are available for the logical server name; 'initial_only' same as 'initial' except the connector should stop after completing the snapshot and before it would normally start emitting changes;'never' to specify the connector should never run a snapshot and that upon first startup the connector should read from the last position (LSN) recorded by the server; and'exported' deprecated, use 'initial' instead; 'custom' to specify a custom class with 'snapshot.custom_class' which will be loaded and used to determine the snapshot, see docs for more details. | initial | String | *snapshotSelectStatement{zwsp}Overrides* (postgres) | This property contains a comma-separated list of fully-qualified tables (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on thespecific connectors. Select statements for the individual tables are specified in further configuration properties, one for each table, identified by the id 'snapshot.select.statement.overrides.DB_NAME.TABLE_NAME' or 'snapshot.select.statement.overrides.SCHEMA_NAME.TABLE_NAME', respectively. The value of those properties is the select statement to use when retrieving data from the specific table during snapshotting. A possible use case for large append-only tables is setting a specific point where to start (resume) snapshotting, in case a previous snapshotting was interrupted. | | String | *sourceStructVersion* (postgres) | A version of the format of the publicly visible source part in the message | v2 | String | *statusUpdateIntervalMs* (postgres) | Frequency for sending replication connection status updates to the server, given in milliseconds. Defaults to 10 seconds (10,000 ms). | 10s | int | *tableBlacklist* (postgres) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring (deprecated, use table.exclude.list instead) | | String | *tableExcludeList* (postgres) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring | | String | *tableIgnoreBuiltin* (postgres) | Flag specifying whether built-in tables should be ignored. | true | boolean | *tableIncludeList* (postgres) | The tables for which changes are to be captured | | String | *tableWhitelist* (postgres) | The tables for which changes are to be captured (deprecated, use table.include.list instead) | | String | *timePrecisionMode* (postgres) | Time, date, and timestamps can be represented with different kinds of precisions, including:'adaptive' (the default) bases the precision of time, date, and timestamp values on the database column's precision; 'adaptive_time_microseconds' like 'adaptive' mode, but TIME fields always use microseconds precision;'connect' always represents time, date, and timestamp values using Kafka Connect's built-in representations for Time, Date, and Timestamp, which uses millisecond precision regardless of the database columns' precision . | adaptive | String | *toastedValuePlaceholder* (postgres) | Specify the constant that will be provided by Debezium to indicate that the original value is a toasted value not provided by the database. If starts with 'hex:' prefix it is expected that the rest of the string repesents hexadecimally encoded octets. | __debezium_unavailable_value | String | *tombstonesOnDelete* (postgres) | Whether delete operations should be represented by a delete event and a subsquenttombstone event (true) or only by a delete event (false). Emitting the tombstone event (the default behavior) allows Kafka to completely delete all events pertaining to the given key once the source record got deleted. | false | boolean | *xminFetchIntervalMs* (postgres) | Specify how often (in ms) the xmin will be fetched from the replication slot. This xmin value is exposed by the slot which gives a lower bound of where a new replication slot could start from. The lower the value, the more likely this value is to be the current 'true' value, but the bigger the performance cost. The bigger the value, the less likely this value is to be the current 'true' value, but the lower the performance penalty. The default is set to 0 ms, which disables tracking xmin. | 0ms | long |=== // endpoint options: END For more information about configuration: https://debezium.io/documentation/reference/0.10/operations/embedded.html#engine-properties[https://debezium.io/documentation/reference/0.10/operations/embedded.html#engine-properties] https://debezium.io/documentation/reference/0.10/connectors/postgresql.html#connector-properties[https://debezium.io/documentation/reference/0.10/connectors/postgresql.html#connector-properties] == Message headers === Consumer headers The following headers are available when consuming change events from Debezium. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | DebeziumConstants.HEADER_IDENTIFIER | ""CamelDebeziumIdentifier"" | String | The identifier of the connector, normally is this format ""+++{server-name}.{database-name}.{table-name}+++"". | DebeziumConstants.HEADER_KEY | ""CamelDebeziumKey"" | Struct | The key of the event, normally is the table Primary Key. | DebeziumConstants.HEADER_SOURCE_METADATA | ""CamelDebeziumSourceMetadata"" | Map | The metadata about the source event, for example `table` name, database `name`, log position, etc, please refer to the Debezium documentation for more info. | DebeziumConstants.HEADER_OPERATION | ""CamelDebeziumOperation"" | String | If presents, the type of event operation. Values for the connector are `c` for create (or insert), `u` for update, `d` for delete or `r` in case of a snapshot event. | DebeziumConstants.HEADER_TIMESTAMP | ""CamelDebeziumTimestamp"" | Long | If presents, the time (using the system clock in the JVM) at which the connector processed the event. | DebeziumConstants.HEADER_BEFORE | ""CamelDebeziumBefore"" | Struct | If presents, contains the state of the row before the event occurred. |=== == Message body The message body if is not `null` (in case of tombstones), it contains the state of the row after the event occurred as `Struct` format or `Map` format if you use the included Type Converter from `Struct` to `Map` (please look below for more explanation). == Samples === Consuming events Here is a very simple route that you can use in order to listen to Debezium events from PostgresSQL connector. [source,java] ---- from(""debezium-postgres:dbz-test-1?offsetStorageFileName=/usr/offset-file-1.dat&databaseHostName=localhost&databaseUser=debezium&databasePassword=dbz&databaseServerName=my-app-connector&databaseHistoryFileName=/usr/history-file-1.dat"") .log(""Event received from Debezium : ${body}"") .log("" with this identifier ${headers.CamelDebeziumIdentifier}"") .log("" with these source metadata ${headers.CamelDebeziumSourceMetadata}"") .log("" the event occured upon this operation '${headers.CamelDebeziumSourceOperation}'"") .log("" on this database '${headers.CamelDebeziumSourceMetadata[db]}' and this table '${headers.CamelDebeziumSourceMetadata[table]}'"") .log("" with the key ${headers.CamelDebeziumKey}"") .log("" the previous value is ${headers.CamelDebeziumBefore}"") ---- By default, the component will emit the events in the body and `CamelDebeziumBefore` header as https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Struct.html[`Struct`] data type, the reasoning behind this, is to perceive the schema information in case is needed. However, the component as well contains a xref:manual::type-converter.adoc[Type Converter] that converts from default output type of https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Struct.html[`Struct`] to `Map` in order to leverage Camel's rich xref:manual::data-format.adoc[Data Format] types which many of them work out of box with `Map` data type. To use it, you can either add `Map.class` type when you access the message e.g: `exchange.getIn().getBody(Map.class)`, or you can convert the body always to `Map` from the route builder by adding `.convertBodyTo(Map.class)` to your Camel Route DSL after `from` statement. We mentioned above about the schema, which can be used in case you need to perform advance data transformation and the schema is needed for that. If you choose not to convert your body to `Map`, you can obtain the schema information as https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Schema.html[`Schema`] type from `Struct` like this: [source,java] ---- from(""debezium-postgres:[name]?[options]]) .process(exchange -> { final Struct bodyValue = exchange.getIn().getBody(Struct.class); final Schema schemaValue = bodyValue.schema(); log.info(""Body value is :"" + bodyValue); log.info(""With Schema : "" + schemaValue); log.info(""And fields of :"" + schemaValue.fields()); log.info(""Field name has `"" + schemaValue.field(""name"").schema() + ""` type""); }); ---- *Important Note:* This component is a thin wrapper around Debezium Engine as mentioned, therefore before using this component in production, you need to understand how Debezium works and how configurations can reflect the expected behavior, especially in regards to https://debezium.io/documentation/reference/0.9/operations/embedded.html#_handling_failures[handling failures]. include::{page-component-version}@camel-spring-boot::page$debezium-postgres-starter.adoc[] ",12158,True,3002.412439131936,median "/* heiz_app.ino, to be compiled with Arduino 1.6.5 */ //-------- includes -------------------------------------------------------------------------------> #include #include #include #include #include #include #include #include ""eth_private.h"" #include ""pushingbox_ids.h"" // your secret DevIDs from PushingBox.com #include ""allnet_ids.h"" // contains the Allnet IP socket mapping //<-------- includes ------------------------------------------------------------------------------- //-------- global variables -----------------------------------------------------------------------> #ifndef SQUARE #define SQUARE(X) ((X)*(X)) #endif #ifndef ABS #define ABS(X) ((X) > 0 ? (X) : (-(X))) #endif #ifndef MAX #define MAX(X,Y) ((X)>(Y) ? (X):(Y)) #endif #ifndef MIN #define MIN(X,Y) ((X)<(Y) ? (X):(Y)) #endif #ifndef ARRAYSIZE #define ARRAYSIZE(x) (sizeof(x)/sizeof(x[0])) #endif byte mac[] = ETH_PRIVATE_MAC; // your secret MAC address from eth_private.h // Set the static IP address to use if the DHCP fails to assign IPAddress ip ETH_PRIVATE_IP; // your secret network settings from eth_private.h IPAddress gateway ETH_PRIVATE_GATEWAY; IPAddress subnet ETH_PRIVATE_SUBNET; #define MAX_ETH_DATA 56 typedef union { byte bBytes[MAX_ETH_DATA]; struct { union { byte bData[MAX_ETH_DATA - sizeof(word)]; word wData[(MAX_ETH_DATA - sizeof(word)) / sizeof(word)]; struct { int16_t swTemperaturWarmWasserLO; int16_t swTemperaturHeizungLM; int16_t swTemperaturHeizungLU; int16_t swTemperaturHeizungRO; int16_t swTemperaturHeizungRU; int16_t swTemperaturAussen; int16_t swTemperaturHeizraum; int16_t swTemperaturKesselwasser; int16_t swTemperaturAbgase; int16_t swTemperaturAussenMittel; int16_t swTemperaturAussenMin; int16_t swTemperaturAussenMax; int16_t swUpTime; int16_t swHolzmenge; int16_t swEinheizZeitpunkt; /*word wAbsFeuchteZuluft; word wAbsFeuchteAbluft; byte bLuefterdrehzahl; bool bLuefterEnabled; bool bHausbeleuchtungEnabled; word wHausbeleuchtungOnTime;*/ bool bReboot; // neue Daten hier einfügen }; }; word wCRC16; // muss unbedingt an letzter Stelle stehen! }; } EthernetDataStruct; EthernetDataStruct EthernetData; #define AREF_VOLTAGE 5000L // mV #define AVR_ADC_RANGE 1024L // ADU #define LM61_OFFSET 600L // mV #define LM61_GAIN 10L // mV/K #define ADC_AVERAGING 1 int sensorPin = A3; // Heizraumtemperatur Adafruit_ADS1115 ads; /* Use this for the 16-bit version */ #define ADS_ADC_RANGE 32767L // ADU #define PT1000_REFERENZ_WERT 1000000L // mOhm bei 0 Grad Celsius #define PT1000_TEMP_KOEFFIZIENT 3851L // ppm/K #define PT1000_SPANNUNGSTEILER_WIDERSTAND 4700L // Ohm fuer maximalen Hub #define PT1000_SPANNUNGSTEILER_SPANNUNG 5000L //mV #define ADS_REF_SPANNUNG 4096L // mV #define ADS_GAIN_2X (2L) int32_t dwSpannungsTeilerSpannung = PT1000_SPANNUNGSTEILER_SPANNUNG; #define TEMPERATUR_OFFSET (16) // 1.6 K // Mittelung der Aussentemperatur: #define MESSINTERVALL (15) // Minuten #define AT_ZEITRAUM (18) // Zeitraum in Stunden #define AT_MESSUNG_PRO_H (60 / MESSINTERVALL) // Messungen pro Stunde #define NR_AT_WERTE (AT_ZEITRAUM * AT_MESSUNG_PRO_H) #define PUSH_PERIOD_WW (((3 * 60) / MESSINTERVALL) - 1) // Intervall 3h, umgerechnet in Viertelstunden #define PUSH_PERIOD_HZ (((2 * 60) / MESSINTERVALL) - 1) // Intervall 2h, umgerechnet in Viertelstunden #define PUSH_PERIOD_AT (((6 * 60) / MESSINTERVALL) - 1) // Intervall 6h, umgerechnet in Viertelstunden #define WARMWASSERLIMIT (40*10) // [1/10 ° Celsius] #define HEIZWASSERLIMIT (29*10) // [1/10 ° Celsius] #define HEIZPUMPENLIMIT (12*10) // [1/10 ° Celsius], Aussentemperatur, unterhalb derer die Pumpe laufen muss // Pushing Box Parameter #define RECEIVER_WW 0x01 #define RECEIVER_HZ 0x02 #define RECEIVER_AT 0x03 #define RECEIVER_STATUS 0x04 #define RECEIVER_TM 0x05 #define PUSHINGBOX_SERVERPFAD ""/pushingbox"" #define PUSHINGBOX_SERVERNAME ""api.pushingbox.com"" //Konstanten in Programmspeicher, die gebraucht werden um die HTTP-GET Anfrage zusammenzusetzen const char PUSHINGBOX_WW_STRING[] = {PUSHINGBOX_DEVID_WW""&wwtemp=""}; const char PUSHINGBOX_HZ_STRING[] = {PUSHINGBOX_DEVID_HZ""&hztemp=""}; const char PUSHINGBOX_ATMEAN_STRING[] = {PUSHINGBOX_DEVID_AT""&atmean=""}; const char PUSHINGBOX_HZTIME_STRING[] = {PUSHINGBOX_DEVID_TM""&hztime=""}; const char PUSHINGBOX_HOLZMENGE_STRING[] = {""&holzm=""}; const char PUSHINGBOX_STATUS_ID_AT_STRING[] = {PUSHINGBOX_DEVID_STATUS""&at=""}; const char PUSHINGBOX_STATUS_ATMEAN_STRING[] = {""&atmean=""}; const char PUSHINGBOX_STATUS_ATMIN_STRING[] = {""&atmin=""}; const char PUSHINGBOX_STATUS_ATMAX_STRING[] = {""&atmax=""}; const char PUSHINGBOX_STATUS_WW_STRING[] = {""&wwtemp=""}; const char PUSHINGBOX_STATUS_HZ_STRING[] = {""&hztemp=""}; char serverName[] = ""api.pushingbox.com""; byte serverAllnet[] = {192, 168, 234, 70}; boolean lastConnected = false; // State of the connection last time through the main loop boolean lastConnectedAllnet = false; // State of the connection last time through the main loop // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): EthernetClient client; EthernetClient allnetclient; // time.nist.gov NTP server char timeServer[] = ""ptbtime1.ptb.de""; const int timeZone = +1; // Central European Time EthernetUDP Udp; unsigned int localPort = 8888; // local port to listen for UDP packets time_t prevDisplay = 0; // when the digital clock was displayed bool bSekundenwechsel = false; int32_t meanbuffer; int16_t messreihe[NR_AT_WERTE]; unsigned char mrc = 0; bool bStartup = true; unsigned char ww_push_timer = 0; unsigned char at_push_timer = 0; unsigned char hz_push_timer = 0; bool bUpdateStatus = false; bool bWarmwasserWarnung = false; bool bHeizwasserWarnung = false; bool bAussentemperaturWarnung = false; bool bUpdateHeizzeit = false; bool bSchalteHeizpumpe = false; bool bAktiviereHeizpumpe = false; // telnet defaults to port 23 EthernetServer chatserver(23); boolean alreadyConnected = false; // whether or not the client was connected previously //<-------- global variables ----------------------------------------------------------------------- //-------- setup code -----------------------------------------------------------------------------> void setup() { Serial.begin(9600); for (int i = 0; i < 10*60; i++) // startup delay of 10 minutes for router to come up { delay(1000); } // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println(""Failed to configure Ethernet using DHCP""); // no point in carrying on, so do nothing forevermore: // try to congifure using IP address instead of DHCP: Ethernet.begin(mac, ip, gateway, subnet); } else { Serial.println(""Ethernet ready""); // print the Ethernet board/shield's IP address: Serial.print(""My IP address: ""); Serial.println(Ethernet.localIP()); } // give the Ethernet shield a second to initialize: delay(1000); for (int i = 0; i < MAX_ETH_DATA; i++) { EthernetData.bBytes[i] = 0; } // start listening for chat clients chatserver.begin(); Udp.begin(localPort); Serial.println(""waiting for sync""); setSyncProvider(getNtpTime); // The ADC input range (or gain) can be changed via the following // functions, but be careful never to exceed VDD +0.3V max, or to // exceed the upper and lower limits if you adjust the input range! // Setting these values incorrectly may destroy your ADC! // ADS1115 // ------- // ads.setGain(GAIN_TWOTHIRDS); // 2/3x gain +/- 6.144V 1 bit = 0.1875mV (default) // ads.setGain(GAIN_ONE); // 1x gain +/- 4.096V 1 bit = 0.125mV // ads.setGain(GAIN_TWO); // 2x gain +/- 2.048V 1 bit = 0.0625mV // ads.setGain(GAIN_FOUR); // 4x gain +/- 1.024V 1 bit = 0.03125mV // ads.setGain(GAIN_EIGHT); // 8x gain +/- 0.512V 1 bit = 0.015625mV // ads.setGain(GAIN_SIXTEEN); // 16x gain +/- 0.256V 1 bit = 0.0078125mV ads.begin(); } //<-------- setup code ----------------------------------------------------------------------------- //-------- loop code ------------------------------------------------------------------------------> void loop() { if (timeStatus() != timeNotSet) { if (now() != prevDisplay) { //update the display only if time has changed prevDisplay = now(); bSekundenwechsel = true; } } if (bSekundenwechsel) // Sekundenwechsel { bSekundenwechsel = false; if (second() % 5 == 0) readTemperaturWarmwasserLO(); if (second() % 5 == 1) readTemperaturPufferLM(); if (second() % 5 == 2) readSpannungsTeilerSpannung(); if (second() % 5 == 3) readAussenTemperatur(); // Ausentemperatur if (second() % 5 == 4) read_AIN_CH3(); // Heizraumtemperatur if (second() == 0) // Minutenwechsel { if (minute() == 0) // nur bei Stundenwechsel { EthernetData.swUpTime++; } if (minute() == 25) // stuendlich twittern, um jeweils kurz vor halb { bUpdateStatus = true; //Serial.println(""Update!""); } if (bStartup) // zuegig mit Daten fuellen { bStartup = false; for (unsigned char i = 0; i < NR_AT_WERTE; i++) { messreihe[i] = EthernetData.swTemperaturAussen; } EthernetData.swTemperaturAussenMittel = EthernetData.swTemperaturAussen; EthernetData.swTemperaturAussenMin = EthernetData.swTemperaturAussen; EthernetData.swTemperaturAussenMax = EthernetData.swTemperaturAussen; } if (minute() % MESSINTERVALL == 0) { messreihe[mrc] = EthernetData.swTemperaturAussen; meanbuffer = 0; EthernetData.swTemperaturAussenMin = +10000; EthernetData.swTemperaturAussenMax = -10000; for (unsigned char i = 0; i < NR_AT_WERTE; i++) { meanbuffer += messreihe[i]; //Serial.println(""mr%i:%i"", i, messreihe[i]); EthernetData.swTemperaturAussenMin = MIN(messreihe[i], EthernetData.swTemperaturAussenMin); EthernetData.swTemperaturAussenMax = MAX(messreihe[i], EthernetData.swTemperaturAussenMax); } meanbuffer /= NR_AT_WERTE; EthernetData.swTemperaturAussenMittel = meanbuffer; berechneHolzMenge(); //Serial.println(""ATM:%i.%i"", EthernetData.swTemperaturAussenMittel/10, EthernetData.swTemperaturAussenMittel%10); //Serial.println(""ATMin:%i.%i"", EthernetData.swTemperaturAussenMin/10, EthernetData.swTemperaturAussenMin%10); //Serial.println(""ATMax:%i.%i"", EthernetData.swTemperaturAussenMax/10, EthernetData.swTemperaturAussenMax%10); if (++mrc == NR_AT_WERTE) { mrc = 0; } // Warmwasser ueberwachen: if (EthernetData.swTemperaturWarmWasserLO < WARMWASSERLIMIT) { if (ww_push_timer == 0) { ww_push_timer = PUSH_PERIOD_WW; // alle 3 Stunden benachrichtigen bWarmwasserWarnung = true; //Serial.println(""Warmwasser!""); } else { ww_push_timer--; } } else { ww_push_timer = 0; } // Warmwasser #warning Warmwasser-Zeitpunkt auch noch extrapolieren // Heizwasser ueberwachen: if ((EthernetData.swTemperaturHeizungLM < HEIZWASSERLIMIT) && (EthernetData.swTemperaturAussenMittel < HEIZPUMPENLIMIT)) { if (hz_push_timer == 0) { hz_push_timer = PUSH_PERIOD_HZ; // alle 2 Stunden benachrichtigen bHeizwasserWarnung = true; //Serial.println(""Heizwasser!""); } else { hz_push_timer--; } } else { hz_push_timer = 0; } // Heizwasser // Aussentemperatur ueberwachen: if (at_push_timer == 0) { at_push_timer = PUSH_PERIOD_AT; // alle 6 Stunden kontrollieren bSchalteHeizpumpe = true; if (EthernetData.swTemperaturAussenMittel < HEIZPUMPENLIMIT) { bAussentemperaturWarnung = true; bAktiviereHeizpumpe = true; //Serial.println(""Aussentemperatur!""); } else { bAktiviereHeizpumpe = false; } } else { at_push_timer--; } // Aussentemperatur } // Messintervall if (minute() == 40) // stuendlich pruefen { if (EthernetData.swTemperaturAussenMittel < HEIZPUMPENLIMIT) { int16_t time_buffer; static int16_t extrapoldata[3]; //alte Werte sichern: extrapoldata[2] = extrapoldata[1]; // 2h extrapoldata[1] = extrapoldata[0]; // 1h extrapoldata[0] = EthernetData.swTemperaturHeizungLM; // aktuelle Temperatur // Temperaturabfall ueber zwei Stunden ermitteln und extrapolieren bis zum Einheizen: time_buffer = (HEIZWASSERLIMIT - extrapoldata[0]); time_buffer /= ((extrapoldata[0] - extrapoldata[2]) / 2); if (extrapoldata[0] > HEIZWASSERLIMIT) { EthernetData.swEinheizZeitpunkt = (time_buffer > 0 ? time_buffer : 24); } else { EthernetData.swEinheizZeitpunkt = 0; } bUpdateHeizzeit = true; } } // Einheiz-Zeitpunkt } // Minutenwechsel } // Sekundenwechsel if (bUpdateStatus) { sendToPushingBox(RECEIVER_STATUS); digitalClockDisplay(); bUpdateStatus = false; } else if (bWarmwasserWarnung) { sendToPushingBox(RECEIVER_WW); digitalClockDisplay(); bWarmwasserWarnung = false; } else if (bHeizwasserWarnung) { sendToPushingBox(RECEIVER_HZ); digitalClockDisplay(); bHeizwasserWarnung = false; } else if (bAussentemperaturWarnung) { sendToPushingBox(RECEIVER_AT); digitalClockDisplay(); bAussentemperaturWarnung = false; } else if (bSchalteHeizpumpe) { activateHeatPump(bAktiviereHeizpumpe); digitalClockDisplay(); bSchalteHeizpumpe = false; } else if (bUpdateHeizzeit) { sendToPushingBox(RECEIVER_TM); bUpdateHeizzeit = false; } // the response from PushingBox Server, you should see a ""200 OK"" if (client.available()) { char c = client.read(); Serial.print(c); } // the response from PushingBox Server, you should see a ""200 OK"" if (allnetclient.available()) { char c = allnetclient.read(); Serial.print(c); } // wait for a new chatclient: EthernetClient chatclient = chatserver.available(); // when the chatclient sends the first byte, say hello: if (chatclient) { if (!alreadyConnected) { // clead out the input buffer: chatclient.flush(); chatclient.println(""Hello, chatclient!""); alreadyConnected = true; } if (chatclient.available() > 0) { // read the bytes incoming from the chatclient: char telcommand = chatclient.read(); chatclient.println("" ""); switch (telcommand) { case 's': bUpdateStatus = true; break; case 't': chatclient.print(hour()); chatclient.print("":""); chatclient.print(minute()); chatclient.print("":""); chatclient.print(second()); chatclient.print("" ""); chatclient.print(day()); chatclient.print("".""); chatclient.print(month()); chatclient.print("".""); chatclient.print(year()); chatclient.println(); break; case 'v': chatclient.println(dwSpannungsTeilerSpannung); break; case '?': chatclient.println(""s: twitter status message""); chatclient.println(""t: local time""); chatclient.println(""v: Pt1000 voltage""); chatclient.println(""?: print this help""); break; default: break; } } } // if there's no net connection, but there was one last time // through the loop, then stop the client: if (!client.connected() && lastConnected) { Serial.println(); Serial.println(""disconnecting.""); client.stop(); } lastConnected = client.connected(); if (!allnetclient.connected() && lastConnectedAllnet) { Serial.println(); Serial.println(""disconnecting.""); allnetclient.stop(); } lastConnectedAllnet = allnetclient.connected(); } // main loop //<-------- loop code ------------------------------------------------------------------------------ //-------- analog code ----------------------------------------------------------------------------> void readTemperaturWarmwasserLO(void) { ads.setGain(GAIN_TWO); // 2x gain +/- 2.048V 1 bit = 0.0625mV int32_t buffer = ads.readADC_SingleEnded(0); if (buffer == ADS_ADC_RANGE) { Serial.println(""WW: n.c.""); return; } // Temperatur in 1/10K berechnen: int64_t Ua = (ADS_REF_SPANNUNG * buffer) / ADS_ADC_RANGE / ADS_GAIN_2X; // mV int64_t Rtemp = (Ua * PT1000_SPANNUNGSTEILER_WIDERSTAND * 1000L) / (dwSpannungsTeilerSpannung - Ua); // mOhm Rtemp -= PT1000_REFERENZ_WERT; Rtemp *= 10; Rtemp /= PT1000_TEMP_KOEFFIZIENT; EthernetData.swTemperaturWarmWasserLO = Rtemp; //Serial.println(""WW:%i.%i"", EthernetData.swTemperaturWarmWasserLO/10, EthernetData.swTemperaturWarmWasserLO%10); } void readTemperaturPufferLM(void) { ads.setGain(GAIN_TWO); // 2x gain +/- 2.048V 1 bit = 0.0625mV int32_t buffer = ads.readADC_SingleEnded(1); if (buffer == ADS_ADC_RANGE) { Serial.println(""HZ: n.c.""); return; } // Temperatur in 1/10K berechnen: int64_t Ua = (ADS_REF_SPANNUNG * buffer) / ADS_ADC_RANGE / ADS_GAIN_2X; // mV int64_t Rtemp = (Ua * PT1000_SPANNUNGSTEILER_WIDERSTAND * 1000L) / (dwSpannungsTeilerSpannung - Ua); // mOhm Rtemp -= PT1000_REFERENZ_WERT; Rtemp *= 10; Rtemp /= PT1000_TEMP_KOEFFIZIENT; EthernetData.swTemperaturHeizungLM = Rtemp; //Serial.println(""HZ:%i.%i"", EthernetData.swTemperaturHeizungLM/10, EthernetData.swTemperaturHeizungLM%10); } void readSpannungsTeilerSpannung(void) { ads.setGain(GAIN_TWOTHIRDS); // 2/3x gain +/- 6.144V 1 bit = 0.1875mV (default) int32_t buffer = ads.readADC_SingleEnded(2); if (buffer == ADS_ADC_RANGE) { Serial.println(""Vdd: n.c.""); dwSpannungsTeilerSpannung = PT1000_SPANNUNGSTEILER_SPANNUNG; return; } // Temperatur in 1/10K berechnen: dwSpannungsTeilerSpannung = (ADS_REF_SPANNUNG * buffer) / ADS_ADC_RANGE; // mV dwSpannungsTeilerSpannung *= 3; // PGA ist 2/3! dwSpannungsTeilerSpannung /= 2; //Serial.println(""Vdd:%i mV"", dwSpannungsTeilerSpannung); //Serial.println(""HR:%i.%i"", EthernetData.swTemperaturHeizraum/10, EthernetData.swTemperaturHeizraum%10); } void readAussenTemperatur(void) { ads.setGain(GAIN_TWO); // 2x gain +/- 2.048V 1 bit = 0.0625mV int32_t buffer = ads.readADC_SingleEnded(3); if (buffer == ADS_ADC_RANGE) { Serial.println(""AT: n.c.""); return; } // Temperatur in 1/10K berechnen: int64_t Ua = (ADS_REF_SPANNUNG * buffer) / ADS_ADC_RANGE / ADS_GAIN_2X; // mV int64_t Rtemp = (Ua * PT1000_SPANNUNGSTEILER_WIDERSTAND * 1000L) / (dwSpannungsTeilerSpannung - Ua); // mOhm Rtemp -= PT1000_REFERENZ_WERT; Rtemp *= 10; Rtemp /= PT1000_TEMP_KOEFFIZIENT; EthernetData.swTemperaturAussen = Rtemp; EthernetData.swTemperaturAussen -= TEMPERATUR_OFFSET; //Serial.println(""AT:%i.%i"", EthernetData.swTemperaturAussen/10, EthernetData.swTemperaturAussen%10); } void read_AIN_CH3(void) // AIN3, LM61 { int32_t buffer = analogRead(sensorPin); EthernetData.swTemperaturHeizraum = ((((buffer * AREF_VOLTAGE) / (ADC_AVERAGING * AVR_ADC_RANGE)) - LM61_OFFSET) * 10) / LM61_GAIN; //Serial.println(EthernetData.swTemperaturHeizraum); } void berechneHolzMenge(void) { int8_t aussentemp = EthernetData.swTemperaturAussenMittel / 10; if (aussentemp <= 5) { EthernetData.swHolzmenge = 18; return; } if (aussentemp <= 7 && aussentemp >= 6) { EthernetData.swHolzmenge = 16; return; } if (aussentemp = 8) { EthernetData.swHolzmenge = 14; return; } if (aussentemp <= 11 && aussentemp >= 9) { EthernetData.swHolzmenge = 18; return; } if (aussentemp = 12) { EthernetData.swHolzmenge = 16; return; } if (aussentemp = 13) { EthernetData.swHolzmenge = 18; return; } if (aussentemp = 14) { EthernetData.swHolzmenge = 16; return; } if (aussentemp >= 15) { EthernetData.swHolzmenge = 16; return; } } //<-------- analog code ---------------------------------------------------------------------------- void activateHeatPump(bool state_on) { sendToAllnet(ALLNET_DEVID_FBH, state_on); sendToAllnet(ALLNET_DEVID_HK, state_on); } //-------- Allnet code ------------------------------------------------------------------------------- //Function for sending the request to PushingBox void sendToAllnet(char switch_id, bool state) { allnetclient.stop(); Serial.println(""allnet: connecting...""); if (allnetclient.connect(serverAllnet, 80)) { Serial.println(""connected, sending request""); allnetclient.print(""GET /xml/jsonswitch.php?id=""); //Kopiere HTTP-Get Anfrage in den TCP-Buffer allnetclient.print(switch_id, DEC); allnetclient.print(""&set=""); allnetclient.print(state, DEC); allnetclient.println("" HTTP/1.1""); allnetclient.print(""Host: ""); allnetclient.println(""ALL4076""); // ??? allnetclient.println(""User-Agent: Heizarduino""); allnetclient.println(); } else { Serial.println(""allnet: connection failed""); } } //<-------- Allnet code ------------------------------------------------------------------------------ //-------- push code ------------------------------------------------------------------------------- //Function for sending the request to PushingBox void sendToPushingBox(char push_receiver) { client.stop(); Serial.println(""connecting...""); if (client.connect(serverName, 80)) { Serial.println(""connected, sending request""); client.print(""GET /pushingbox?devid=""); switch (push_receiver) //Kopiere HTTP-Get Anfrage in den TCP-Buffer { case RECEIVER_WW: client.print(PUSHINGBOX_WW_STRING); client.print(EthernetData.swTemperaturWarmWasserLO / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturWarmWasserLO) % 10, DEC); // Holzmenge: client.print(PUSHINGBOX_HOLZMENGE_STRING); client.print(EthernetData.swHolzmenge, DEC); break; case RECEIVER_HZ: client.print(PUSHINGBOX_HZ_STRING); client.print(EthernetData.swTemperaturHeizungLM / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturHeizungLM) % 10, DEC); // Holzmenge: client.print(PUSHINGBOX_HOLZMENGE_STRING); client.print(EthernetData.swHolzmenge, DEC); break; case RECEIVER_AT: client.print(PUSHINGBOX_ATMEAN_STRING); client.print(EthernetData.swTemperaturAussenMittel / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturAussenMittel) % 10, DEC); break; case RECEIVER_TM: client.print(PUSHINGBOX_HZTIME_STRING); client.print(EthernetData.swEinheizZeitpunkt, DEC); break; case RECEIVER_STATUS: // Aussentemperatur Aktuell: client.print(PUSHINGBOX_STATUS_ID_AT_STRING); client.print(EthernetData.swTemperaturAussen / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturAussen) % 10, DEC); // Aussentemperatur Mittel: client.print(PUSHINGBOX_STATUS_ATMEAN_STRING); client.print(EthernetData.swTemperaturAussenMittel / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturAussenMittel) % 10, DEC); // Aussentemperatur Min: client.print(PUSHINGBOX_STATUS_ATMIN_STRING); client.print(EthernetData.swTemperaturAussenMin / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturAussenMin) % 10, DEC); // Aussentemperatur Max: client.print(PUSHINGBOX_STATUS_ATMAX_STRING); client.print(EthernetData.swTemperaturAussenMax / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturAussenMax) % 10, DEC); // Warmwassertemperatur: client.print(PUSHINGBOX_STATUS_WW_STRING); client.print(EthernetData.swTemperaturWarmWasserLO / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturWarmWasserLO) % 10, DEC); // Heizwassertemperatur: client.print(PUSHINGBOX_STATUS_HZ_STRING); client.print(EthernetData.swTemperaturHeizungLM / 10, DEC); client.print('.'); client.print(ABS(EthernetData.swTemperaturHeizungLM) % 10, DEC); break; } client.println("" HTTP/1.1""); client.print(""Host: ""); client.println(serverName); client.println(""User-Agent: Heizarduino""); client.println(); } else { Serial.println(""connection failed""); } } //<-------- push code ------------------------------------------------------------------------------ //-------- NTP code -------------------------------------------------------------------------------> const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets void digitalClockDisplay() { // digital clock display of the time Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.print("" ""); Serial.print(day()); Serial.print("".""); Serial.print(month()); Serial.print("".""); Serial.print(year()); Serial.println(); } void printDigits(int digits) { // utility for digital clock display: prints preceding colon and leading 0 Serial.print("":""); if (digits < 10) Serial.print('0'); Serial.print(digits); } time_t getNtpTime() { while (Udp.parsePacket() > 0) ; // discard any previously received packets Serial.println(""Transmit NTP Request""); sendNTPpacket(timeServer); uint32_t beginWait = millis(); while (millis() - beginWait < 1500) { int size = Udp.parsePacket(); if (size >= NTP_PACKET_SIZE) { Serial.println(""Receive NTP Response""); Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer unsigned long secsSince1900; // convert four bytes starting at location 40 to a long integer secsSince1900 = (unsigned long)packetBuffer[40] << 24; secsSince1900 |= (unsigned long)packetBuffer[41] << 16; secsSince1900 |= (unsigned long)packetBuffer[42] << 8; secsSince1900 |= (unsigned long)packetBuffer[43]; return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR; } } Serial.println(""No NTP Response :-(""); return 0; // return 0 if unable to get the time } // send an NTP request to the time server at the given address void sendNTPpacket(char* address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } //<-------- NTP code ------------------------------------------------------------------------------- ",8343,False,1474.2279781367372,median "/* 1- Wi-Fi -User interface for SSID/Password OK 2- Local Date/Time Set OK 3- Local Temp/Hum OK 4- External Temp/Hum (WUnderground) OK Deleted for now. 5- Trigger Intervals -30 sec local check OK -10 mins #4 update OK Deleted for now -24h reboot OK Deleted for now 6- Alexa - Alexa request -English -Turn On OK -Turn Off OK -Get Room Temp OK -Set Temp OK -Get Settings OK -Diag OK -upTime OK -Spanish -Turn On -Turn Off -Get Room Temp -Set Room Temp 5- Screen -Main Screen - + Temp (UP) OK - - Temp (Down) OK - Room Temp OK - Set Temp OK - Light Indicator On OK - Light Indicator Heat on OK -Diagnostic Screen -On/Off Status OK -Room Temp OK -Set Temp OK -External Temp Not for now -Heat Index OK -Date/Time OK -UpTime OK -Last Alexa Access OK -Network Screen -SSID OK -IP OK -Gateway OK -MAC OK -Signal WiFi.RSSI() OK -System Screen -Date Time (Running) OK -Version OK -Uptime OK -Internal Voltage OK 8- Optimize -Delete/Comment Println -Delete/Comment unnecesary code 9- Document -Standatd header -short function/sub comments -any relevant comment needed. */ /* Thermostat Logic. Room Temp: Temperature is retirved every 30 secs from the DHT11 Sensor. Set Temp: Temperature that starts or stops the heating. This value is set via Nextion Screen or Alexa. On/Off: This setting is the device ""On/Off"". If Off, the heat is alwas off regardless of the Set/Room values. If On, Set/Room values dictacte if relay is on or off. Every 30 secs: (CheckTemp fucntion) If On/Off = 1 (True or On) If Room Temp < Set Temp Open Relay Update Nextion Else Close Relay Update Nextion Else Do Nothing On On/Off button Change CheckTemp function On Set Temp Value Change (Alexa/Nextion) CheckTemp function */ // ----- Include Section ------ #include #include #include #include #include //https://github.com/tzapu/WiFiManager #include #include #include #include #include #include #include #include #include #include #include ""DHT.h"" #include #define CAYENNE_PRINT Serial // Comment this out to disable prints and save space #include // Change this to use a different communication device. See Communications examples. ADC_MODE(ADC_VCC); /*---- Global Vars ----*/ int ExTemp = 0; int ExHum = 0; int RoomTem = 0; int RoomHum = 0; int HeatIndex = 0; int SetTemp = 23; String TempSP[46] = {""Cero"", ""Uno"", ""Dos"", ""Tres"", ""Cuatro"", ""Cinco"", ""Seis"", ""Siete"", ""Ocho"", ""Nueve"", ""Diez"", ""Once"", ""Doce"", ""Trece"", ""Catorce"", ""Quince"", ""Dieciseis"", ""Diecisiete"", ""Dieciocho"", ""Diesi nueve"", ""Veinte"", ""Veintiuno"", ""Veintidos"", ""Veintitres"", ""Veinticuatro"", ""Veinticinco"", ""Veintiseis"", ""Veintisiete"", ""Veintiocho"", ""Veintinueve"", ""Treinta"", ""TreintaiUno"", ""TreintaiDos"", ""TreintaiTres"", ""TreintaiCuatro"", ""TreintaiCinco"", ""TreintaiSeis"", ""TreintaiSiete"", ""TreintaiOcho"", ""TreintaiNueve"", ""Cuarenta"", ""CuarentaiUno"", ""CuarentaiDos"", ""CuarentaiTres"", ""CuarentaiCuatro"", ""CuarentaiCinco""}; String MonthNames[13] = {"""", ""January"", ""February"", ""March"", ""April"", ""May"", ""June"", ""July"", ""August"", ""September"", ""October"", ""November"", ""December""}; bool ThermStatus = false; #define RelayPin D5 #define DHTPIN D6 #define NextionRX D7 #define NextionTX D8 #define OnLED D4 #define HeatLED D4 int bootTime = 0; int AlexaTime = 0; #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); char chaTemp[16]; // Cayenne authentication info. This should be obtained from the Cayenne Dashboard. char username[] = ""e65997b0-2d8d-11e8-b1c6-0d0b749c9848""; char password[] = ""88c40fa0cff1aa7d5c4f86903f78636cb23dad6b""; char clientID[] = ""f97d30f0-2dd7-11e8-af7b-4f8845dd6501""; /*-------- Web Server code ----------------*/ ESP8266WebServer server(81); String webString = """"; // String to display void handle_root() { server.send(200, ""text/plain"", ""You are now connected to the home thermostat.""); //Serial.println(""HTTP root has been called.""); Alarm.delay(500); } //Nextion SoftwareSerial nextionSerial(NextionRX, NextionTX); // RX, TX Nextion nex(nextionSerial); //Page0 NextionNumber txtRoomTemp(nex, 0, 2, ""txtRoomTemp""); NextionNumber txtSetTemp(nex, 0, 1, ""txtSetTemp""); NextionHotspot sp_Up(nex, 0, 3, ""sp_Up""); NextionHotspot sp_Down(nex, 0, 4, ""sp_Down""); NextionHotspot hs_OnOff(nex, 0, 7, ""hs_OnOff""); NextionText txt_MainTime(nex, 0, 22, ""txt_MainTime""); NextionHotspot hs_Diagnostics0(nex, 0, 19, ""hs_Diagnostics""); NextionHotspot hs_Network0(nex, 0, 9, ""hs_Network""); NextionHotspot hs_Systems0(nex, 0, 21, ""hs_Systems""); NextionHotspot hs_reset(nex, 0, 20, ""hs_reset""); NextionVariableString varLocalIP(nex, 0, 10, ""varLocalIP""); NextionVariableString varSSID(nex, 0, 11, ""varSSID""); NextionVariableString varHost(nex, 0, 12, ""varHost""); NextionVariableString varGateway(nex, 0, 13, ""varGateway""); NextionVariableString varMAC(nex, 0, 14, ""varMAC""); NextionPicture pRunning(nex, 0, 16, ""pRunning""); NextionPicture pBooting(nex, 0, 15, ""pBooting""); NextionVariableNumeric varOnOff(nex, 0, 8, ""varOnOff""); NextionVariableNumeric varRunning(nex, 0, 17, ""varRunning""); NextionVariableNumeric varBooting(nex, 0, 18, ""varBooting""); //Page1 NextionText txt_SSID(nex, 1, 3, ""txt_SSID""); NextionText txt_HOST(nex, 1, 4, ""txt_HOST""); NextionText txt_IP(nex, 1, 5, ""txt_IP""); NextionText txt_GATEWAY(nex, 1, 6, ""txt_GATEWAY""); NextionText txt_MAC(nex, 1, 7, ""txt_MAC""); NextionHotspot hs_Thermostat1(nex, 1, 1, ""hs_Thermostat""); NextionHotspot hs_Diagnostics1(nex, 1, 8, ""hs_Diagnostics""); NextionHotspot hs_Systems1(nex, 1, 9, ""hs_Systems""); //Page2 NextionText txt_Diga(nex, 2, 3, ""txt_Diga""); NextionHotspot hp_Thermostat2(nex, 2, 1, ""hp_Thermostat""); NextionHotspot hs_Network2(nex, 2, 2, ""hs_Network""); NextionHotspot hs_Systems2(nex, 2, 4, ""hs_Systems""); //Page3 NextionText txt_Date(nex, 3, 4, ""txt_Date""); NextionText txt_SDK(nex, 3, 5, ""txt_SDK""); NextionText txt_CPU(nex, 3, 6, ""txt_CPU""); NextionText txt_Size(nex, 3, 7, ""txt_Size""); NextionText txt_ADC(nex, 3, 8, ""txt_ADC""); NextionText txt_Core(nex, 3, 9, ""txt_Core""); NextionText txt_Uptime(nex, 3, 10, ""txt_Uptime""); NextionHotspot hs_Thermostat3(nex, 3, 1, ""hs_Thermostat""); NextionHotspot hs_Diagnostics3(nex, 3, 2, ""hs_Diagnostics""); NextionHotspot hs_Network3(nex, 3, 3, ""hs_Network""); #define ThermoOn 65535 #define ThermoOff 63488 void PowerOnLED(int RPin, int RelayState) { pinMode(RPin, OUTPUT); digitalWrite(RPin, RelayState); }; void HeatOnLED(int RPin, int RelayState) { pinMode(RPin, OUTPUT); digitalWrite(RPin, RelayState); }; void TurnOff() { Serial.println("" Status is On ---> Off""); varOnOff.setValue(0); nex.sendCommand(""vis pRedOff,1""); nex.sendCommand(""vis pBlueOn,0""); txtSetTemp.setForegroundColour(ThermoOff); ThermStatus = false; } void TurnOn() { Serial.println("" Status is Off ---> On""); varOnOff.setValue(1); nex.sendCommand(""vis pRedOff,0""); nex.sendCommand(""vis pBlueOn,1""); txtSetTemp.setForegroundColour(ThermoOn); ThermStatus = true; } void OnOffCallback(NextionEventType type, INextionTouchable *widget) { if (type == NEX_EVENT_POP) { int nTemp; Serial.print(""On Off was pressed :""); nTemp = varOnOff.getValue(); if (nTemp == 0) { TurnOn(); } else { TurnOff(); } CheckThermo(); } } void callback(NextionEventType type, INextionTouchable *widget) { if (type == NEX_EVENT_PUSH) { } else if (type == NEX_EVENT_POP) { ////Serial.println(""Push2""); Serial.print(""Changing SetTemp from ""); Serial.print(SetTemp); SetTemp = txtSetTemp.getValue(); Serial.print("" -----> ""); Serial.println(SetTemp); CheckThermo(); } } void OpenDiagScreen(NextionEventType type, INextionTouchable *widget) { Serial.println(""--------------------------------------""); if (type == NEX_EVENT_POP) { NextionDiag(txt_Diga); } } void OpenSystemsScreen(NextionEventType type, INextionTouchable *widget) { Serial.println(""--------------------------------------""); if (type == NEX_EVENT_POP) { SystemScreen(); } } void HS_Reset(NextionEventType type, INextionTouchable *widget) { Serial.println(""R E S E T - R E B O O T""); if (type == NEX_EVENT_POP) { RebootESP(); } } //NTP static const char ntpServerName[] = ""us.pool.ntp.org""; const int timeZone = -3; // Chile WiFiUDP Udp; unsigned int localPort = 8888; // local port to listen for UDP packets time_t getNtpTime(); void sendNTPpacket(IPAddress &address); /*-------- NTP code ----------*/ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets time_t getNtpTime() { IPAddress ntpServerIP; // NTP server's ip address while (Udp.parsePacket() > 0) ; // discard any previously received packets //Serial.println(""Transmit NTP Request""); // get a random server from the pool if (String(ntpServerIP) == ""0.0.0.0"") { //Serial.println(""No connection to NTP server!!!!!!!!""); } //Serial.print(""Local IP: ""); //Serial.println(WiFi.localIP()); WiFi.hostByName(ntpServerName, ntpServerIP); //Serial.print(ntpServerName); //Serial.print("": ""); //Serial.println(ntpServerIP); sendNTPpacket(ntpServerIP); uint32_t beginWait = millis(); while (millis() - beginWait < 1500) { int size = Udp.parsePacket(); if (size >= NTP_PACKET_SIZE) { //Serial.println(""Receive NTP Response""); Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer unsigned long secsSince1900; // convert four bytes starting at location 40 to a long integer secsSince1900 = (unsigned long)packetBuffer[40] << 24; secsSince1900 |= (unsigned long)packetBuffer[41] << 16; secsSince1900 |= (unsigned long)packetBuffer[42] << 8; secsSince1900 |= (unsigned long)packetBuffer[43]; return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR; } } //Serial.println(""No NTP Response :-(""); return 0; // return 0 if unable to get the time } // send an NTP request to the time server at the given address void sendNTPpacket(IPAddress &address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } String printDigits(int digits) { String tempstr = """"; // utility for digital clock display: prints preceding colon and leading 0 tempstr = "":""; if (digits < 10) tempstr = tempstr + '0'; tempstr = tempstr + String(digits); return tempstr; } String digitalClockDisplay() { String tmpstr = """"; // digital clock display of the time tmpstr = tmpstr + String(hour()); tmpstr = tmpstr + printDigits(minute()); tmpstr = tmpstr + printDigits(second()); tmpstr = tmpstr + ("" ""); tmpstr = tmpstr + String(day()); tmpstr = tmpstr + String("".""); tmpstr = tmpstr + String(month()); tmpstr = tmpstr + String("".""); tmpstr = tmpstr + String(year()); return tmpstr; }; void SetNextionDateTime() { String tmpstr = """"; char strText[20]; tmpstr = tmpstr + String(day()); tmpstr = tmpstr + String(""/""); tmpstr = tmpstr + String(month()); tmpstr = tmpstr + String(""/""); tmpstr = tmpstr + String(year()); tmpstr = tmpstr + ("" ""); tmpstr = tmpstr + String(hour()); tmpstr = tmpstr + printDigits(minute()); tmpstr = tmpstr + printDigits(second()); tmpstr.toCharArray(strText, 20); txt_Date.setText(strText); txt_MainTime.setText(strText); } /*---- Functions ----*/ void CheckThermo() { int RelayStatus = 0; Serial.println(""----------- Checking -------------""); Serial.println(digitalClockDisplay()); GetRoomTemp(); txtRoomTemp.setValue(RoomTem); SetTemp = txtSetTemp.getValue(); ThermStatus = varOnOff.getValue(); RelayStatus = digitalRead(RelayPin); if (ThermStatus){ //Thermostat is On if (RoomTem < SetTemp){ if (RelayStatus == LOW){ //Heat is off, open relay and set heat on SetRelay(RelayPin, HIGH); } } else{ if (RelayStatus == HIGH){ //Heat is on, close relay and set heat off SetRelay(RelayPin, LOW); } } } else{ //Termostat is off, turn heat off just in case. SetRelay(RelayPin, LOW); } Cayenne.celsiusWrite(0, RoomTem); Cayenne.celsiusWrite(1, SetTemp); } String SpanishTest() { String strSPTest = """"; strSPTest = strSPTest + ""El termostato se a encendido.""; strSPTest = strSPTest + ""el termostato se ha apagado.""; strSPTest = strSPTest + "".""; strSPTest = strSPTest + "".""; //strSPTest = strSPTest + "".""; return strSPTest; } void SetDefaultsStartup() { nex.sendCommand(""vis pBooting,0""); varBooting.setValue(0); nex.sendCommand(""vis pRunning,0""); varRunning.setValue(0); txtRoomTemp.setValue(-1); txtSetTemp.setValue(-1); ThermStatus = false; varOnOff.setValue(0); Alarm.delay(2000); nex.sendCommand(""vis pBooting,1""); varBooting.setValue(1); txtSetTemp.setForegroundColour(ThermoOff); txtSetTemp.setValue(SetTemp); nex.sendCommand(""vis pRedOff,1""); nex.sendCommand(""vis pBlueOn,0""); txt_Diga.setText(""Booting""); } void SetRelay(int RPin, int RelayState) { pinMode(RPin, OUTPUT); digitalWrite(RPin, RelayState); }; String ThermoStatus() { if (ThermStatus) { return ""On""; } else { return ""Off""; } } String Diagnostics() { String strDiag = ""Diagnostic is complete. ""; strDiag = strDiag + ""Thermostat status is "" + ThermoStatus() + "". ""; strDiag = strDiag + ""Room temperature is "" + String(RoomTem) + "" degrees"" + "". ""; //strDiag = strDiag + ""External temperature is "" + String(ExTemp) + "" degrees"" + "". ""; strDiag = strDiag + ""Thermostat is set to "" + String(SetTemp) + "" degrees"" + "". ""; strDiag = strDiag + ""Thermostat current date is "" + MonthNames[month()] + "" "" + String(day()) + "" and the current time is "" + String(hour()) + printDigits(minute()) + "". ""; strDiag = strDiag + ""S S I D is "" + WiFi.SSID() + "".""; strDiag = strDiag + ""Local I P is "" + IP2String(WiFi.localIP()) + "" .""; strDiag = strDiag + ""The thermostat has been operational for "" + GetUpTime(true); + "".""; return strDiag; } void NextionDiag(NextionText txtObj) { char strText[250]; String tempS = """"; tempS.toCharArray(strText, 250); txtObj.setText(strText); Alarm.delay(500); Serial.println(""Diagnostic screen open""); tempS = ""Thermostat status: "" + ThermoStatus() + "".\\\\r""; tempS.toCharArray(strText, 250); txtObj.setText(strText); tempS = tempS + ""Room temperature: "" + String(RoomTem) + ""C"" + "".\\\\r""; tempS.toCharArray(strText, 250); txtObj.setText(strText); tempS = tempS + ""Heat index: "" + String(HeatIndex) + ""C"" + "".\\\\r""; tempS.toCharArray(strText, 250); txtObj.setText(strText); tempS = tempS + ""Thermostat set: "" + String(SetTemp) + ""C"" + "".\\\\r""; tempS.toCharArray(strText, 250); txtObj.setText(strText); tempS = tempS + ""Date: "" + MonthNames[month()] + "" "" + String(day()) + "".\\\\r""; tempS.toCharArray(strText, 250); txtObj.setText(strText) ; tempS = tempS + ""Time: "" + String(hour()) + printDigits(minute()) + "".\\\\r""; tempS.toCharArray(strText, 250); txtObj.setText(strText); tempS = tempS + ""Uptime: "" + GetUpTime(false) + "".\\\\r""; tempS.toCharArray(strText, 250); txtObj.setText(strText); tempS = tempS + ""Alexa: "" + GetAlexaTime(false) + "".\\\\r""; tempS.toCharArray(strText, 250); txtObj.setText(strText); } void SystemScreen() { char strText[25]; String tempS = """"; float fTemp; Serial.println(""Systems screen open""); tempS = ESP.getSdkVersion(); tempS.toCharArray(strText, 25); txt_SDK.setText(strText); tempS = ESP.getCpuFreqMHz(); tempS = tempS + ""Mhz""; tempS.toCharArray(strText, 25); txt_CPU.setText(strText); fTemp = ESP.getSketchSize() / 1024.0; tempS = String(fTemp) + ""MB""; tempS.toCharArray(strText, 25); txt_Size.setText(strText); fTemp = ESP.getVcc() / 1000.0; tempS = String(fTemp) + ""DCV""; tempS.toCharArray(strText, 25); txt_ADC.setText(strText); tempS = ESP.getCoreVersion(); tempS.toCharArray(strText, 25); txt_Core.setText(strText); tempS = GetUpTime(false); tempS.toCharArray(strText, 25); txt_Uptime.setText(strText); } String GetUpTime(bool isText) { String strTemp = """"; int seconds = now() - bootTime; int days = seconds / 86400; seconds %= 86400; byte hours = seconds / 3600; seconds %= 3600; byte minutes = seconds / 60; seconds %= 60; if (isText) { strTemp = String(days) + "" days, "" + String(hours) + "" hours, "" + String(minutes) + "" minutes and "" + String(seconds) + "" seconds since last system reboot.""; } else { strTemp = String(days) + ""D "" + String(hours) + ""H "" + String(minutes) + ""M "" + String(seconds) + ""S""; } return strTemp; } String GetAlexaTime(bool isText) { String strTemp = """"; if (AlexaTime == 0) { if (isText) { strTemp = ""has not been accessed since last system reboot.""; } else { strTemp = ""No access requested.""; } } else { int seconds = now() - AlexaTime; int days = seconds / 86400; seconds %= 86400; byte hours = seconds / 3600; seconds %= 3600; byte minutes = seconds / 60; seconds %= 60; if (isText) { strTemp = String(days) + "" days, "" + String(hours) + "" hours, "" + String(minutes) + "" minutes and "" + String(seconds) + "" seconds since last Alexa access..""; } else { strTemp = String(days) + ""D "" + String(hours) + ""H "" + String(minutes) + ""M "" + String(seconds) + ""S""; } } return strTemp; } void GetRoomTemp() { /* 1- Get Room Temp form DHT11 Sensor. -Get Temp value in C -Get Hum value in % -Get Heat Index in C */ float fTemp = 0; fTemp = dht.readTemperature(); RoomTem = fTemp; RoomHum = dht.readHumidity(); HeatIndex = dht.computeHeatIndex(RoomTem, RoomHum, false); if (isnan(RoomHum) || isnan(RoomTem)) { RoomTem = dht.readTemperature(); RoomHum = dht.readHumidity(); HeatIndex = dht.computeHeatIndex(RoomTem, RoomHum, false); } } void RebootESP() { ESP.restart(); } char * IP2String(IPAddress IPString) { byte oct1 = IPString[0]; byte oct2 = IPString[1]; byte oct3 = IPString[2]; byte oct4 = IPString[3]; sprintf(chaTemp, ""%d.%d.%d.%d"", oct1, oct2, oct3, oct4); return chaTemp; } String mac2String(byte ar[]) { String s; for (byte i = 0; i < 6; ++i) { char buf[3]; sprintf(buf, ""%2X"", ar[i]); s += buf; if (i < 5) s += ':'; } s.replace("" "", ""0""); return s; } void GetNetworkData() { //Serial.println(""----------- setting Nextion Network screen data""); char bla[25]; char bla3[25]; WiFi.SSID().toCharArray(bla, 25); varLocalIP.setText(IP2String(WiFi.localIP())); Alarm.delay(50); varSSID.setText(bla); long rssi = WiFi.RSSI(); String(rssi).toCharArray(bla3, 25); varHost.setText(bla3); varGateway.setText(IP2String(WiFi.gatewayIP())); byte bla2[6]; WiFi.macAddress(bla2); mac2String(bla2).toCharArray(bla3, 25); varMAC.setText(bla3); } void configModeCallback (WiFiManager * myWiFiManager) { Serial.println(""Entered config mode""); Serial.println(WiFi.softAPIP()); //if you used auto generated SSID, print it Serial.println(myWiFiManager->getConfigPortalSSID()); } void setup() { PowerOnLED(OnLED,LOW); Serial.begin(115200); //Start Serial debugger Serial.println(""1....""); /*---- Nextion Init ---- 1*/ Alarm.delay(250); Serial.println(""1....""); nextionSerial.begin(9600); //Start Nextion Serial Serial.println(""2....""); Alarm.delay(50); Serial.println(""3....""); nex.init(); //Start Nextion Serial.println(""4....""); dht.begin(); //Start Temp Sensor Serial.println(""5....""); /*---- Nextion Init ---- 2*/ Serial.println(sp_Up.attachCallback(&callback)); Serial.println(sp_Down.attachCallback(&callback)); Serial.println(hs_OnOff.attachCallback(&OnOffCallback)); Serial.println(hs_reset.attachCallback(&HS_Reset)); Serial.println(hs_Diagnostics0.attachCallback(&OpenDiagScreen)); Serial.println(hs_Diagnostics1.attachCallback(&OpenDiagScreen)); Serial.println(hs_Diagnostics3.attachCallback(&OpenDiagScreen)); Serial.println(hs_Systems0.attachCallback(&OpenSystemsScreen)); Serial.println(hs_Systems1.attachCallback(&OpenSystemsScreen)); Serial.println(hs_Systems2.attachCallback(&OpenSystemsScreen)); SetDefaultsStartup(); /*---- WiFi Init ----*/ WiFiManager wifiManager; wifiManager.autoConnect(""AutoConnectAP""); Serial.println(""WiFi....""); Cayenne.begin(username, password, clientID); /*---- NPT Init ----*/ static char respBuf[4096]; Udp.begin(localPort); Serial.println(""waiting for sync""); setSyncProvider(getNtpTime); //Get Local Date/Time setSyncInterval(14400); setTime(hour(), minute(), second(), day(), month(), year()); //Set Local Date/Time to Alarm lib Serial.println(""Time set....""); bootTime = now(); Serial.println(digitalClockDisplay()); /*---- WUnderground Init ----*/ //GetWUnderground(); //Serial.println(""Weather Underground....""); GetNetworkData(); Serial.println(""Network Data....""); /*---- WebServer Init ----*/ server.on(""/"", handle_root); server.on(""/SpanishTest"", []() { // if you add this subdirectory to your webserver call, you get text below :) webString = SpanishTest(); AlexaTime = now(); server.send(200, ""text/plain"", webString); // send to someones browser when asked }); server.on(""/on"", []() { // if you add this subdirectory to your webserver call, you get text below :) TurnOn(); AlexaTime = now(); webString = ""The thermostat has been turned on""; server.send(200, ""text/plain"", webString); // send to someones browser when asked CheckThermo(); }); server.on(""/off"", []() { // if you add this subdirectory to your webserver call, you get text below :) TurnOff(); AlexaTime = now(); webString = ""The thermostat has been turned off""; server.send(200, ""text/plain"", webString); // send to someones browser when asked CheckThermo(); }); server.on(""/RoomTemp"", []() { // if you add this subdirectory to your webserver call, you get text below :) AlexaTime = now(); webString = ""The room temperature is "" + String(RoomTem) + "" degrees and the thermostat is set to "" + String(SetTemp) + "".""; server.send(200, ""text/plain"", webString); // send to someones browser when asked CheckThermo(); }); server.on(""/SetTempSet"", []() { // if you add this subdirectory to your webserver call, you get text below :) SetTemp = server.arg(0).toInt(); AlexaTime = now(); txtSetTemp.setValue(SetTemp); CheckThermo(); webString = ""The temperature has been changed to "" + String(SetTemp) + "" degrees.""; server.send(200, ""text/plain"", webString); // send to someones browser when asked }); server.on(""/GetThermostatSeting"", []() { // if you add this subdirectory to your webserver call, you get text below :) AlexaTime = now(); webString = ""The room temperature is "" + String(RoomTem) + "" degrees and the thermostat is set to "" + String(SetTemp) + "" degrees"" ; server.send(200, ""text/plain"", webString); // send to someones browser when asked CheckThermo(); }); server.on(""/Diag"", []() { // if you add this subdirectory to your webserver call, you get text below :) webString = """" ; AlexaTime = now(); webString = Diagnostics(); server.send(200, ""text/plain"", webString); // send to someones browser when asked }); server.on(""/uptime"", []() { // if you add this subdirectory to your webserver call, you get text below :) AlexaTime = now(); webString = ""The thermostat has been operational for "" + GetUpTime(true); server.send(200, ""text/plain"", webString); // send to someones browser when asked }); server.begin(); Serial.println(""HTTP server started""); /*---- Alarm/Repeat Init ----*/ Alarm.timerRepeat(30, CheckThermo); Alarm.timerRepeat(1, SetNextionDateTime); //Alarm.timerRepeat(300,GetWUnderground); //Alarm.timerRepeat(86400,RebootESP); nex.sendCommand(""vis pBooting,0""); Alarm.delay(50); nex.sendCommand(""vis pRunning,1""); CheckThermo(); varRunning.setValue(1); Alarm.delay(50); Serial.println(""Setup complete""); PowerOnLED(OnLED,HIGH); } void loop() { Alarm.delay(50); server.handleClient(); Alarm.delay(50); nex.poll(); } ",8158,False,1405.417067160447,median " /* Web client This sketch connects to a website (http://www.google.com) using an Arduino Wiznet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 created 18 Dec 2009 by David A. Mellis modified 9 Apr 2012 by Tom Igoe, based on work by Adrian McEwen Update 4 December 2015 hgroover - added temp / humidity sensor and switched to 4-position relay */ #include ""math.h"" #include #include #include #include #define VERSION_STR ""1.0.6b"" // Offset from UTC to local standard time in seconds (e.g. Los Angeles is -8 hours or -28800 seconds; New Delhi, 19800 // No DST - plants don't care about civic time const long utcOffset = -28800; // Do we have ethernet? #define HAS_ETHERNET 1 // Do we have CT connections? Set to number on analog pins 2-5 #define HAS_CURRENT_SENSOR 0 // Do we have a switch / button? #define HAS_BUTTON 0 // 5 minutes in seconds #define DUTY_CYCLE 300 #define WITH_TEST 0 dht11 DHT11; const int buttonPin = 2; // the number of the pushbutton pin const int ledPin = 13; // blinkenlights const int temperaturePinShort = A0; // Number of analog thermistor pin on short lead const int temperaturePinLong = A1; // Long lead int relayPin1 = 7; // IN1 connected to digital pin 7 int relayPin2 = 8; // IN2 connected to digital pin 8 int relayPin3 = 9; int relayPin4 = 6; int dhtPin = 3; int heater1On = 10; // Heater 1 on when below this temperature int heater1Off = 11; // Heater 1 off when above this temperature int heater2On = 9; // Heater 2 on when below this temperature int heater2Off = 10; // Heater 2 off when above this temperature int pins[] = { 7, 8, 9, 6 }; //const int currentPin = A1; // Analog pin connected to CT circuit // variables will change: int buttonState = 0; // variable for reading the pushbutton status int lastButtonState = 0; int relay1State = 0; // 0 = open // Get request int getRequested = 0; int starting = 1; unsigned long lastBlink; int blinkState = LOW; unsigned long lastRequest = 0; unsigned long lastChange = 0; unsigned long lastFlipFlop = 0; // Request rate in ms unsigned long requestRate = 30 * 1000; // Blink rate data #define blinkOffNormal 3500 #define blinkOnNormal 1500 #define blinkOffError 500 #define blinkOnError 2000 int blinkOff = blinkOffNormal; // ms off for normal int blinkOn = blinkOnNormal; // ms on for normal // Serialize requests unsigned long requestSerial = 1; // Measure last 3 thermistor readings to determine validity float lastTemp[3]; float lastTemp2[3]; int lastDHT[3]; int lastHum[3]; int lastTempIdx = 0; int lastTemp2Idx = 0; int lastDHTIdx = 0; int hasTherm1 = 0; int hasTherm2 = 0; int hasDHT = 0; int hms_hour = 0; int hms_minute = 0; int hms_second = 0; double outsideTemp = 0; double waterTemp = 0; int insideTemp = 0; int humidity = 0; int simulate = 0; // Values managed by loop_time() unsigned long time_last_millis = 0; unsigned long time_cur_millis ; // Set in loop_ntp() - time_utc_sec / time_utc_ms is in seconds, time_utc_millis is millis() at time of last adjustment unsigned long time_utc_sec = 0; unsigned long time_utc_ms = 0; unsigned long time_utc_millis = 0; // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; unsigned int localPort = 8888; // local port to listen for UDP packets //char timeServer[] = ""pool.ntp.org""; // time.nist.gov NTP server char timeServer[] = ""192.168.1.1""; // was 1.12 byte staticIP[] = {192,168,1,20}; const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets // A UDP instance to let us send and receive packets over UDP EthernetUDP Udp; // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): EthernetClient client; // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); int hasNet = 0; int relayTestState = 0; unsigned long ntpState = 0; // 4.91 if input is USB power (5V) // 5.0 if using recommended 12V input power float vcc = 5.0; // only used for display purposes, if used // set to the measured Vcc. float pad = 9850; // balance/pad resistor value, set this to // the measured resistance of your pad resistor //float thermr = 4700; //10000; // thermistor nominal resistance // Sample data at 5-minute interval for last 24 hours (60/5 * 24) // Not enough SRAM - try 6 hours at 15 minutes #define SAMPLE_SET 24 #define SAMPLE_INTERVAL 15 #define SAMPLE_INTERVAL_SEC (SAMPLE_INTERVAL*60) // With the paltry 2k of SRAM available on the Uno, // we can't do this. int insideHist[SAMPLE_SET] = {0}; int outsideHist[SAMPLE_SET] = {0}; int humidHist[SAMPLE_SET] = {0}; int waterHist[SAMPLE_SET] = {0}; byte settingHist[SAMPLE_SET] = {0}; int sampleHead = 0; int sampleTail = 0; // 0 = auto off; 1 = auto on; 2 = manual off; 3 = manual on byte relaySetting[4] = {2,3,0,0}; // Time of last relay change as utc seconds unsigned long lastRelayChange[4] = { 0,0,0,0 }; // manufacturer data for episco k164 10k thermistor // simply delete this if you don't need it // or use this idea to define your own thermistors #define EPISCO_K164_10k 4300.0f,298.15f,10000.0f // B,T0,R0 #define EPCOS_100k 4066.0f,298.15f,100000.0f // B,T0,R0 #define EPCOS_4_7k 4300.0f,298.15f,4700.0f // B,T0,R0 #define CURRENT_THERMISTOR EPCOS_4_7k //#define CURRENT_THERMISTOR EPCOS_4_7k // Temperature function outputs float , the actual // temperature // Temperature function inputs // 1.AnalogInputNumber - analog input to read from // 2.OuputUnit - output in celsius, kelvin or fahrenheit // 3.Thermistor B parameter - found in datasheet // 4.Manufacturer T0 parameter - found in datasheet (kelvin) // 5. Manufacturer R0 parameter - found in datasheet (ohms) // 6. Your balance resistor resistance in ohms float Temperature(int AnalogInputNumber,/*int OutputUnit,*/float B,float T0,float R0,float R_Balance) { float R,T; int tempADC = analogRead(AnalogInputNumber); //Serial.println( ""TempADC="" + String(tempADC) + "" R0="" + String(int(R0)) ); R=1024.0f*R_Balance/float(tempADC)-R_Balance; T=1.0f/(1.0f/T0+(1.0f/B)*log(R/R0)); // switch(OutputUnit) { // case T_CELSIUS : T-=273.15f; // break; // case T_FAHRENHEIT : // T=9.0f*(T-273.15f)/5.0f+32.0f; // break; // default: // break; // }; return T; } void printDouble(double val, byte precision) { // prints val with number of decimal places determine by precision // precision is a number from 0 to 6 indicating the desired decimal places // example: printDouble(3.1415, 2); // prints 3.14 (two decimal places) Serial.print (int(val)); //prints the int part if( precision > 0) { Serial.print("".""); // print the decimal point unsigned long frac, mult = 1; byte padding = precision -1; while(precision--) mult *=10; if(val >= 0) frac = (val - int(val)) * mult; else frac = (int(val) - val) * mult; unsigned long frac1 = frac; while(frac1 /= 10) padding--; while(padding--) Serial.print(""0""); Serial.print(frac,DEC) ; } } void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } pinMode(buttonPin, INPUT); // Digital pinMode(ledPin, OUTPUT); pinMode(relayPin1, OUTPUT); // sets the digital pin as output pinMode(relayPin2, OUTPUT); // sets the digital pin as output pinMode(relayPin3, OUTPUT); // sets the digital pin as output pinMode(relayPin4, OUTPUT); // sets the digital pin as output digitalWrite(relayPin1, HIGH); // Prevents relays from starting up engaged digitalWrite(relayPin2, HIGH); // Prevents relays from starting up engaged digitalWrite(relayPin3, HIGH); // Prevents relays from starting up engaged digitalWrite(relayPin4, HIGH); // Prevents relays from starting up engaged //pinMode(temperaturePin, INPUT); digitalWrite(ledPin, blinkState); lastBlink = millis(); Serial.println( ""Greenhouse mgr v"" VERSION_STR ); //Serial.println( ""Local times are in non-civic standard time (no DST adjustment)"" ); int checkDHT = DHT11.read(dhtPin); if (checkDHT == DHTLIB_OK) { Serial.println( ""Has DHT11"" ); lastDHT[lastDHTIdx] = -70; hasDHT = 1; } else { Serial.println( ""DHT11 not detected"" ); } // start the Ethernet connection; omit static IP to use DHCP //if (Ethernet.begin(mac, staticIP) == 0) { // Serial.println(""Eth fail""); //} //else Ethernet.begin(mac, staticIP); heater1On = 0; if (1) { hasNet = 1; server.begin(); // print your local IP address: printIPAddress(); Udp.begin(localPort); //relayTestState = 1; } } String hms( unsigned long ts ) { String r; hms_hour = (ts % 86400L) / 3600; r = String(hms_hour); // print the hour (86400 equals secs per day) r += ':'; hms_minute = (ts % 3600) / 60; if (hms_minute < 10) { // In the first 10 minutes of each hour, we'll want a leading '0' r += '0'; } r += String(hms_minute); // print the minute (3600 equals secs per minute) r += ':'; hms_second = (ts % 60); if (hms_second < 10) { // In the first 10 seconds of each minute, we'll want a leading '0' r += '0'; } r += String(hms_second); // print the second return r; } #if WITH_TEST int loop_relaytest() { if (relayTestState != 0) { switch (relayTestState) { case 1: delay( 5000 ); Serial.println( ""Starting relay test"" ); digitalWrite( relayPin1, LOW ); Serial.println( ""Turning on AC1"" ); delay( 2000 ); digitalWrite( relayPin1, HIGH ); delay( 5000 ); relayTestState = 2; break; case 2: digitalWrite( relayPin2, LOW ); Serial.println( ""Turning on AC2"" ); delay( 2000 ); digitalWrite( relayPin2, HIGH ); delay( 5000 ); relayTestState = 3; break; case 3: digitalWrite( relayPin3, LOW ); Serial.println( ""Turning on SP1"" ); delay( 2000 ); digitalWrite( relayPin3, HIGH ); delay( 5000 ); relayTestState = 4; break; case 4: digitalWrite( relayPin4, LOW ); Serial.println(""Turning on SP2"" ); delay( 2000 ); digitalWrite( relayPin4, HIGH ); delay( 5000 ); relayTestState = 0; break; } return 1; } return 0; } // loop_relaytest() #endif int loop_ntp() { if (ntpState == 0) { sendNTPpacket(timeServer); // send an NTP packet to a time server ntpState = millis(); // wait to see if a reply is available delay(2000); if (Udp.parsePacket()) { //Serial.println(""Got udp response from ntp request""); // We've received a packet, read the data from it Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer // the timestamp starts at byte 40 of the received packet and is four bytes, // or two words, long. First, extract the two words: unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): unsigned long secsSince1900 = highWord << 16 | lowWord; //Serial.print(""epoch1900 = ""); //Serial.println(secsSince1900); // now convert NTP time into everyday time: Serial.print(""Unix time = ""); // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: const unsigned long seventyYears = 2208988800UL; // subtract seventy years: unsigned long epoch = secsSince1900 - seventyYears; time_utc_sec = epoch; time_utc_millis = millis(); time_utc_ms = time_utc_millis % 1000; // print Unix time: Serial.println(epoch); // print the hour, minute and second: //Serial.println(""The UTC time is "" + hms(epoch)); // UTC is the time at Greenwich Meridian (GMT) /*** Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) Serial.print(':'); if (((epoch % 3600) / 60) < 10) { // In the first 10 minutes of each hour, we'll want a leading '0' Serial.print('0'); } Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) Serial.print(':'); if ((epoch % 60) < 10) { // In the first 10 seconds of each minute, we'll want a leading '0' Serial.print('0'); } Serial.println(epoch % 60); // print the second ***/ //Serial.println(""Local non-civic time is "" + hms(epoch+utcOffset) ); } //else Serial.println(""No NTP response""); } return 0; } // loop_ntp() int loop_dhcp() { if (!hasNet) return 0; switch (Ethernet.maintain()) { case 1: //renewed fail Serial.println(""E-RNWFAIL""); break; case 2: //renewed success Serial.println(""RNWOK""); //print your local IP address: printIPAddress(); break; case 3: //rebind fail Serial.println(""E-RBND""); break; case 4: //rebind success Serial.println(""RBNDOK""); //print your local IP address: printIPAddress(); break; default: //nothing happened break; } return 0; } // loop_dhcp() int loop_webserver() { EthernetClient client = server.available(); if (!client) return 0; //Serial.println(""new client""); // an http request ends with a blank line boolean currentLineIsBlank = true; String curLine; while (client.connected()) { if (client.available()) { char c = client.read(); //Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\\n' && currentLineIsBlank) { // send a standard http response header client.println(""HTTP/1.1 200 OK""); client.println(""Content-Type: text/html""); client.println(""Connection: close""); // the connection will be closed after completion of the response client.println(""Refresh: 30; url=/?r="" + String(time_utc_sec)); // refresh the page automatically every 30 sec client.println(); client.println(""""); client.println(""""); // output the value of each analog input pin /*** for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); client.print(""analog input ""); client.print(analogChannel); client.print("" is ""); client.print(sensorReading); client.println(""
    ""); } ****/ unsigned long curMillis = millis(); client.println( ""
    GHmgr v"" VERSION_STR "" "" + hms(time_utc_sec + utcOffset) + "" "" + SecondsPlusMS(time_utc_sec, time_utc_ms) + "" "" + SecondsPlusMS(ntpState/1000, ntpState%1000) + "" "" + SecondsPlusMS(curMillis/1000, curMillis%1000) + ""
    "" ); client.println( ""
    Current
    "" ); client.print( ""

    In: ""); client.print( lastDHT[lastDHTIdx] ); client.print( "" h1{"" + String(heater1On) + "","" + String(heater1Off) + ""} h2{"" + String(heater2On)+"",""+String(heater2Off)+""}""); client.print( ""

    Hum: ""); client.print( lastHum[lastDHTIdx] ); client.println( ""

    "" ); if (hasTherm1) { client.print( ""

    Out: "" ); client.print( outsideTemp ); client.println( ""

    "" ); } if (hasTherm2) { client.print( ""

    Water: "" ); client.print( waterTemp ); client.println( ""

    "" ); } client.println( ""

    Relays: "" + String(relaySetting[0]) + "","" + String(relaySetting[1]) + "","" + String(relaySetting[2]) + "","" + String(relaySetting[3]) + ""

    ""); client.println( ""
    History "" + String(SAMPLE_INTERVAL) + ""
    "" ); dumpHist( &client, ""In"", insideHist ); dumpHist( &client, ""Out"", outsideHist ); dumpHist( &client, ""Water"", waterHist ); dumpHist( &client, ""Hum"", humidHist ); dumpRelayHist( &client, settingHist ); client.println(""""); break; } if (c == '\\n') { // you're starting a new line currentLineIsBlank = true; if (curLine.startsWith(""GET /"")) { curLine = curLine.substring(4); int spaceSep = curLine.indexOf(' '); if (spaceSep > 0) curLine = curLine.substring(0,spaceSep); Serial.println( ""Got: "" + curLine ); // Handle /off=n, /on=n, /auto=n int arg = 0; int argSep = curLine.indexOf('='); if (argSep > 0) { arg = curLine.substring(argSep+1).toInt(); { curLine = curLine.substring(1,argSep); //Serial.println( ""Cmd: ["" + curLine + ""]"" ); if (curLine == ""on"" && arg > 0 && arg <= 4) { digitalWrite(pins[arg-1], LOW); relaySetting[arg-1] = 3; } else if (curLine == ""off"" && arg > 0 && arg <= 4) { digitalWrite(pins[arg-1], HIGH); relaySetting[arg-1] = 2; } else if (curLine == ""auto"" && arg > 0 && arg <= 4) { digitalWrite(pins[arg-1], HIGH); relaySetting[arg-1] = 0; } else if (curLine == ""sim"") { simulate = arg; } else if (curLine == ""h1on"") { heater1On = arg; } else if (curLine == ""h1off"") { heater1Off = arg; } else if (curLine == ""h2on"") { heater2On = arg; } else if (curLine == ""h2off"") { heater2Off = arg; } //else Serial.println(""n/r""); } } } curLine = """"; } else if (c != '\\r') { // you've gotten a character on the current line currentLineIsBlank = false; curLine += c; } } // client available } // while connected // give the web browser time to receive the data delay(1); // close the connection: client.stop(); //Serial.println(""client disconnected""); Ethernet.maintain(); return 0; } // loop_webserver() int loop_sample() { // Check for alarm conditions double Temp = Temperature(A0, CURRENT_THERMISTOR, 10000.0f); double Temp2 = Temperature(A1, CURRENT_THERMISTOR, 10000.0f); #if HAS_BUTTON // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); if (buttonState != lastButtonState) { // Door opened? if (buttonState == LOW && getRequested == 0) getRequested = 1; lastButtonState = buttonState; } #endif if (DHT11.read(dhtPin) == DHTLIB_OK) { insideTemp = DHT11.temperature; if (DHT11.temperature != lastDHT[lastDHTIdx] || DHT11.humidity != lastHum[lastDHTIdx]) { //Serial.print(""Humidity: ""); //Serial.print(DHT11.humidity); //Serial.print( ""% Temp(C): ""); //Serial.println(DHT11.temperature); lastDHTIdx = (lastDHTIdx + 1) % 3; lastDHT[lastDHTIdx] = DHT11.temperature; lastHum[lastDHTIdx] = DHT11.humidity; } } if (simulate) { insideTemp = simulate; } else { insideTemp = lastDHT[lastDHTIdx]; } humidity = lastHum[lastDHTIdx]; if (Temp < -30 || Temp > 80) { hasTherm1 = 0; } else { hasTherm1 = 1; outsideTemp = Temp; } if (Temp2 < -30 || Temp2 > 80) { hasTherm2 = 0; } else { hasTherm2 = 1; waterTemp = Temp2; } return 0; } // loop_sample() int loop_led() { if (insideTemp >= 32.0) { //if (blinkOn != blinkOnError) //{ // Serial.println( ""Temperature high: "" + String(int(Temp * 10)) ); //} blinkOn = blinkOnError; blinkOff = blinkOffError; } else if (blinkOn != blinkOnNormal) { //Serial.println( ""Temperature normal: "" + String(int(Temp * 10)) ); blinkOn = blinkOnNormal; blinkOff = blinkOffNormal; } unsigned long curTime = millis(); if (curTime < lastBlink || (blinkState == LOW && curTime - lastBlink >= blinkOff) || (blinkState == HIGH && curTime - lastBlink >= blinkOn)) { lastBlink = curTime; blinkState = (blinkState == HIGH) ? LOW : HIGH; //Serial.println(""Time="" + String(curTime) + "" state="" + String(blinkState) + "" temp="" + String(int(Temp*10)) + "" Temp2="" + String(int(Temp2*10))); digitalWrite(ledPin, blinkState); } return 0; } // loop_led() int loop_time() { time_cur_millis = millis(); long delta_since_last = time_cur_millis - time_utc_millis; if (time_cur_millis < time_last_millis || delta_since_last < 0) { // Force immediate resync - wrap in millis() occurs about once every 49.7 days ntpState = 0; return 0; } // Update no more than 1hz if (delta_since_last < 1000) { return 0; } time_utc_millis = time_cur_millis; time_utc_sec += (delta_since_last / 1000); time_utc_ms = time_cur_millis % 1000; return 0; } int loop_task() { long time_delta = time_utc_sec - lastChange; int n; // Minimum delta is 1s if (time_delta < 0) lastChange = time_utc_sec; // Handle time wrap if (time_delta < 1) return 0; setHeater( 0, heater1On, heater1Off ); setHeater( 1, heater2On, heater2Off ); hms(time_utc_sec + utcOffset); long decTime = hms_hour * 10000 + hms_minute * 100 + hms_second; timedValve( 2, decTime, 73000, 73100, 9 ); lastChange = time_utc_sec; // 1-minute // 5-minute if (time_utc_sec % DUTY_CYCLE== 0 && time_utc_sec != lastFlipFlop) { lastFlipFlop = time_utc_sec; for (n = 0; n < 2; n++) { if ((relaySetting[n] & 0x02) == 0) continue; relaySetting[n] ^= 0x01; if (relaySetting[n] & 0x01) { Serial.println( ""t="" + String(time_utc_sec) + "" r"" + String(n+1) + "" ON""); digitalWrite(pins[n], LOW); } else { Serial.println( ""t="" + String(time_utc_sec) + "" r"" + String(n+1) + "" off""); digitalWrite(pins[n], HIGH); } } } // 10-minute if (time_utc_sec % SAMPLE_INTERVAL_SEC == 0) { // Save history //Serial.println( ""Time:"" + String(time_utc_sec % 600) + "" "" + String(sampleHead)); insideHist[sampleHead] = insideTemp; outsideHist[sampleHead] = int(outsideTemp); humidHist[sampleHead] = humidity; settingHist[sampleHead] = relaySetting[0] | (relaySetting[1] << 2) | (relaySetting[2] << 4) | (relaySetting[3] << 6); waterHist[sampleHead] = int(waterTemp); sampleHead = (sampleHead + 1) % SAMPLE_SET; if (sampleHead == sampleTail) { sampleTail = (sampleTail + 1) % SAMPLE_SET; } } // 2 hour NTP adjustment - our crude method for time update produces around 12 minutes drift // per 24 hours if (time_utc_sec % 7200 == 0) { unsigned long curM = millis(); if (curM < ntpState || curM - ntpState >= 7200000) { ntpState = 0; } } return 0; } void loop() { #if WITH_TEST if (loop_relaytest()) return; #endif loop_ntp(); //loop_sample(); loop_time(); // Adjust relays @1hz, update history every 300s loop_task(); loop_led(); //loop_dhcp(); loop_webserver(); } // Set power relay for heater based on low (on) temp // and high (off) temp int setHeater( int index, int lowTemp, int highTemp ) { // Manual? if (relaySetting[index] & 0x02) return 0; // Enforce minimum quiet time of 10s before turning on and 30s before turning off if (insideTemp < lowTemp && relaySetting[index] == 0 && time_utc_sec - lastRelayChange[index] >= 10) { digitalWrite( pins[index], LOW ); Serial.println( ""H on "" + String(index+1) ); relaySetting[index] = 1; lastRelayChange[index] = time_utc_sec; return 1; } else if (insideTemp > highTemp && relaySetting[index] == 1 && time_utc_sec - lastRelayChange[index] >= 30) { digitalWrite( pins[index], HIGH ); Serial.println( ""H off "" + String(index+1) ); relaySetting[index] = 0; lastRelayChange[index] = time_utc_sec; return 1; } return 0; // no change } void printIPAddress() { Serial.print(""IP: ""); for (byte thisByte = 0; thisByte < 4; thisByte++) { // print the value of each byte of the IP address: Serial.print(Ethernet.localIP()[thisByte], DEC); Serial.print("".""); } Serial.println(); } // send an NTP request to the time server at the given address void sendNTPpacket(char* address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } void dumpHist( EthernetClient *pc, char *label, int *hist ) { int n; if (sampleHead == sampleTail) { pc->println( ""

    No history "" + String(label) + ""

    "" ); return; } pc->print( ""

    "" ); // ["" + String(sampleTail) + "","" + String(sampleHead) + ""] "" ); pc->print( label ); pc->print( "":"" ); for (n = sampleTail; n != sampleHead; n = (n + 1) % SAMPLE_SET) { pc->print( "" "" + String(hist[n]) ); } pc->println( ""

    "" ); } void dumpRelayHist( EthernetClient *pc, byte *hist ) { int n; if (sampleHead == sampleTail) return; pc->print( ""

    Relays: "" ); for (n = sampleTail; n != sampleHead; n = (n + 1) % SAMPLE_SET) { pc->print( "" "" + String(hist[n]) ); } pc->println( ""

    "" ); } int timedValve( int index, long decTime, long decTimeOn, long decTimeOff, int minTemp ) { // Manual? if (relaySetting[index] & 0x02) return 0; if (decTime < decTimeOn || decTime >= decTimeOff) { if (relaySetting[index]) { Serial.println(""Assert off "" + String(index)); relaySetting[index] = 0; digitalWrite( pins[index], HIGH ); return 1; } //Serial.println(""Not yet ""+String(decTime)); return 0; } if (decTime >= decTimeOn && relaySetting[index] == 0 && insideTemp >= minTemp) { Serial.println(""Assert on "" + String(index)); relaySetting[index] = 1; digitalWrite(pins[index], LOW); return 1; } //Serial.println(""Out of time "" + String(decTime)); return 0; } String SecondsPlusMS(unsigned long second_part, unsigned long ms_part ) { String r = String(second_part) + "".""; if (ms_part < 10) r += ""0""; if (ms_part < 100) r += ""0""; return r + String(ms_part); } ",8345,False,1442.3199613701943,median "// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // ""License""); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // = Using CDI to Inject OSGi Bundles as Services in IDE NetBeans :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: Using CDI to Inject OSGi Bundles as Services in IDE NetBeans - Apache NetBeans :keywords: Apache NetBeans, Tutorials, Using CDI to Inject OSGi Bundles as Services in IDE NetBeans This document demonstrates how the integrated support for the link:http://www.osgi.org/Main/HomePage[+Open Services Gateway Initiative+] (OSGi) framework in IDE NetBeans simplifies the process of creating OSGi bundles and using the bundles in your projects. В этом учебном курсе будут созданы два простых пакета OSGi из архетипа пакета OSGi Maven, затем они будут развернуты на сервере GlassFish Server Open Source Edition 3.1. После создания основных пакетов OSGi будет создано клиентское веб-приложение, а CDI использован для внедрения пакетов как служб. Затем веб-приложение будет развёрнуто как пакет на сервере. Далее в этом учебном курсе показано использование консоли администрирования OSGi для работы с пакетами OSGi. Применение пакета OSGi в приложении уровня предприятия позволяет увеличить модульность и гибкость по отношению к обновлению отдельных пакетов. Встроенная поддержка OSGi в сервере GlassFish делает внедрение пакетов в приложение очень простым. Этот учебный курс основан на записи в блоге link:http://blogs.oracle.com/arungupta/entry/totd_154_dynamic_osgi_services[+ TOTD #154: Dynamic OSGi services in GlassFish 3.1 - Using CDI and @OSGiService +] и других записях, которые можно найти в link:http://blog.arungupta.me/[+блоге Аруна Гупты+]. Блог также содержит много других интересных записей о работе с OSGi. Кроме того, следующие ресурсы содержат массу информации об использовании OSGi и CDI в гибридных приложениях. * link:http://weblogs.java.net/blog/2009/06/14/developing-hybrid-osgi-java-ee-applications-glassfish[+ Разработка гибридных (OSGi + Java EE) приложений в GlassFish+] * link:http://blogs.oracle.com/sivakumart/entry/typesafe_injection_of_dynamic_osgi[+ Корректное по отношению к типам внедрение динамических служб OSGi в гибридных приложениях Java EE +] * link:http://weblogs.java.net/blog/2009/06/04/osgi-enabled-web-applications-inglassfish[+Веб-приложения с использованием OSGi в GlassFish+] * link:http://www.youtube.com/watch?v=vaOpJJ-Xm70[+ Видео на YouTube: корректное по отношению к типам внедрение динамических служб OSGi при помощи GlassFish 3.1 и CDI+] * link:http://glassfish.java.net/public/GF-OSGi-Features.pdf[+ Разработка приложений OSGi с помощью GlassFish Server""+] *Упражнения по темам руководства* * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> *Для работы с этим учебным курсом требуется следующее программное обеспечение и ресурсы.* |=== |Программное обеспечение или материал |Требуемая версия |link:http://download.netbeans.org/netbeans/7.1/beta/[+IDE NetBeans+] |Версия 7.2, 7.3, 7.4, 8.0, Java EE |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Комплект для разработчика на языке Java (JDK)+] |версия 7 или 8 |GlassFish Server Open Source Edition 3.1.2.2 |3.1.x или 4.x |=== *Предпосылки* Предполагается, что читатель обладает базовыми знаниями по следующим технологиям или опытом программирования с их использованием: * Программирование на Java * IDE NetBeans * Платформа Maven Перед изучением этого учебного курса можно ознакомиться со следующей документацией: * link:http://wiki.netbeans.org/MavenBestPractices[+Испытанные приемы для Apache Maven в IDE NetBeans+] * link:http://books.sonatype.com/mvnref-book/reference/introduction.html[+Глава 1. Введение в Apache Maven+] (из книги link:http://books.sonatype.com/mvnref-book/reference/index.html[+Maven: The Complete Reference +]) * link:http://www.osgi.org/javadoc/r4v42/[+Платформа OSGi+] == Создание родительского проекта POM В этом разделе создается родительский проект POM для пакетов OSGi, которые создаются в данном учебном курсе. Файл POM проекта ( ``pom.xml`` ) изменяется для добавления элементов управления зависимостями, которые будут наследоваться дочерними проектами как зависимости. 1. Выберите 'Создать проект' (Ctrl-Shift-N; ⌘-Shift-N в Mac) в главном меню. 2. Выберите в категории ""Maven"" проект POM. image::images/cdi-newpomproject.png[title=""Архетип проекта Maven POM в мастере создания проектов""] . Введите *MavenOSGiCDIProject* в поле имени проекта. Нажмите кнопку ""Завершить"". После нажатия кнопки ""Готово"" среда IDE создает проект POM и открывает проект в окне ""Проекты"". . Разверните узел ""Файлы проекта"" в окне проектов и дважды щелкните файл ``pom.xml`` , чтобы открыть файл в редакторе. Базовый файл POM для проекта должен быть аналогичен следующему. [source,xml] ---- 4.0.0 com.mycompany MavenOSGiCDIProject 1.0-SNAPSHOT pom UTF-8 ---- . Измените родительский файл ``pom.xml`` , добавив следующие элементы. Сохраните изменения. [source,xml] ---- 4.0.0 com.mycompany MavenOSGiCDIProject 1.0-SNAPSHOT pom UTF-8 * org.osgi org.osgi.core 4.2.0 provided * ---- В этом упражнении был явно указан артефакт, используемый в этом проекте, и его версия. Используя управление зависимостями и указывая артефакты в родительском файле POM, можно сделать файлы POM в дочерних проектах проще и обеспечить соответствие версий зависимостей в проекте. Дополнительные сведения об использовании управления зависимостями приведены в документе link:http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html[+ Введении в механизм зависимостей+]. == Создание пакетных проектов OSGi Категория Maven в мастере создания проекта содержит архетип пакета OSGi для создания проектов пакетов OSGi. При создании проекта пакета OSGi в создаваемом файле POM архив JAR ``org.osgi.core`` объявляется зависимостью, и для сборки проекта выбирается подключаемый модуль ``maven-bundle-plugin`` . === Создание пакета интерфейса MavenHelloServiceApi В этом упражнении используется мастер создания проекта для создания пакетного проекта OSGi, который даст простой интерфейс, реализуемый другими пакетами. После создания пакета и интерфейса файл POM исправляется для обновления зависимости от артефакта ``org.osgi.core`` , указанного в родительском проекте файла POM. 1. Выберите в меню ""Файл"" пункт ""Новый проект"", чтобы открыть мастер создания проекта. 2. Выберите пакет OSGi из категории Maven. Нажмите кнопку ""Далее"". image::images/cdi-new-osgiproject.png[title=""Архетип набора Maven OSGi в мастере создания проектов""] . Введите в поле имени проекта *MavenHelloServiceApi*. . Нажмите кнопку ""Обзор"" и выберите в качестве расположения проект POM *MavenOSGiCDIProject*. Нажмите кнопку ""Завершить"". После нажатия кнопки ""Готово"" среда IDE создает проект и открывает его в окне проектов. Если открыть ``pom.xml`` для проекта MavenHelloServiceApi в редакторе, то вы увидите, что элемент ``packaging`` определяет ``bundle`` , и что ``maven-bundle-plugin`` будет использоваться при сборке пакета. [source,xml] ---- 4.0.0 MavenOSGiCDIProject com.mycompany 1.0-SNAPSHOT com.mycompany MavenHelloServiceApi 1.0-SNAPSHOT *bundle* MavenHelloServiceApi OSGi Bundle UTF-8 org.osgi org.osgi.core 4.3.0 provided org.apache.felix *maven-bundle-plugin* 2.3.7 true com.mycompany.mavenhelloserviceimpl.Activator ... ... ---- Также можно увидеть, что при создании проекта пакета OSGi с использованием архетипа пакета Maven OSGi среда IDE добавляет артефакт ``org.osgi.core`` в качестве зависимости по умолчанию. . Щелкните правой кнопкой мыши узел проекта MavenHelloServiceApi в окне проектов и выберите пункт ""Свойства"". . Выберите в диалоговом окне ""Свойства проекта"" категорию ""Исходные файлы"". . Укажите для параметра *Формат исходных/двоичных файлов* значение 1.6 и подтвердите, что *кодировка* — UTF-8. Нажмите кнопку ""ОК"". . Щелкните правой кнопкой мыши узел ""Исходные пакеты"" в окне проектов и выберите пункт ""Создать"" > ""Интерфейс Java"". . Введите в поле ""Имя класса *Hello*. . Выберите пакет *com.mycompany.mavenhelloserviceapi*. Нажмите кнопку ""Завершить"". . Добавьте следующий метод ``sayHello`` к интерфейсу (выделено жирным) и сохраните изменения. [source,java] ---- public interface Hello { *String sayHello(String name);* } ---- . Щелкните правой кнопкой мыши узел проекта в окне проектов и выберите ""Сборка"". После сборки проекта, если открыть окно ""Файлы"" и развернуть узел проекта, вы увидите, что файл ``MavenHelloServiceApi-1.0-SNAPSHOT.jar`` создан в папке ``target`` . image::images/cdi-manifest.png[title=""просмотреть содержимое скомпилированного файла JAR в окне 'Файлы'""] Подключаемый модуль ``maven-bundle-plugin`` обрабатывает создание файла ``MANIFEST.MF`` при сборке проекта. Если открыть файл ``MANIFEST.MF`` в скомпилированном файле JAR, можно увидеть, что модуль создал заголовок манифеста, который объявляет экспортные пакеты. Для OSGi все пакеты, которые нужно предоставить и сделать доступными для других пакетов, должны быть перечислены в элементе ``Export-Package`` в файле ``MANIFEST.MF`` . . Убедитесь, что файл ``MANIFEST.MF`` содержит элемент ``Export-Package`` (в приведенном ниже примере этот элемент выделен *жирным шрифтом*). [source,java] ---- Manifest-Version: 1.0 Bnd-LastModified: 1395049732676 Build-Jdk: 1.7.0_45 Built-By: nb Bundle-Activator: com.mycompany.mavenhelloserviceapi.Activator Bundle-ManifestVersion: 2 Bundle-Name: MavenHelloServiceApi OSGi Bundle Bundle-SymbolicName: com.mycompany.MavenHelloServiceApi Bundle-Version: 1.0.0.SNAPSHOT Created-By: Apache Maven Bundle Plugin *Export-Package: com.mycompany.mavenhelloserviceapi;uses:=""org.osgi.frame work"";version=""1.0.0.SNAPSHOT""* Import-Package: org.osgi.framework;version=""[1.6,2)"" Tool: Bnd-1.50.0 ---- Контейнер OSGi считывает заголовок манифеста ``Export-Package`` для определения доступных извне классов пакета. Например, в этом примере предоставляются классы пакета ``com.mycompany.mavenhelloserviceapi`` . NOTE: Если в файле ``MANIFEST.MF`` отсутствует элемент ``Export-Package`` , необходимо разрешить поведение по умолчанию для подключаемого модуля в окне 'Свойства проекта' и выполнить построение проекта повторно. В диалоговом окне 'Свойства проекта' выберите категорию 'Экспорт пакетов', затем выберите параметр *Поведение подключаемого модуля maven-bundle-plugin по умолчанию*. На панели 'Экспорт пакетов' в окне 'Свойства проекта' можно явно указать предоставляемые пакеты. Также можно указать пакеты непосредственно в файле ``pom.xml`` . === Создание пакета реализации MavenHelloServiceImpl В этом упражнении будет создан MavenHelloServiceImpl в проекте POM. 1. Выберите в меню ""Файл"" пункт ""Новый проект"", чтобы открыть мастер создания проекта. 2. Выберите пакет OSGi из категории Maven. Нажмите кнопку ""Далее"". 3. Введите строку *MavenHelloServiceImpl* в качестве имени проекта. 4. Нажмите кнопку ""Обзор"" и выберите в качестве расположения проект POM *MavenOSGiCDIProject* (если оно еще не выбрано). Нажмите кнопку ""Завершить"". 5. Щелкните правой кнопкой мыши узел проекта в окне ""Проекты"" и выберите команду ""Свойства"". 6. Выберите в диалоговом окне ""Свойства проекта"" категорию ""Исходные файлы"". 7. Укажите для параметра *Формат исходных/двоичных файлов* значение 1.6 и подтвердите, что *кодировка* — UTF-8. Нажмите кнопку ""ОК"". 8. Щелкните правой кнопкой мыши узел ""Исходные пакеты"" в окне ""Проекты"" и выберите пункт ""Создать"" > ""Класс Java"". 9. Введите значение *HelloImpl* в поле имени класса. 10. Выберите пункт *com.mycompany.mavenhelloserviceimpl* в поле ""Пакет"". Нажмите кнопку ""Завершить"". 11. Введите следующее (жирным шрифтом) и сохраните изменения. [source,java] ---- public class HelloImpl *implements Hello { public String sayHello(String name) { return ""Hello "" + name;* } } ---- При внедрении ``Hello`` среда IDE отобразит ошибку, которую необходимо разрешить добавлением проекта MavenHelloServiceApi в качестве зависимости. . Щелкните правой кнопкой мыши узел ""Зависимости"" в *MavenHelloServiceImpl* в окне проектов и выберите пункт ""Добавить зависимость"". . Щелкните вкладку ""Открытые проекты"" в диалоговом окне ""Добавить библиотеку"". . Выберите пакет OSGi MavenHelloServiceApi. Нажмите кнопку ""Add"". image::images/cdi-add-dependency.png[title=""Откройте вкладку "Проекты" в диалоговом окне "Добавить библиотеку".""] . Щелкните правой кнопкой мыши класс ``HelloImpl.java`` , открытый в редакторе и выберите 'Исправить выражения импорта' (Alt-Shift-I; ⌘-Shift-I в Mac), чтобы добавить оператор импорта для ``com.mycompany.mavenhelloserviceapi.Hello`` . Сохраните изменения. . Разверните пакет ``com.mycompany.mavenhelloserviceimpl`` и дважды щелкните ``Activator.java`` для открытия файла в редакторе. image::images/cdi-activator.png[title=""Класс 'Активатор' в окне 'Проекты'.""] Среда IDE автоматически создала класс активатора пакета ``Activator.java`` в вашем проекте. Активатор пакета используется для управления жизненным циклом пакета. Класс активатора пакета объявляется в файле ``MANIFEST.MF`` пакета и создается при запуске пакета контейнером. Класс активатора не является обязательным для пакета OSGi, но метод ``start()`` в классе активатора можно использовать, например, для инициализации служб или других нужных пакету ресурсов. В этом упражнении будут добавлены несколько строк кода в класс, который будет выводить сообщения в ""Окно вывода"". Это позволит определить, когда пакет запускается и останавливается. . Измените методы ``start()`` и ``stop()`` в классе активатора пакета, чтобы добавить следующие строки (выделено жирным). [source,java] ---- public class Activator implements BundleActivator { public void start(BundleContext context) throws Exception { *System.out.println(""HelloActivator::start""); context.registerService(Hello.class.getName(), new HelloImpl(), null); System.out.println(""HelloActivator::registration of Hello service successful"");* } public void stop(BundleContext context) throws Exception { *context.ungetService(context.getServiceReference(Hello.class.getName())); System.out.println(""HelloActivator stopped"");* } } ---- Класс активатора пакета импортирует ``org.osgi.framework.BundleActivator`` и ``org.osgi.framework.BundleContext`` . По умолчанию создаваемый класс содержит два метода: ``start()`` и ``stop()`` . Платформа OSGi вызывает методы ``start()`` и ``stop()`` для включения и отключения функциональных возможностей пакета. При запуске пакета, компонент службы пакета регистрируется в реестре служб OSGi. После регистрации пакета, остальные пакеты могут найти в реестре и использовать через контекст пакета активные службы. Если посмотреть на файл POM для проекта, то можно увидеть элемент ```` , который указывает активатор пакета в элементе настройки для ``maven-bundle-plugin`` . [source,xml] ---- org.apache.felix maven-bundle-plugin 2.3.7 true *com.mycompany.mavenhelloserviceimpl.Activator* ---- При сборке пакета подключаемый модуль создает заголовок манифеста в файле манифеста проекта в файле JAR и указывает класс активатора пакета. При развертывании пакета среда выполнения OSGi ищет в файле манифеста заголовок ``Bundle-Activator`` . . Исправьте операторы импорта в ``Activator.java`` для импорта ``com.mycompany.mavenhelloserviceapi.Hello`` . Сохраните изменения. . Разверните узел ""Зависимости"" и убедитесь, что артефакт ``org.osgi.core`` добавлен в список зависимостей. NOTE: Удалите все предыдущие версии артефакта в узле 'Зависимости'. Для этого щелкните артефакт правой кнопкой мыши и выберите 'Удалить зависимость'. Узел ""Зависимости"" должен содержать только проект MavenHelloServiceApi и артефакт ``org.osgi.core`` . image::images/cdi-implproject.png[title=""Класс 'Активатор' в окне 'Проекты'.""] === Сборка и развертывание пакетов OSGi В этом упражнении пакеты OSGi будут собраны и развернуты на сервере GlassFish. 1. Щелкните правой кнопкой мыши узел MavenOSGiCDIProject в окне ""Проекты"" и выберите пункт ""Очистить и собрать"". При сборке проекта среда IDE создает файлы JAR в папке ``target`` каждого из проектов, а также устанавливает снимок JAR в локальный репозиторий. В окне ""Файлы"" можно развернуть папку ``target`` для каждого из двух проектов пакетов чтобы увидеть два архива JAR ( ``MavenHelloServiceApi-1.0-SNAPSHOT.jar`` и ``MavenHelloServiceImpl-1.0-SNAPSHOT.jar`` ). . Запустите сервер GlassFish, если он еще не запущен. . Скопируйте ``MavenHelloServiceApi-1.0-SNAPSHOT.jar`` в каталог ``glassfish/domains/domain1/autodeploy/bundles/`` вашей установки GlassFish. Вы должны увидеть выходные данные, похожие на следующие данные журнала сервера GlassFish, в окне выходных данных. [source,java] ---- INFO: Started bundle: file:/glassfish-4.0/glassfish/domains/domain1/autodeploy/bundles/MavenHelloServiceApi-1.0-SNAPSHOT.jar ---- Щелкните правой кнопкой мыши узел сервера GlassFish в окне ""Службы"" и выберите пункт ""Просмотреть журнал сервера домена"", если журнал сервера не виден в окне вывода. . Повторите действия по копированию файла ``MavenHelloServiceImpl-1.0-SNAPSHOT.jar`` в каталог ``autodeploy/bundles`` . Теперь в журнале сервера GlassFish вы должны видеть примерно следующий результат. [source,java] ---- INFO: HelloActivator::start INFO: HelloActivator::registration of Hello service successful INFO: Started bundle: file:/glassfish-4.0/glassfish/domains/domain1/autodeploy/bundles/MavenHelloServiceImpl-1.0-SNAPSHOT.jar INFO: Started bundle: file:/glassfish-4.0/glassfish/domains/domain1/autodeploy/bundles/MavenHelloServiceImpl-1.0-SNAPSHOT.jar ---- В качестве альтернативы можно установить пакеты из консоли администрирования GlassFish OSGi. Дополнительные сведения приведены в разделе <>. == Создание клиентского веб-приложения В этом разделе показано создание веб-клиента Java EE, использующего службу пакета OSGi. Создается простой сервлет в веб-приложении, а затем внедряются объявленные службы. Перед созданием проекта в родительский проект POM добавляются некоторые элементы управления зависимостями. === Настройка зависимостей в родительском проекте POM В этом упражнении указываются элементы зависимости в родительском проекте POM. Кроме того, добавляется репозиторий для артефактов, который будет использоваться в проекте. . Разверните узел ""Файлы проекта"" в проекте *MavenOSGiCDIProject* в окне проектов и дважды щелкните файл ``pom.xml`` , чтобы открыть файл в редакторе. . Измените родительский файл ``pom.xml`` , добавив следующие элементы управления зависимостями (выделены жирным шрифтом). Сохраните изменения. [source,xml] ---- 4.0.0 com.mycompany MavenOSGiCDIProject 1.0-SNAPSHOT pom UTF-8 ... org.osgi org.osgi.core 4.3.0 provided * org.osgi org.osgi.compendium 4.2.0 provided org.glassfish osgi-cdi-api 3.1-b41 jar provided * ... ---- . Добавьте следующие элементы, чтобы добавить к POM репозиторий GlassFish. Сохраните изменения. [source,xml] ---- ... * glassfish-repo-archive Nexus repository collection for Glassfish http://maven.glassfish.org/content/groups/glassfish never * MavenHelloServiceApi MavenHelloServiceImpl ---- После добавления репозитория GlassFish в POM при просмотре списка репозиториев в узле 'Репозитории Maven' в окне 'Службы' вы увидите, что среда IDE автоматически добавила узел для репозитория GlassFish. По умолчанию среда IDE отображает узел для локального репозитория Maven. Когда в открытом проекте указан репозиторий, среда IDE автоматически добавляет узел репозитория под узлом 'Репозитории Maven'. image::images/cdi-maven-repositories.png[title=""Репозиторий GlassFish в окне 'Репозиториии Maven'""] В этом упражнении добавлены дополнительные артефакты и версии артефактов, которые будут использоваться в проекте. Кроме того, добавлен репозиторий GlassFish, содержащий артефакты ``osgi-cdi-api`` . === Создание веб-приложения MavenHelloWebClient Сначала создайте обычное веб-приложение, затем преобразуйте проект в комплект OSGi (комплект веб-приложения (WAB)). 1. В главном меню выберите ""Файл"" > ""Новый проект"". 2. Выберите в категории Maven пункт ""Веб-приложение"". Нажмите кнопку ""Далее"". 3. Введите *MavenHelloWebClient* в поле имени проекта. 4. Нажмите кнопку ""Обзор"" и выберите проект POM *MavenOSGiCDIProject* в качестве местоположения (если он еще не выбран). Нажмите кнопку ""Далее"". 5. В качестве сервера выберите сервер GlassFish, а в качестве версии Java EE укажите Java EE 6 Web или Java EE 7 Web. Нажмите кнопку ""Завершить"". 6. Щелкните правой кнопкой мыши узел проекта и выберите в меню ""Создать"" пункт ""Сервлет"". 7. Введите *HelloServlet* в поле имени класса. 8. В списке 'Пакет' выберите ``com.mycompany.mavenhellowebclient`` . Нажмите кнопку ""Завершить"". 9. Удалите созданные средой IDE методы по умолчанию ( ``processRequest`` , ``doGet`` , ``doPost`` , ``getServletInfo`` ). NOTE: Потребуется расширить свертывание редактора для удаления методов HttpServlet. . Для внедрения службы введите следующий код (выделен жирным). [source,java] ---- @WebServlet(name = ""HelloServlet"", urlPatterns = {""/HelloServlet""}) public class HelloServlet extends HttpServlet { *@Inject @OSGiService(dynamic=true) Hello hello;* } ---- . Добавьте следующий метод ``doGet`` . [source,java] ---- @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(hello.sayHello(""Duke"")); } ---- . Щелкните узел проекта правой кнопкой мыши и выберите команду ""Создать"" > ""Другие"". . Выберите *beans.xml* в категории ""Подключение контекстов и зависимостей"". Нажмите кнопку ""Далее"". . Используйте имя файла по умолчанию ( ``beans`` ). Нажмите кнопку ""Завершить"". При нажатии кнопки ""Готово"" мастер создает в веб-приложении файл ``beans.xml`` . Среда CDI автоматически включена, если ``beans.xml`` является частью приложения. . В файле ``beans.xml`` измените значение параметра ``bean-discovery-mode`` на ``all`` . [source,java] ---- bean-discovery-mode=""*all*"" ---- Сохраните изменения и закройте файл. Подробные сведения о различиях между значениями параметра ``bean-discovery-mode`` см. на следующих страницах: * link:http://docs.oracle.com/javaee/7/tutorial/doc/cdi-adv001.htm[+25.1 Упаковка приложений CDI+] в учебном курсе по Java EE 7 * link:http://stackoverflow.com/questions/18107858/cdi-inject-fails-on-maven-embedded-glassfish-plugin-org-jboss-weld-exceptions[+http://stackoverflow.com/questions/18107858/cdi-inject-fails-on-maven-embedded-glassfish-plugin-org-jboss-weld-exceptions+] . Щелкните правой кнопкой мыши узел ""Зависимости"" в MavenHelloWebClient в окне проектов и выберите пункт ""Добавить зависимость"". . Выберите *""Предоставленный""* в качестве области действия. . Щелкните в диалоговом окне добавления библиотеки вкладку ""Открытые проекты"" и выберите *пакет MavenHelloServiceApi OSGi *. Нажмите кнопку ""Add"". . Снова щелкните правой кнопкой мыши узел ""Зависимости"" и выберите пункт ""Добавить зависимость"". . Щелкните вкладку ""Управление зависимостями"" в диалоговом окне ""Добавить библиотеку"" и выберите артефакт ``osgi-cdi-api`` , указанный в родительском проекте POM. Нажмите кнопку ""Add"". image::images/cdi-add-dependency3.png[title=""Вкладка 'Управление зависимостями' в диалоговом окне 'Добавить библиотеку'""] . Щелкните правой кнопкой мыши ``HelloServlet.java`` в редакторе и выберите 'Исправить выражения импорта' (Alt-Shift-I; ⌘-Shift-I в Mac), чтобы добавить ``com.mycompany.mavenhelloserviceapi.Hello`` , ``javax.inject.Inject`` и ``org.glassfish.osgicdi.OSGiService`` . Сохраните изменения. NOTE: Может потребоваться добавление вручную операторов импорта для ``com.mycompany.mavenhelloserviceapi.Hello`` , если среда IDE не добавит их автоматически. . Щелкните правой кнопкой мыши MavenOSGiCDIProject и выберите пункт ""Очистка и сборка"". При сборке проекта в окне вывода должен появиться результат, похожий на следующий. [source,java] ---- Reactor Summary: MavenOSGiCDIProject ............................... SUCCESS [0.798s] MavenHelloServiceApi OSGi Bundle .................. SUCCESS [7.580s] MavenHelloServiceImpl OSGi Bundle ................. SUCCESS [1.142s] MavenHelloWebClient ............................... SUCCESS [8.072s] ------------------------------------------------------------------------ BUILD SUCCESS ---- NOTE: Если при сборке проекта MavenOSGiCDIProject веб-приложение не собирается автоматически, потребуется собрать его вручную. В окне файлов разверните узел проекта для веб-приложения и подтвердите, что архив ``MavenHelloWebClient-1.0-SNAPSHOT.war`` был создан в целевом каталоге. Если вы развернете архив WAR веб-клиента и исследуете ``MANIFEST.MF`` , то увидите, что в манифесте содержатся строки, похожие на следующие. [source,java] ---- Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Created-By: Apache Maven Built-By: nb Build-Jdk: 1.7.0_45 ---- === Сборка веб-приложения как пакета OSGi Для использования ``@OSGiService`` и получения зарегистрированных пакетов OSGi необходимо сделать веб-приложение пакетом, который может получать доступ к ``BundleContext`` . Чтобы сделать архив WAR пакетом OSGi (пакет веб-приложения), можно добавить метаданные ``Web-ContextPath`` к файлу ``MANIFEST.MF`` в архиве WAR. Для этого укажите элемент ```` в инструкциях к модулю ``maven-bundle-plugin`` , и созданный этим модулем манифест будет содержать этот элемент. Затем измените настройку ``maven-war-plugin`` , чтобы дать указание модулю добавить манифест, созданный ``maven-bundle-plugin`` , к архиву WAR. 1. В окне 'Проекты' разверните узел 'Файлы проекта' в MavenHelloWebClient и дажды щелкните ``pom.xml`` , чтобы открыть файл в редакторе. 2. Добавьте следующую запись, чтобы добавить ``maven-bundle-plugin`` к POM. [source,xml] ---- * org.apache.felix maven-bundle-plugin 2.2.0 true ejb war bundle jar /mavenhellowebclient !*.impl.*, * bundle-manifest process-classes manifest bundle-install install install * ---- . Исправьте элементы настройки в ``maven-war-plugin`` , чтобы добавить информацию о пакете к ``MANIFEST.MF`` . Сохраните изменения. [source,xml] ---- org.apache.maven.plugins maven-war-plugin 2.3 * ${project.build.outputDirectory}/META-INF/MANIFEST.MF WEB-INF/classes/ * false ---- . Щелкните правой кнопкой мыши узел проекта MavenHelloWebClient project в окне проектов и выберите пункт ""Очистка и сборка"". Теперь, если развернуть архив WAR и открыть файл ``MANIFEST.MF`` в редакторе, видно, что ``MANIFEST.MF`` теперь содержит дополнительные сведения, в том числе запись ``Web-ContextPath: /mavenhellowebclient`` , указанную в настройке ``maven-bundle-plugin`` и записях имени пакета. [source,java] ---- Manifest-Version: 1.0 Export-Package: com.mycompany.mavenhellowebclient;uses:=""com.mycompany .mavenhelloserviceapi,javax.servlet,org.glassfish.osgicdi,javax.injec t,javax.servlet.annotation,javax.servlet.http"";version=""1.0.0.SNAPSHO T"" Bundle-ClassPath: WEB-INF/classes/ Built-By: nb Tool: Bnd-1.50.0 Bundle-Name: MavenHelloWebClient Created-By: Apache Maven Bundle Plugin *Web-ContextPath: /mavenhellowebclient* Build-Jdk: 1.7.0_45 Bundle-Version: 1.0.0.SNAPSHOT Bnd-LastModified: 1395053424008 Bundle-ManifestVersion: 2 Import-Package: com.mycompany.mavenhelloserviceapi;version=""[1.0,2)"",j avax.inject,javax.servlet,javax.servlet.annotation,javax.servlet.http ,org.glassfish.osgicdi;version=""[1.0,2)"" Bundle-SymbolicName: com.mycompany.MavenHelloWebClient Archiver-Version: Plexus Archiver ---- Дополнительные сведения о сборке веб-приложений, таких как пакеты OSGi, приведены на следующих страницах. * link:http://weblogs.java.net/blog/2009/06/04/osgi-enabled-web-applications-inglassfish[+ http://weblogs.java.net/blog/2009/06/04/osgi-enabled-web-applications-inglassfish+] * link:http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html[+ http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html+] === Развертывание пакета веб-приложения В этом упражнении пакет веб-приложения будет скопирован в папку ``autodeploy/bundles`` в установке GlassFish. 1. Перейдите в каталог ``target`` , содержащий ``MavenHelloWebClient-1.0-SNAPSHOT.war`` . 2. Скопируйте ``MavenHelloWebClient-1.0-SNAPSHOT.war`` в папку ``autodeploy/bundles`` вашей установки GlassFish. При копировании архива WAR в каталог в журнале сервера GlassFish появится примерно такой результат. [source,java] ---- INFO: Started bundle: file:/glassfish-3.1.1/glassfish/domains/domain1/autodeploy/bundles/MavenHelloWebClient-1.0-SNAPSHOT.war ... INFO: ---- Injection requested for framework service type interface com.mycompany.mavenhelloserviceapi.Hello and annotated with dynamic=true, serviceCriteria= INFO: WEB0671: Loading application [com.mycompany.MavenHelloWebClient_1.0.0.SNAPSHOT] at [/mavenhellowebclient] INFO: Registered ServletContext as a service with properties: {osgi.web.symbolicname=com.mycompany.MavenHelloWebClient, osgi.web.version=1.0.0.SNAPSHOT, osgi.web.contextpath=/mavenhellowebclient} ---- Теперь можно просмотреть сервлет в браузере, щелкнув следующую ссылку link:http://localhost:8080/mavenhellowebclient/HelloServlet[+http://localhost:8080/mavenhellowebclient/HelloServlet+]. == Установка и использование консоли администрирования OSGi Можно использовать консоль администрирования OSGi GlassFish для установки, запуска и останова пакетов OSGi, развернутых на сервере. В этом упражнении будет включена консоль администрирования OSGi GlassFish, а затем просмотрен список зарегистрированных пакетов OSGi. Выполните следующие действия по установке требуемых дополнительных надстроек GlassFish, чтобы включить консоль OSGi и просмотреть развернутые пакеты в консоли администрирования домена GlassFish. 1. Откройте консоль администрирования домена GlassFish в своем браузере. Щелкните правой кнопкой мыши узел сервера GlassFish в окне ""Службы"" и выберите пункт ""Просмотреть консоль администрирования домена"". . Щелкните средство обновления в левом столбце навигации. . Выберите ``glassfish-osgi-gui`` из списка допустимых надстроек. Нажмите ""Установить"" и примите лицензионное соглашение. image::images/cdi-glassfish-addons.png[title=""Средство обновления консоли администратора GlassFish""] . Перезапустите сервер приложений GlassFish. *Важно!* При работе с GlassFish Server 3.1.2.2 необходимо внести изменения в файл ``osgi.properties`` , который находится в каталоге ``_GLASSFISH-INSTALL_/glassfish/config/`` , и задать для свойства ``org.osgi.framework.startlevel.beginning`` значение '2' ( ``org.osgi.framework.startlevel.beginning=2`` ). Дополнительную информацию см. в сообщении форума: link:http://www.java.net/forum/topic/glassfish/glassfish/cannot-start-web-console-glassfish-version-3122[+ Невозможно запустить веб-консоль на Glassfish версии 3.1.2.2+]. . Снова откройте консоль администрирования и выберите пункт *сервер (сервер администрирования)* в левом столбце навигации. . Щелкните по вкладке консоли OSGi, чтобы просмотреть список развернутых пакетов OSGi. image::images/cdi-glassfish-console.png[title=""Вкладка 'Управление зависимостями' в диалоговом окне 'Добавить библиотеку'""] NOTE: На экране может отобразиться запрос на ввод имени пользователя и пароля для просмотра списка пакетов OSGi. Если на вкладке ""Консоль OSGi"" не отображается список пакетов, убедитесь, что не скрыто диалоговое окно авторизации. По умолчанию для GlassFish 4 используется имя пользователя ``admin`` (если сервер был установлен вместе с IDE). Пароль по умолчанию пуст. Можно прокрутить список ниже, чтобы просмотреть состояние зарегистрированных пакетов OSGi, запускать и останавливать отдельные пакеты. Если упорядочить список по идентификатору (от высшего к низшему), на первых позициях в списке отобразятся три развернутых пакета. link:/about/contact_form.html?to=3&subject=Feedback:%20Using%20CDI%20to%20Inject%20OSGi%20Bundles%20as%20Services[+Отправить отзыв по этому учебному курсу+] == Дополнительные сведения For more information about using IDE NetBeans and Maven to develop OSGi bundles, see the following resources: * link:http://wiki.netbeans.org/OSGiAndNetBeans[+OSGi и NetBeans на wiki.netbeans.org+] * link:http://wiki.netbeans.org/MavenBestPractices[+Испытанные приемы для Apache Maven в IDE NetBeans+] * link:https://blogs.oracle.com/arungupta/entry/totd_125_creating_an_osgi[+TOTD #125: Создание пакетов OSGi с помощью NetBeans и развертывание в GlassFish+] * link:../../trails/java-ee.html[+Учебная карта по Java EE и Java Web+] To send comments and suggestions, get support, and keep informed on the latest developments on the IDE NetBeans Java EE development features, link:../../../community/lists/top.html[+join the nbj2ee mailing list+]. ",12461,False,2430.447935446843,median "eBay erweitert sein Fulfillment-Programm mit dem Logistikpartner Orange Connex. eBay Fulfillment by Orange Connex bietet eBay-Verkäufer:innen unkomplizierte, zuverlässige und bezahlbare Fulfillment-Dienstleistungen an, die speziell auf die Service-Standards im eCommerce zugeschnittenen sind. [discrete] == Jetzt teilnehmen Du möchtest eBay Fulfillment by Orange Connex nutzen? Informiere dich und starte jetzt mit link:https://cloud.forbusiness.ebay.com/fulfillment[eBay Fulfillment by Orange Connex^]. [discrete] == Was bedeutet Outbound? Der Begriff _Outbound_ beschreibt den Prozess des Vertriebs und Versands, den der Fulfillment-Dienstleister für dich übernimmt: Er verpackt die Artikel, lagert diese zwischen und sendet die Artikel dann an deine Kund:innen. Diesen gesamten Prozess übernimmt eBay Fulfillment by Orange Connex für dich. [discrete] == Hinweise für Händler, die bereits die eBay Fulfillment-Lösung mit Fiege nutzen Wenn du bereits die eBay Fulfillment-Lösung mit Fiege nutzt und dich somit aktuell im ""Parallelbetrieb"" befindest, beachte die folgenden Punkte und prüfe die Einstellungen in deinem plentymarkets System: *Auftragsherkunft* * Prüfe die <>. Die Auftragsherkunft für *eBay Fulfillment by Orange Connex* muss aktiviert sein. * icon:exclamation-triangle[role=""red""] Die bisher verwendete Auftragsherkunft für die eBay Fulfillment-Lösung mit Fiege sollte jedoch _nicht_ deaktiviert werden, bis der gesamte Warenbestand im Fiege-Lager abgekauft bzw. ins Orange Connex-Lager umgezogen wurde. *Marktplatz-Verfügbarkeit am Artikel bzw. der Variante* * Füge die <> *eBay Fulfillment by Orange Connex* an den Varianten hinzu. * icon:exclamation-triangle[role=""red""] Die bisher verwendete Verfügbarkeit für die eBay Fulfillment-Lösung mit Fiege sollte jedoch _nicht_ entfernt werden, bis der gesamte Warenbestand im Fiege-Lager abgekauft bzw. ins Orange Connex-Lager umgezogen wurde. *Lagerauswahl am Auftrag* * Prüfe die Auftragseinstellungen und passe abhängig von der Einstellung die <> oder das <> an den Varianten an. *Bestandsübertragung an Marktplätze* * Prüfe in den jeweiligen Einstellungen des Marktplatzes, welche Lager für die Bestandsübertragung in Betracht gezogen werden. [#vorbereitende-einstellungen] == Vorbereitende Einstellungen im plentymarkets Backend Nimm die in den folgenden Unterkapiteln beschriebenen Einstellungen im plentymarkets Backend vor. [#auftragsherkunft-aktivieren] === Auftragsherkunft aktivieren Die Auftragsherkunft *eBay Fulfillment by Orange Connex* ist bereits im Menü *Einrichtung » Aufträge » Auftragsherkunft* vorhanden. Du musst diese Auftragsherkunft aktivieren. [TIP] .Hinweis für Händler, die bereits die eBay Fulfillment-Lösung mit Fiege nutzen ==== Wenn du bereits die eBay Fulfillment-Lösung mit Fiege nutzt, ist es wichtig, dass du die korrekte Auftragsherkunft für *eBay Fulfillment by Orange Connex* aktivierst. Bevor der Umzug der Waren noch nicht vollständig abgeschlossen ist, solltest du die bisher verwendete Auftragsherkunft für eBay Fulfillment nicht deaktivieren. ==== [.instruction] Auftragsherkunft aktivieren: . Öffne im plentymarkets Backend das Menü *Einrichtung » Aufträge » Auftragsherkunft*. . Suche *eBay Fulfillment by Orange Connex*. . Aktiviere die Option, indem du ein Häkchen setzt. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [#lieferlaender-aktivieren] === Lieferländer aktivieren eBay Fulfillment by Orange Connex bietet den Versand in folgende Länder an: * Belgien * Bulgarien * Deutschland * Frankreich (außer Überseegebiete) * Griechenland * Italien (außer Campione d'Italia, Livigno, San Marino, Vatikanstadt) * Kroatien * Luxemburg * Malta * Niederlande (außer Überseegebiete) * Österreich * Portugal (außer Azoren, Madeira) * Rumänien * Slowakei * Slowenien * Spanien (außer Kanarische Inseln, Ceuta, Melilla) * Tschechische Republik * Ungarn * Zypern Um in plentymarkets korrekt mit diesen Lieferländern arbeiten zu können, müssen diese in deinem plentymarkets System aktiviert werden. [WARNING] .Hinweis ==== Es kann zu Einschränkungen bei der Belieferung über andere Marktplätze aufgrund der begrenzten Anzahl an aktiven Lieferländern kommen. ==== [.instruction] Lieferländer aktivieren: . Öffne das Menü *Einrichtung » Aufträge » Versand » Optionen*. + → Das Tab *Lieferländer* wird geöffnet. . Wähle für die gewünschten Lieferländer in der Spalte *Aktiv* die Option *Aktiv* oder *Backoffice aktiv* aus der Dropdown-Liste. + → *_Hinweis:_* Bei Wahl der Option *Aktiv* ist das Lieferland auch im Webshop sichtbar. Bei Wahl der Option *Backoffice aktiv* ist das Lieferland nur im plentymarkets System, aber nicht im Webshop sichtbar. . Wähle in der Spalte *Sprache* die gewünschte Sprache, die für das Lieferland aktiviert werden soll. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [#e-mail-server-zugangsdaten] === E-Mail-Server-Zugangsdaten speichern Damit du über dein plentymarkets System E-Mails an deine Kund:innen senden kannst, ist es unbedingt erforderlich, die Zugangsdaten des E-Mail-Postfachs, aus dem du die E-Mails versenden möchtest, in plentymarkets zu speichern. [.instruction] E-Mail-Server-Zugangsdaten speichern: . Öffne im plentymarkets Backend das Menü *Einrichtung » Mandant » [Mandant wählen] » E-Mail » Zugangsdaten*. . Nimm die gewünschten Einstellungen vor. Beachte die Erläuterungen in <<#table-ebay-fulfillment-email-server-login-details>>. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [[table-ebay-fulfillment-email-server-login-details]] .Zugangsdaten des E-Mail-Servers speichern [cols=""1,3""] |==== |Einstellung |Erläuterung | *Testmodus* | *Aktiv* = Der Testmodus ist aktiviert. Alle E-Mails werden nur an die eingegebene E-Mail-Adresse gesendet. So kann vor dem Live-Betrieb die korrekte Funktionsweise geprüft werden. + *Inaktiv* = Der Live-Modus ist aktiviert. + *_Wichtig:_* Der Testmodus gilt nur für diesen Webshop. Die Einstellungen für weitere Mandanten werden im Menü des Mandanten konfiguriert. | *Name des Absenders* |Eigenen Namen oder Namen des Webshops eingeben. Der Name wird dem Empfänger angezeigt. Für die korrekte Darstellung die Verwendung von Sonderzeichen vermeiden. | *E-Mail-Adresse* |E-Mail-Adresse eingeben, wie sie auch im E-Mail-Programm steht. | *Postausgangsserver/SMTP-Server* |Postausgangsserver wie vom Provider angegeben eingeben (meist smtp.domain.de oder mail.domain.de). | *Benutzername* |Benutzer:innenname zu der E-Mail-Adresse eingeben. | *Passwort* |Passwort zu dem Benutzer:innenname und der E-Mail-Adresse eingeben. | *Port* |Wert *465* eingeben, wenn als Verschlüsselung *SSL* verwendet wird. + Wert *25* eingeben, wenn *keine Verschlüsselung* verwendet wird. + *_Hinweis:_* Ggf. den korrekten Port beim Provider erfragen. | *Verschlüsselung* | *SSL*, *TLS* oder *keine Verschlüsselung* wählen. |==== [#benutzerrechte-backend-benutzer] === Rechte für Backend-Benutzer:innen vergeben :rights-purpose: mit eBay Fulfillment by Orange Connex arbeiten können :right-one: pass:quotes[*Aufträge > Anzeigen*] :right-two: pass:quotes[*Aufträge > Auftragsstatus > Anzeigen*] :right-three: pass:quotes[*Aufträge > Auftragsstatus > Aktualisieren*] include::_includes:page$rechte.adoc[] [#einstellungen-assistent] == Einstellungen im Assistenten In den folgenden Unterkapiteln ist beschrieben, welche Einstellungen du in den einzelnen Schritten des Assistenten *eBay Fulfillment by Orange Connex* vornehmen kannst. Du findest den Assistenten im Menü *Einrichtung » Assistenten* im Bereich *Integration*. [#anmelden-registrieren] === Authentifizierung Im ersten Schritt des Assistenten authentifizierst du dich für die Nutzung von eBay Fulfillment by Orange Connex. Öffne die Webseite, indem du auf die Schaltfläche *Autorisieren* klickst. Gib dort deine Zugangsdaten ein, die du von Orange Connex erhalten hast. Wenn du dann auf der Authentifizierungsseite die Schaltfläche *Ich stimme zu* geklickt hast, erhältst du eine Meldung, dass die Authentifizierung erfolgreich war und du das Browser-Tab schließen und zum Assistenten zurückkehren kannst. Sobald du dich erfolgreich authentifiziert und im Assistenten auf *Weiter* geklickt hast, ist der Schritt *Authentifizierung* im Assistenten nicht mehr sichtbar. [#datenuebertragung-lagereinstellungen] === Datenübertragung und Lagereinstellungen Im Schritt *Datenübertragung und Lagereinstellungen* legst du fest, ob deine Artikel und der Warenbestand übertragen werden sollen. Wenn du diese Optionen aktivierst, werden: * die Artikeldaten automatisch in regelmäßigen Abständen von plentymarkets an Orange Connex übertragen * die Warenbestände automatisch in regelmäßigen Abständen von Orange Connex an plentymarkets zurückgemeldet Außerdem entscheidest du, ob du ein neues Lager für eBay Fulfillment by Orange Connex erstellen oder ein bestehendes Lager verwenden möchtest. Wenn du hier ein neues Lager erstellst, wird automatisch der Typ *Vertrieb* gewählt und alle Auftragsherkünfte werden für dieses Lager aktiviert. Der Name des Lagers ist _eBay Fulfillment_. Das Erstellen eines zweiten Lagers ist nicht notwendig. Wenn du ein bestehendes Lager wählst, werden dir hier nur Lager vom Typ *Vertrieb* angezeigt. Anschließend wählst du den Standardservice für den Inlandsversand und den internationalen Versand. Die hier gewählten Services werden dann als Standard bei allen Versandprofilen übertragen, außer du wählst im Versandprofil explizit einen anderen Service. [#briefversand] [discrete] ==== Briefversand Wenn du den Briefversand nutzen möchtest, wählst du als Standardservice *DE Inland Economy*. Im Assistentenschritt <<#versandprofilverknuepfung, *Versandprofilverknüpfung*>> wählst du den Versanddienstleister *Orange Connex*. Orange Connex stellt dann eine Sendungsnummer zur Verfügung. Die Sendungsnummer zeigt an, wann der Brief versendet wurde. Es ist allerdings nicht möglich, den Verlauf des Briefes zu verfolgen. [#speditionsversand] [discrete] ==== Speditionsversand Wenn du den Speditionsversand nutzen möchtest, wählst du als Standardservice *DE Fracht*. Mit dem Speditionsversand kannst du Aufträge bis 2,5 Tonnen per Spedition versenden lassen. Im Assistentenschritt <<#versandprofilverknuepfung, *Versandprofilverknüpfung*>> wählst du den Versanddienstleister *Orange Connex*. Orange Connex leitet das Tracking zu diesen Sendungsnummern dann automatisch auf den korrekten Speditionspartner um. [#auftragsstatus-auftraege-senden-stornieren] === Status: Outbound-Aufträge senden/stornieren Im Schritt *Status: Outbound-Aufträge senden/stornieren* kannst du zwei Status speichern: einen Status für Outbound-Aufträge, die an eBay Fulfillment by Orange Connex versendet werden können und einen Status für Outbound-Aufträge, die erfolgreich an eBay Fulfillment by Orange Connex versendet wurden, aber die du wieder stornieren möchtest. Du kannst entweder bestehende Status wählen oder neue Status erstellen. [IMPORTANT] Wenn du einen bestehenden Status wählst, stelle sicher, dass dieser Status in keinem anderen Prozess oder Ereignisaktion verwendet wird. Andernfalls könnte dies zu Problemen führen. Erstelle einen Auftragsstatus für die folgenden zwei Ereignisse: * Outbound-Auftrag senden * Stornierungsanfrage senden [#auftragsstatus-auftragsaenderung-ebay-fulfillment-orange-connex] === Status: Auftragsänderungen durch eBay Fulfillment by Orange Connex Im Schritt *Status: Auftragsänderungen durch eBay Fulfillment by Orange Connex* kannst du die Status für Outbound-Aufträge speichern, die als Antwort von eBay Fulfillment by Orange Connex in dein plentymarkets System zurückkommen. Die Antwort von eBay Fulfillment by Orange Connex bezieht sich immer auf Outbound-Aufträge, die du bereits gesendet hast. Du kannst entweder bestehende Status wählen oder neue Status erstellen. [IMPORTANT] Wenn du einen bestehenden Status wählst, stelle sicher, dass dieser Status in keinem anderen Prozess oder Ereignisaktion verwendet wird. Andernfalls könnte dies zu Problemen führen. Erstelle einen neuen Auftragsstatus oder wähle einen bestehenden Auftragsstatus für die folgenden Auftragsänderungen: * Outbound-Auftrag erfolgreich gesendet * Outbound-Auftrag abgelehnt * Outbound-Auftrag storniert * Outbound-Auftrag Ausnahme * Outbound-Auftrag unzustellbar * Auto-Fulfillment-Auftrag fehlgeschlagen [[table-order-statuses]] .Auftragsstatus für eBay Fulfillment by Orange Connex [cols=""1,3""] |==== |Status |Erläuterung |Outbound-Auftrag erfolgreich gesendet |Wenn sich der Outbound-Auftrag in diesem Status in deinem plentymarkets System befindet, war die Übertragung an Orange Connex erfolgreich. |Outbound-Auftrag abgelehnt |Wenn sich der Outbound-Auftrag in diesem Status in deinem plentymarkets System befindet, wurde der Outbound-Auftrag von Orange Connex abgelehnt. + Ein Grund dafür könnten fehlende Daten am Artikel sein. Der Grund wird als Auftragsnotiz gespeichert. |Outbound-Auftrag storniert |Wenn sich der Outbound-Auftrag in diesem Status in deinem plentymarkets System befindet, hat Orange Connex die Stornierung des Outbound-Auftrags akzeptiert. |Outbound-Auftrag Ausnahme |Wenn sich der Outbound-Auftrag in diesem Status in deinem plentymarkets System befindet, wurde der Outbound-Auftrag nachträglich abgelehnt. Das bedeutet, zunächst hat Orange Connex den Outbound-Auftrag akzeptiert und nachträglich dann doch abgelehnt. + Gründe dafür könnten z.B. die falsche Menge im Lager oder ein defekter Artikel sein. Der Grund wird als Auftragsnotiz gespeichert. |Outbound-Auftrag unzustellbar a|Wenn sich der Outbound-Auftrag in diesem Status in deinem plentymarkets System befindet, konnte der Outbound-Auftrag nicht zugestellt werden. + Gründe für die Unzustellbarkeit sind z.B.: * die Adresse ist falsch * das Paket wurde innerhalb der Einlagerungsfrist nicht abgeholt * die Annahme wurde verweigert * der Empfänger wurde mehrfach nicht angetroffen. |Auto-Fulfillment-Auftrag fehlgeschlagen a|Wenn sich der Auto-Fulfillment-Auftrag in diesem Status in deinem plentymarkets System befindet, konnte der Auto-Fulfillment-Auftrag nicht übermittelt werden. + Ein Grund für die fehlgeschlagene Übermittlung ist z.B., dass der Straßenname zu viele Zeichen hat. Logge dich in das Orange Connex-Portal ein und behebe den Fehler dort, damit der Auftrag korrekt übermittelt werden kann. |==== [WARNING] .Nur freie Auftragsstatus verwenden ==== Du musst freie, noch unbesetzte Auftragsstatus suchen und diese dann verwenden. Überschreibe in keinem Fall bereits besetzte Auftragsstatus, da sich diese möglicherweise an anderer Stelle in deinem plentymarkets System (z.B. in Ereignisaktionen oder Prozessen) bereits in Verwendung befinden und Komplikationen die Folge sein könnten. *_Tipp:_* Wähle die Status zwischen 5 und 8. ==== [#auftragsstatus-retourenauftragsaenderung-ebay-fulfillment-orange-connex] === Status: Retourenauftragsänderungen durch eBay Fulfillment by Orange Connex Im Schritt *Status: Retourenauftragsänderungen durch eBay Fulfillment by Orange Connex* kannst du die Status für Retourenaufträge speichern, die als Antwort von eBay Fulfillment by Orange Connex in dein plentymarkets System zurückkommen. Die Antwort von eBay Fulfillment by Orange Connex bezieht sich immer auf Retourenaufträge, die bei einer Retoure angelegt werden, sofern noch kein Retourenauftrag existiert. Du kannst entweder bestehende Status wählen oder neue Status erstellen. [IMPORTANT] Wenn du einen bestehenden Status wählst, stelle sicher, dass dieser Status in keinem anderen Prozess oder Ereignisaktion verwendet wird. Andernfalls könnte dies zu Problemen führen. Erstelle einen Auftragsstatus für das folgende Ereignis: * Auftrag unzustellbar [#versandprofilverknuepfung] === Versandprofilverknüpfung Im Schritt *Versandprofilverknüpfung* verknüpfst du die eBay Fulfillment by Orange Connex-Dienstleister mit den plentymarkets Versandprofilen. [IMPORTANT] .eBay Fulfillment by Orange Connex legt Dienstleister fest ==== Die Dienstleister sind von eBay Fulfillment by Orange Connex festgelegt. Du kannst diese nicht löschen oder neue Dienstleister hinzufügen. eBay Fulfillment by Orange Connex entscheidet, welcher Dienstleister für den Fulfillment-Prozess verwendet wird. Aktuell werden DHL, DPD, GLS, Hermes, UPS und Deutsche Post eingesetzt. + Wenn du <<#briefversand, Briefversand>> oder <<#speditionsversand, Speditionsversand>> nutzen möchtest, wählst du als Versanddienstleister *Orange Connex*. ==== Damit du deine Sendungen korrekt verfolgen kannst, musst du jedem eBay Fulfillment by Orange Connex-Dienstleister ein plentymarkets Versandprofil zuweisen. Du kannst ein bereits vorhandenes Versandprofil wählen oder ein neues Versandprofil erstellen. [discrete] ==== Neues Versandprofil erstellen Klicke auf die Dropdown-Liste *Versandprofil* und wähle den Eintrag *+ Neues Versandprofil erstellen*, damit plentymarkets automatisiert ein neues Versandprofil und einen Versanddienstleister für dich erstellt. Der Name des Versandprofils setzt sich zusammen aus dem Namen des Versanddienstleisters und dem Anhang _eBay Fulfillment by Orange Connex_, z.B. *Hermes eBay Fulfillment by Orange Connex*. [#zusammenfassung] === Zusammenfassung In diesem Schritt wird eine Zusammenfassung aller getätigten Eingaben in den einzelnen Schritten aufgelistet. Du kannst deine Angaben prüfen, in den einzelnen Schritten ggf. Anpassungen vornehmen und den Assistenten danach über die Zusammenfassung abschließen. [#artikel-einrichten-sku-erhalten] == Artikel einrichten und SKU erhalten Richte die Artikel bzw. Varianten ein, die du über eBay Fulfillment by Orange Connex versenden möchtest. Die Variante wird an Orange Connex übertragen, wenn die folgenden Bedingungen erfüllt sind: * Der Markt (Auftragsherkunft) *eBay Fulfillment by Orange Connex* wurde im Tab *Verfügbarkeit* der Variante aktiviert. * Der Verkaufspreis, für den die Auftragsherkunft *eBay Fulfillment by Orange Connex* aktiviert ist, wurde im Tab *Einstellungen* der Variante gespeichert. Orange Connex prüft die Variante und überträgt die SKU nach positiver Prüfung automatisch an plentymarkets. [IMPORTANT] .Stündlicher Abgleich der SKU ==== Beachte, dass es nach positiver Prüfung der Variante bis zu einer Stunde dauern kann, bis die SKU auch am Artikel bz. an der Variante sichtbar ist. ==== Im Folgenden ist beschrieben, wie du die Verkaufspreise und die Verfügbarkeit manuell einrichtest. Wie du diese Einstellungen über eine Gruppenfunktion für alle Varianten vornimmst, ist im Kapitel <<#gruppenfunktion-verwenden, Gruppenfunktion verwenden>> beschrieben. [.instruction] Artikel einrichten: . Öffne im plentymarkets Backend das Menü *Artikel » Artikel bearbeiten*. . Öffne die Variante, die du über eBay Fulfillment by Orange Connex versenden möchtest. + → Die Hauptvariante wird geöffnet. . Gib im Bereich *Verkaufspreise* den von dir gewünschten Verkaufspreis ein. . Wechsele in das Tab *Verfügbarkeit*. . Aktiviere im Bereich *Märkte* die Optionen *eBay*, *eBay Fulfillment by Orange Connex* und *WEB-API*. . *Speichere* (icon:save[role=""green""]) die Einstellungen. . Wechsele zurück in das Tab *Einstellungen*. . Setze im Bereich *Verfügbarkeit* ein Häkchen bei *Aktiv*. . *Speichere* (icon:save[role=""green""]) die Einstellung. + → Der Artikel ist aktiviert und die SKU wird automatisch an plentymarkets übertragen. [WARNING] .Verfügbarkeit und eBay-Verkaufspreis müssen gespeichert sein ==== Artikelstammdaten werden nur von plentymarkets an eBay Fulfillment by Orange Connex übermittelt, wenn die Verfügbarkeit aktiviert und der Verkaufspreis, für den die Auftragsherkunft *eBay Fulfillment by Orange Connex* aktiviert ist, gespeichert sind. ==== [#artikelpaket-einrichten] === Artikelpaket (Bundle) einrichten Ein Bundle, ein sogenanntes Artikelpaket, besteht aus mehreren Artikeln. Der Paketpreis des Bundles kann dabei günstiger sein als die Summe der Einzelpreise. Wenn du in deinem plentymarkets System bereits Artikelpakete eingerichtet hast, gibt es dennoch 2 Einstellungsmöglichkeiten am Artikel, die du vornehmen musst, damit diese durch eBay Fulfillment by Orange Connex verarbeitet werden können. [#bundle-mehrere-artikel-als-einheit] === Bundle aus mehreren Artikeln als Einheit Das Bundle besteht aus mehreren Artikeln, die eine Einheit bilden. Das heißt, das Bundle wird als solche Einheit angeboten und wird in einer gemeinsamen Verpackung verpackt an eBay Fulfillment by Orange Connex versendet. Dem kompletten Paket wird eine SKU zugeordnet. [.collapseBox] .Beispiel eines Bundles aus mehreren Artikeln als Einheit -- Ein etwas abstraktes Beispiel für ein “festes” Bundle ist ein Auto. Das Auto wird als Einheit verkauft und es ist nicht vorgesehen, beispielsweise nur das Lenkrad auszubauen und dann zu verkaufen, obwohl es sich bei dem Lenkrad trotzdem um einen einzelnen Artikel handeln kann. -- [#bundle-mehrere-einzelne-artikel] ==== Bundle aus mehreren, einzelnen Artikeln Das Bundle besteht aus mehreren, einzelnen Artikeln. Das heißt, du musst in jedem Bestandteil dieses Pakets die Verfügbarkeit wie in Kapitel <> beschrieben setzen. Dadurch verfügt jeder Artikel im Paket über eine eigene SKU. Bei der Bestellübermittlung an eBay Fulfillment by Orange Connex wird jeder Bestandteil des Artikelpakets wie die Bestellung einzelner Artikel behandelt. [.collapseBox] .Beispiel eines Bundles aus mehreren, einzelnen Artikeln -- Du verkaufst Esszimmerstühle und Esszimmertische. Außerdem bietest du eine Kombination der Artikel als Bundle (1 Esszimmertisch und 4 Esszimmerstühle) an. Im Gegensatz zu den einzelnen Preisen ergibt sich der Bundlepreis wie folgt: [[table-ebay-fulfillment-example-bundle]] .Beispielrechnung für Bundle [cols=""1,3,3""] |==== | *Artikel* | *Einzelpreis* | *Gesamtpreis* |Esszimmerstuhl |59,99 EUR |Preis x 4 = 239,96 EUR |Esszimmertisch |299,99 EUR |299,99 EUR | | |539,95 EUR 3+|Bundlepreis = 499,99 EUR |==== [[bild-artikel-bearbeiten]] .Übersicht im Menü *Artikel » Artikel bearbeiten* image::fulfillment/assets/eBay-Fulfillment-Artikeluebersicht.png[width=640, height=360] [[bild-tab-bestand]] .Ansicht in der Variante im Tab *Bestand* image::fulfillment/assets/eBay-Fulfillment-Bundle-Tab-Bestand.png[width=640, height=360] -- [#gruppenfunktion-verwenden] === Gruppenfunktion verwenden Im Menü *Artikel » Artikel bearbeiten* kannst du über die Varianten-Gruppenfunktion schnell und komfortabel deine Varianten bearbeiten und so die Verkaufspreise ändern und die Martkplatz-Verfügbarkeit *eBay Fulfillment by Orange Connex* aktivieren. Gehe wie im Folgenden beschrieben vor. [.instruction] Gruppenfunktion verwenden: . Öffne das Menü *Artikel » Artikel bearbeiten*. . Setze links den Filter *Tabellentyp* auf *Varianten*. . Wähle ggf. weitere <>. . Klicke auf *Suchen* (icon:search[role=""blue""]). . Wähle (icon:check-square[role=""blue""]) die zu bearbeitenden Varianten in der Übersicht rechts. . Klicke auf *Varianten-Gruppenfunktion*. + → Das Fenster *Varianten-Gruppenfunktion* wird geöffnet. . Wähle im Bereich *Marktplatz-Verfügbarkeit* die Option *eBay Fulfillment by Orange Connex*. . Wähle die Checkboxen auf der linken und rechten Seite. . Klicke auf icon:execute[set=plenty] *Ausführen*, um die Einstellungen an den Varianten vorzunehmen. [TIP] .Hinweis für Händler, die bereits die eBay Fulfillment-Lösung mit Fiege nutzen ==== Wenn du bereits die eBay Fulfillment-Lösung mit Fiege nutzt, kannst du über die Varianten-Gruppenfunktion die Marktplatz-Verfügbarkeit *eBay Fulfillment by Orange Connex* hinzufügen. + *_Wichtig:_* Füge die neue Verfügbarkeit hinzu, aber entferne _nicht_ die vorherige eBay Fulfillment-Lösung mit Fiege. Andernfalls könnte es beim Übergang von Alt auf Neu zu Problemen führen. Setze im Menü *Artikel » Artikel bearbeiten* den Filter *Tabellentyp* auf *Varianten* und den Filter *eBay Fulfillment* auf *Sichtbar*, damit dir alle Varianten, die du mit Fiege abgewickelt hast, angezeigt werden. ==== Weitere Informationen zur Varianten-Gruppenfunktion findest du auf der Handbuchseite <>. [#automatismen-einrichten] == Automatismen einrichten In plentymarkets besteht die Möglichkeit Routineaufgaben wie beispielsweise das Verschieben von Aufträgen in den korrekten Status oder das Buchen von Warenausgängen automatisiert durch das System erledigen zu lassen. Somit kannst du den ganzen Outbound-Prozess automatisiert durchlaufen lassen. Mit den Ereignisaktionen stellen wir dir ein effektives Werkzeug zur Verfügung, mit dem du solche Automatismen einstellen und zuverlässig durch dein plentymarkets System ausführen lassen kannst. Das Grundprinzip von Ereignisaktionen ist leicht verständlich: Bestimmte Ereignisse lösen bestimmte Aktionen aus. [#ea-outbound-auftrag-verschieben] === Ereignisaktion zum Verschieben des Outbound-Auftrags in den korrekten Status einrichten Gehe wie im Folgenden beschrieben vor, um die Ereignisaktion einzurichten. [.instruction] Ereignisaktion zum Verschieben des Outbound-Auftrags in den korrekten Status einrichten: . Öffne im plentymarkets Backend das Menü *Einrichtung » Aufträge » Ereignisse*. . Klicke auf *Ereignisaktion hinzufügen* (icon:plus-square[role=""green""]). . Gib den gewünschten Namen für diese Ereignisaktion, z.B. `Outbound-Auftrag verschieben`. *_Auslösendes Ereignis_* . Wähle aus der Dropdown-Liste *Ereignis* die Option *Auftragsänderung > Statuswechsel*. . Wähle aus der Dropdown-Liste *Status* den Status *Freigabe Versand*. . *Speichere* (icon:save[role=""green""]) die Einstellungen. *_Filterkriterien für Aufträge_* . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragstyp*. . Klicke auf *Hinzufügen*. . Aktiviere die Option *Auftrag*. . Aktiviere die Option *Lieferauftrag*. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragslager*. . Klicke auf *Hinzufügen*. . Aktiviere das eBay Fulfillment by Orange Connex Lager, das du im Assistenten erstellt hast. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Zahlungsart*. . Klicke auf *Hinzufügen*. . Aktiviere alle Zahlungsarten mit Ausnahme von *Nachnahme*. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Versand > Lieferland*. . Klicke auf *Hinzufügen*. . Aktiviere die Länder, die du auch im Orange Connex-Backend im Bereich _Für eBay Fulfillment registrieren_ aktiviert hast. *_Auszuführende Aktion_* . Klicke auf *Aktion hinzufügen* (icon:plus-square[role=""green""]). . Wähle die Aktion *Auftrag > Status ändern*. . Klicke auf *Hinzufügen*. . Wähle aus der Dropdown-Liste *Status* den Status, den du im Assistenten erstellt hast, z.B. `Outbound-Auftrag senden`. . Setze ein Häkchen bei *Aktiv*, um die Ereignisaktion zu aktivieren. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [#ea-outbound-auftrag-senden] === Ereignisaktion zum Senden des Outbound-Auftrags an eBay Fulfillment by Orange Connex einrichten Gehe wie im Folgenden beschrieben vor, um die Ereignisaktion einzurichten. [.instruction] Ereignisaktion zum Senden des Outbound-Auftrags an eBay Fulfillment by Orange Connex einrichten: . Öffne im plentymarkets Backend das Menü *Einrichtung » Aufträge » Ereignisse*. . Klicke auf *Ereignisaktion hinzufügen* (icon:plus-square[role=""green""]). . Gib den gewünschten Namen für diese Ereignisaktion ein, z.B. `eBay Fulfillment Outbound senden`. *_Auslösendes Ereignis_* . Wähle aus der Dropdown-Liste *Ereignis* die Option *Auftragsänderung > Statuswechsel*. . Wähle aus der Dropdown-Liste *Status* den Status, den du im Assistenten erstellt hast, z.B. `Outbound-Auftrag senden`. . *Speichere* (icon:save[role=""green""]) die Einstellungen. *_Filterkriterien für Aufträge_* . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragstyp*. . Klicke auf *Hinzufügen*. . Aktiviere die Option *Auftrag*. . Aktiviere die Option *Lieferauftrag*. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragslager*. . Klicke auf *Hinzufügen*. . Aktiviere das eBay Fulfillment by Orange Connex Lager, das du im Assistenten erstellt hast. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Versand > Lieferland*. . Klicke auf *Hinzufügen*. . Aktiviere die Länder, die du auch im Orange Connex-Backend im Bereich _Für eBay Fulfillment registrieren_ aktiviert hast. *_Auszuführende Aktion_* . Klicke auf *Aktion hinzufügen* (icon:plus-square[role=""green""]). . Wähle die Aktion *Plugins > eBay Fulfillment by Orange Connex: Auftrag senden*. . Klicke auf *Hinzufügen*. . Setze ein Häkchen bei *Aktiv*, um die Ereignisaktion zu aktivieren. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [#ea-warenausgang-buchen] === Ereignisaktion zum Buchen des Warenausgangs einrichten Wenn eBay Fulfillment by Orange Connex die Bestellung abwickeln kann, wird automatisch die Paketnummer im Outbound-Auftrag hinterlegt. Um anschließend den Warenausgang zu buchen und die Paketnummer an eBay Fulfillment by Orange Connex zu übermitteln, damit deine Kund:innen die Sendungsverfolgung nutzen können, richte eine weitere Ereignisaktion ein. [.instruction] Ereignisaktion zum Buchen des Warenausgangs einrichten: . Öffne im plentymarkets Backend das Menü *Einrichtung » Aufträge » Ereignisse*. . Klicke auf *Ereignisaktion hinzufügen* (icon:plus-square[role=""green""]). . Gib den gewünschten Namen für diese Ereignisaktion ein, z.B. `eBay Fulfillment Warenausgang`. *_Auslösendes Ereignis_* . Wähle aus der Dropdown-Liste *Ereignis* die Option *Auftragsänderung > Paketnummer*. . *Speichere* (icon:save[role=""green""]) die Einstellungen. *_Filterkriterien für Aufträge_* . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragslager*. . Aktiviere das eBay Fulfillment by Orange Connex Lager, das du im Assistenten erstellt hast. *_Auszuführende Aktion_* . Klicke auf *Aktion hinzufügen* (icon:plus-square[role=""green""]). . Wähle die Aktion *Auftrag > Warenausgang buchen*. . Klicke auf *Hinzufügen*. . Setze ein Häkchen bei *Aktiv*, um die Ereignisaktion zu aktivieren. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [#ea-automatische-sendungsverfolgung] === Ereignisaktion für die automatische Sendungsverfolgung (Tracking-URL) einrichten Mit deinem plentymarkets System ist es möglich, eine Versandbestätigung via E-Mail an deine Kund:innen zu versenden. Dies setzt voraus, dass du die <> und eine entsprechende E-Mail-Vorlage in deinem System erstellt hast. [.instruction] Ereignisaktion für die automatische Sendungsverfolgung (Tracking-URL) einrichten: . Öffne im plentymarkets Backend das Menü *Einrichtung » Mandant » Standard » E-Mail » Vorlagen » Allgemeine Vorlagen > Auftrag: Versandbestätigung*. . Wähle das Tab *E-Mail-Nachricht*. + → Hier befindet sich ein Text, der standardmäßig in jedem System hinterlegt ist. Passe diesen Text ggf. nach deinen eigenen Wünschen an. . Füge die Variable `$TrackingURL` an der gewünschten Stelle in deinem Text ein. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [IMPORTANT] .Übersicht über alle Template-Variablen ==== Klicke im Tab *E-Mail-Vorlagen* rechts neben der *Speichern*-Schaltfläche auf die Schaltfläche *Template-Variablen und -Funktionen* (icon:code[role=""blue""]), um eine Übersicht über alle Template-Variablen zu erhalten, die du in deine E-Mail-Vorlage einfügen kannst. ==== Die folgenden Schritte erklären, wie du eine Versandbestätigung automatisch an deine Kund:innen versenden kannst. . Öffne im plentymarkets Backend das Menü *Einrichtung » Aufträge » Ereignisse*. . Klicke auf *Ereignisaktion hinzufügen* (icon:plus-square[role=""green""]). . Gib den gewünschten Namen für diese Ereignisaktion ein, z.B. `Automatisierung Sendungsverfolgung Outbound`. *_Auslösendes Ereignis_* . Wähle aus der Dropdown-Liste *Ereignis* die Option *Auftragsänderung > Paketnummer*. *_Filterkriterien für Aufträge_* . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragstyp*. . Klicke auf *Hinzufügen*. . Aktiviere die Option *Auftrag*. . Aktiviere die Option *Lieferauftrag*. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragslager*. . Klicke auf *Hinzufügen*. . Aktiviere das eBay Fulfillment by Orange Connex Lager, das du im Assistenten erstellt hast. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Herkunft*. . Klicke auf *Hinzufügen*. + . Aktiviere anschließend alle Herkünfte außer eBay. + → *_Wichtig:_* eBay versendet eine eigene Bestätigungsmail mit der entsprechenden Tracking-URL. *_Auszuführende Aktion_* . Klicke auf *Aktion hinzufügen* (icon:plus-square[role=""green""]). . Wähle die Aktion *Kunde > E-Mail versenden*. . Klicke auf *Hinzufügen*. . Klicke innerhalb des Aktionsfenster auf den Pfeil auf der linken Seite, sodass sich die Aktionsübersicht öffnet. . Klicke dort auf *Hinzufügen* (icon:plus-square[role=""green""]). . Wähle im ersten Feld die Option *Auftrag: Versandbestätigung*. . Wähle im zweiten Feld die Option *Kunde*. + → <<#image-procedure-send-email>> zeigt die Übersicht einer fertiggestellten Aktion. . Setze ein Häkchen bei *Aktiv*, um die Ereignisaktion zu aktivieren. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [[image-procedure-send-email]] .Einstellungen innerhalb der Aktion *E-Mail versenden* image::fulfillment/assets/eBay-Fulfillment-Einstellungen-Aktion-E-Mail-versenden.png[width=640, height=360] === Ereignisaktion zum Senden einer Stornierungsanfrage einrichten Du hast die Möglichkeit für einen Outbound-Auftrag eine Stornierungsanfrage zu senden, wenn du den Outbound-Auftrag vorher bereits zu eBay Fulfillment by Orange Connex übermittelt hast und der Outbound-Auftrag akzeptiert wurde. Richte eine Ereignisaktion ein, um diese Anfrage zu übermitteln. [IMPORTANT] .Auftragsnotiz bei nicht erfolgter Stornierung ==== Wenn der Outbound-Auftrag seitens eBay Fulfillment by Orange Connex noch storniert werden kann, setzt dein plentymarkets System den Outbound-Auftrag in den von dir im Assistenten gewählten Status. + Wenn eine Stornierung nicht mehr möglich ist, weil das Paket bereits vollständig verpackt oder sogar schon abgeholt wurde, verbleibt der Outbound-Auftrag im Status der Stornierungsanfrage und dein plentymarkets System erstellt eine Auftragsnotiz, dass die Stornierung nicht möglich war. ==== [instruction] Ereignisaktion zum Senden einer Stornierungsanfrage einrichten: . Öffne im plentymarkets Backend das Menü *Einrichtung » Aufträge » Ereignisse*. . Klicke auf *Ereignisaktion hinzufügen* (icon:plus-square[role=""green""]). . Gib den gewünschten Namen für diese Ereignisaktion ein, z.B. `Stornierungsanfrage senden`. *_Auslösendes Ereignis_* . Wähle aus der Dropdown-Liste *Ereignis* die Option *Auftragsänderung > Statuswechsel*. . Wähle aus der Dropdown-Liste *Status* den Status zum Senden der Stornierungsanfrage an Orange Connex, den du im Assistenten erstellt hast. . *Speichere* (icon:save[role=""green""]) die Einstellungen. *_Filterkriterien für Aufträge_* . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragstyp*. . Klicke auf *Hinzufügen*. . Aktiviere die Option *Auftrag*. . Aktiviere die Option *Lieferauftrag*. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragslager*. . Klicke auf *Hinzufügen*. . Aktiviere das eBay Fulfillment by Orange Connex Lager, das du im Assistenten erstellt hast. *_Auszuführende Aktion_* . Klicke auf *Aktion hinzufügen* (icon:plus-square[role=""green""]). . Wähle die Aktion *Plugins > eBay Fulfillment by Orange Connex: Auftrag stornieren*. . Setze ein Häkchen bei *Aktiv*, um die Ereignisaktion zu aktivieren. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [#versand-erster-artikel-aufträge-splitten] == Versand des ersten Artikels und Splitten von Aufträgen [#versand-erster-artikel] === Versand des ersten Artikels Sobald der Bestand im Lager von eBay Fulfillment by Orange Connex eingegangen und gebucht ist, wird der Bestand des eBay Fulfillment by Orange Connex Lagers in deinem plentymarkets System automatisch aktualisiert. Dazu musst du im Assistenten *eBay Fulfillment by Orange Connex* im Schritt *Datenübertragung und Lagereinstellungen* die Option *Warenbestand importieren* <<#datenuebertragung-lagereinstellungen, aktivieren>>. Ab diesem Moment und unter der Voraussetzung, dass alle Einstellungen in deinem plentymarkets System korrekt vorgenommen wurden, ist es möglich, den ersten Outbound-Auftrag an eBay Fulfillment by Orange Connex zu übertragen. Wenn du Bestellungen für den selben Artikel erhältst, den du zuvor aus deinem eigenen Lager verkauft hast, überträgt das plentymarkets System keinen Outbound-Auftrag an eBay Fulfillment by Orange Connex. Die Übertragung findet so lange nicht statt, bis der Bestand von eBay Fulfillment by Orange Connex für das entsprechende Lager aktualisiert wurde. Falls du dich bereits für ein <> entschieden hast, steht der Abwicklung von eBay Fulfillment by Orange Connex-Aufträgen nichts mehr im Wege. [#auftrage-splitten] === Splitten von Aufträgen Beispiel: * Ein Auftrag enthält 2 Artikel: A und B. * Artikel A befindet sich im eigenen Lager. * Artikel B befindet sich im Lager von eBay Fulfillment by Orange Connex. Ergebnis: * Die Artikel werden in unterschiedliche Lieferaufträge aufgeteilt. [discrete] ==== Aufteilen der Lieferaufträge nach Artikelverfügbarkeit Wähle im Menü *Einrichtung » Aufträge » Einstellungen* in der Zeile *Zuordnung des Lagers* die Einstellung *b) pro Artikelposition kann ein Lager zugeordnet werden* und in der Zeile *Automatische Lagerauswahl* die Einstellung *d) in Abhängigkeit der Lagerpriorität und des höchsten Warenbestandes*. [discrete] ==== Ereignisaktion zum Generieren von Lieferaufträgen einrichten . Öffne im plentymarkets Backend das Menü *Einrichtung » Aufträge » Ereignisse*. . Klicke auf *Ereignisaktion hinzufügen* (icon:plus-square[role=""green""]). . Gib den gewünschten Namen für diese Ereignisaktion ein, z.B. `eBay Fulfillment Splitting`. *_Auslösendes Ereignis_* . Wähle aus der Dropdown-Liste *Ereignis* die Option *Auftragsänderung > Statuswechsel (Versandvorbereitung)*. . *Speichere* (icon:save[role=""green""]) die Einstellungen. *_Filterkriterien für Aufträge_* . Wähle den Filter *Auftrag > Auftragstyp*. . Klicke auf *Hinzufügen*. . Aktiviere die Option *Auftrag*. . Klicke auf *Filter hinzufügen* (icon:plus-square[role=""green""]). . Wähle den Filter *Auftrag > Auftragslager*. . Klicke auf *Hinzufügen*. . Aktiviere in dem Filter die Option *Mehrere Lager pro Auftrag*. *_Auszuführende Aktion_* . Klicke auf *Aktion hinzufügen* (icon:plus-square[role=""green""]). . Wähle die Aktion *Auftrag > Lieferaufträge generieren*. . Klicke auf *Hinzufügen*. . Setze ein Häkchen bei *Aktiv*, um die Ereignisaktion zu aktivieren. . *Speichere* (icon:save[role=""green""]) die Einstellungen. [#faq] == FAQ [#faq-fehlermeldung-gueltigkeit-refresh-token] [.collapseBox] .Ich erhalte eine Fehlermeldung mit ""invalid_grant"" oder ""invalid refresh token"". Was muss ich tun? -- Du erhältst den folgenden (oder einen ähnlichen) Fehler? `{„error“:„invalid_grant“,„error_description“:""Invalid refresh token:` Dann ist der Refresh token von Orange Connex abgelaufen. Nun musst du folgendes tun: . Öffne den Assistenten *eBay Fulfillment by Orange Connex* im Menü *Einrichtung » Assistenten* im Bereich *Integration*. . Öffne den Schritt *Authentifizierung* und gib deine Zugangsdaten erneut ein. + → Ein weitere Hinweis dafür, dass der Refresh token von Orange Connex abgelaufen ist, dass du den Schritt *Authentifizierung* wieder im Assistenten siehst (denn dieser ist sonst nach dem erstmaligen Authentifizieren nicht mehr sichtbar im Assistenten). -- ",12036,False,2466.358547089483,median "/*************************************************************************/ /* gdscript.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* ""Software""), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include ""gdscript.h"" #include ""core/engine.h"" #include ""core/global_constants.h"" #include ""core/io/file_access_encrypted.h"" #include ""core/os/file_access.h"" #include ""core/os/os.h"" #include ""core/project_settings.h"" #include ""gdscript_compiler.h"" /////////////////////////// GDScriptNativeClass::GDScriptNativeClass(const StringName &p_name) { name = p_name; } bool GDScriptNativeClass::_get(const StringName &p_name, Variant &r_ret) const { bool ok; int v = ClassDB::get_integer_constant(name, p_name, &ok); if (ok) { r_ret = v; return true; } else { return false; } } void GDScriptNativeClass::_bind_methods() { ClassDB::bind_method(D_METHOD(""new""), &GDScriptNativeClass::_new); } Variant GDScriptNativeClass::_new() { Object *o = instance(); if (!o) { ERR_EXPLAIN(""Class type: '"" + String(name) + ""' is not instantiable.""); ERR_FAIL_COND_V(!o, Variant()); } Reference *ref = Object::cast_to(o); if (ref) { return REF(ref); } else { return o; } } Object *GDScriptNativeClass::instance() { return ClassDB::instance(name); } GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) { /* STEP 1, CREATE */ GDScriptInstance *instance = memnew(GDScriptInstance); instance->base_ref = p_isref; instance->members.resize(member_indices.size()); instance->script = Ref(this); instance->owner = p_owner; #ifdef DEBUG_ENABLED //needed for hot reloading for (Map::Element *E = member_indices.front(); E; E = E->next()) { instance->member_indices_cache[E->key()] = E->get().index; } #endif instance->owner->set_script_instance(instance); /* STEP 2, INITIALIZE AND CONSRTUCT */ #ifndef NO_THREADS GDScriptLanguage::singleton->lock->lock(); #endif instances.insert(instance->owner); #ifndef NO_THREADS GDScriptLanguage::singleton->lock->unlock(); #endif initializer->call(instance, p_args, p_argcount, r_error); if (r_error.error != Variant::CallError::CALL_OK) { instance->script = Ref(); instance->owner->set_script_instance(NULL); #ifndef NO_THREADS GDScriptLanguage::singleton->lock->lock(); #endif instances.erase(p_owner); #ifndef NO_THREADS GDScriptLanguage::singleton->lock->unlock(); #endif ERR_FAIL_COND_V(r_error.error != Variant::CallError::CALL_OK, NULL); //error constructing } //@TODO make thread safe return instance; } Variant GDScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { /* STEP 1, CREATE */ if (!valid) { r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); } r_error.error = Variant::CallError::CALL_OK; REF ref; Object *owner = NULL; GDScript *_baseptr = this; while (_baseptr->_base) { _baseptr = _baseptr->_base; } ERR_FAIL_COND_V(_baseptr->native.is_null(), Variant()); if (_baseptr->native.ptr()) { owner = _baseptr->native->instance(); } else { owner = memnew(Reference); //by default, no base means use reference } ERR_EXPLAIN(""Can't inherit from a virtual class""); ERR_FAIL_COND_V(!owner, Variant()); Reference *r = Object::cast_to(owner); if (r) { ref = REF(r); } GDScriptInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error); if (!instance) { if (ref.is_null()) { memdelete(owner); //no owner, sorry } return Variant(); } if (ref.is_valid()) { return ref; } else { return owner; } } bool GDScript::can_instance() const { #ifdef TOOLS_ENABLED return valid && (tool || ScriptServer::is_scripting_enabled()); #else return valid; #endif } Ref