mirror of
https://github.com/esphome/esphome.git
synced 2026-11-18 19:15:59 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
930cef71d2 | ||
|
|
9898eb124a | ||
|
|
cac0e29421 |
No files matched your search
@@ -0,0 +1,128 @@
|
||||
// Requests a Copilot code review on a pull request. A failed request only
|
||||
// warns: Copilot review is advisory and must never block the PR.
|
||||
//
|
||||
// GitHub answers a request it will not act on (one made by an identity without
|
||||
// a Copilot seat, which includes GITHUB_TOKEN and GitHub Apps when the PR
|
||||
// author has no Copilot access) with a success and no review, so the timeline
|
||||
// is read back to confirm the request was recorded.
|
||||
|
||||
const COPILOT_REVIEWER = "copilot-pull-request-reviewer[bot]";
|
||||
// The timeline names the reviewer by its display login; the reviews API uses
|
||||
// the bot account.
|
||||
const COPILOT_LOGINS = new Set(["Copilot", COPILOT_REVIEWER]);
|
||||
|
||||
module.exports = async ({ github, context, core }) => {
|
||||
const pull = context.payload.pull_request;
|
||||
if (pull.user?.type === "Bot") {
|
||||
core.info(`#${pull.number} was opened by a bot; skipping the Copilot review.`);
|
||||
return;
|
||||
}
|
||||
await requestCopilotReview({ github, core, ...context.repo, prNumber: pull.number });
|
||||
};
|
||||
|
||||
async function requestCopilotReview({ github, core, owner, repo, prNumber }) {
|
||||
const readTimeline = () =>
|
||||
github.paginate(github.rest.issues.listEventsForTimeline, {
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const { login: requester, stop } = await identify({ github, core });
|
||||
if (stop) return;
|
||||
let before = null;
|
||||
if (requester) {
|
||||
try {
|
||||
before = await readTimeline();
|
||||
} catch (err) {
|
||||
core.warning(
|
||||
`Could not read the timeline of #${prNumber}, so the request goes unconfirmed: ${err.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await github.rest.pulls.requestReviewers({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: prNumber,
|
||||
reviewers: [COPILOT_REVIEWER],
|
||||
});
|
||||
} catch (err) {
|
||||
core.warning(`Could not request a Copilot review on #${prNumber}: ${err.message}`);
|
||||
return;
|
||||
}
|
||||
if (!before) return;
|
||||
let events;
|
||||
try {
|
||||
events = await readTimeline();
|
||||
} catch (err) {
|
||||
core.warning(
|
||||
`Requested a Copilot review on #${prNumber} but could not confirm it: ${err.message}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
const seen = new Set(before.map((event) => event.id));
|
||||
const copilotRequests = events.filter(
|
||||
(event) =>
|
||||
event.event === "review_requested" &&
|
||||
COPILOT_LOGINS.has(event.requested_reviewer?.login)
|
||||
);
|
||||
// Ours is a request this token's account filed that was not there before.
|
||||
if (
|
||||
copilotRequests.some(
|
||||
(event) => event.actor?.login === requester && !seen.has(event.id)
|
||||
)
|
||||
) {
|
||||
core.info(`Requested a Copilot review on #${prNumber}.`);
|
||||
return;
|
||||
}
|
||||
// The latest request or removal decides whether a review is still queued.
|
||||
const last = events
|
||||
.filter(
|
||||
(event) =>
|
||||
(event.event === "review_requested" ||
|
||||
event.event === "review_request_removed") &&
|
||||
COPILOT_LOGINS.has(event.requested_reviewer?.login)
|
||||
)
|
||||
.at(-1);
|
||||
if (last?.event === "review_requested" && !reviewedSince(events, last.created_at)) {
|
||||
core.info(
|
||||
`A Copilot review requested by ${last.actor?.login} is still pending on #${prNumber}.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
core.warning(
|
||||
`GitHub accepted the Copilot review request on #${prNumber} but recorded none; ` +
|
||||
`${requester} likely has no Copilot seat.`
|
||||
);
|
||||
}
|
||||
|
||||
// The account the token belongs to: { login }, {} when it can't be told
|
||||
// (the request goes ahead unconfirmed), or { stop: true } when the token is rejected.
|
||||
async function identify({ github, core }) {
|
||||
try {
|
||||
const { data } = await github.rest.users.getAuthenticated();
|
||||
return { login: data.login };
|
||||
} catch (err) {
|
||||
// An expired or revoked token fails loudly so someone rotates it.
|
||||
if (err.status === 401) {
|
||||
core.setFailed(
|
||||
`COPILOT_REVIEW_TOKEN was rejected (${err.message}); rotate esphome-review-bot's token.`
|
||||
);
|
||||
return { stop: true };
|
||||
}
|
||||
core.warning(
|
||||
`Could not identify the requesting account, so the request goes unconfirmed: ${err.message}`
|
||||
);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function reviewedSince(events, since) {
|
||||
return events.some(
|
||||
(event) =>
|
||||
event.event === "reviewed" &&
|
||||
COPILOT_LOGINS.has(event.user?.login) &&
|
||||
Date.parse(event.submitted_at) >= Date.parse(since)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "request-copilot-review",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"test": "node --test tests/*.test.js"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const requestCopilotReview = require('../index');
|
||||
|
||||
const REPO = { owner: 'esphome', repo: 'esphome' };
|
||||
|
||||
const OLD = '2020-01-01T00:00:00Z';
|
||||
const LATER = '2020-01-01T00:05:00Z';
|
||||
// The account the workflow's token belongs to.
|
||||
const REQUESTER = 'esphome-review-bot';
|
||||
// "ours" is a request filed by REQUESTER; anything else stands for the ruleset or a maintainer.
|
||||
const copilotRequest = (id, by, createdAt = LATER) => ({
|
||||
id,
|
||||
event: 'review_requested',
|
||||
actor: { login: by === 'ours' ? REQUESTER : 'someone', type: 'User' },
|
||||
requested_reviewer: { login: 'Copilot' },
|
||||
created_at: createdAt,
|
||||
});
|
||||
const copilotReview = (id, submittedAt, login = 'Copilot') => ({
|
||||
id,
|
||||
event: 'reviewed',
|
||||
user: { login },
|
||||
submitted_at: submittedAt,
|
||||
});
|
||||
const copilotRemoval = (id) => ({
|
||||
id,
|
||||
event: 'review_request_removed',
|
||||
requested_reviewer: { login: 'Copilot' },
|
||||
created_at: LATER,
|
||||
});
|
||||
|
||||
// `before` and `after` are the timeline reads around the request, `timeline` sets both, and
|
||||
// `timelineError` makes that read throw.
|
||||
function makeGithub(opts = {}) {
|
||||
const calls = [];
|
||||
const reads = [
|
||||
{ name: 'before', events: opts.timeline ?? opts.before ?? [] },
|
||||
{ name: 'after', events: opts.timeline ?? opts.after ?? [copilotRequest(1, 'ours')] },
|
||||
];
|
||||
const listEventsForTimeline = () => {};
|
||||
return {
|
||||
calls,
|
||||
github: {
|
||||
paginate: async (fn) => {
|
||||
assert.equal(fn, listEventsForTimeline);
|
||||
const read = reads.shift();
|
||||
assert.ok(read, 'the timeline is read at most twice');
|
||||
if (opts.timelineError === read.name) throw new Error('secondary rate limit');
|
||||
return read.events;
|
||||
},
|
||||
rest: {
|
||||
users: {
|
||||
getAuthenticated: async () => {
|
||||
if (opts.whoamiStatus) {
|
||||
throw Object.assign(new Error('Bad credentials'), { status: opts.whoamiStatus });
|
||||
}
|
||||
return { data: { login: REQUESTER } };
|
||||
},
|
||||
},
|
||||
issues: { listEventsForTimeline },
|
||||
pulls: {
|
||||
requestReviewers: async (args) => {
|
||||
if (opts.fail) throw new Error('Reviews may only be requested from collaborators');
|
||||
calls.push(args);
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeCore() {
|
||||
const warnings = [];
|
||||
const infos = [];
|
||||
const failures = [];
|
||||
return {
|
||||
warnings,
|
||||
infos,
|
||||
failures,
|
||||
core: {
|
||||
info: (m) => void infos.push(m),
|
||||
warning: (m) => void warnings.push(m),
|
||||
setFailed: (m) => void failures.push(m),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function run(githubOpts, type = 'User') {
|
||||
const { github, calls } = makeGithub(githubOpts);
|
||||
const { core, infos, warnings, failures } = makeCore();
|
||||
const context = { repo: REPO, payload: { pull_request: { number: 9, user: { type } } } };
|
||||
await requestCopilotReview({ github, context, core });
|
||||
return { calls, infos, warnings, failures };
|
||||
}
|
||||
|
||||
test('a PR event requests a Copilot review', async () => {
|
||||
const { calls, infos, warnings } = await run();
|
||||
assert.deepEqual(calls, [{ ...REPO, pull_number: 9, reviewers: ['copilot-pull-request-reviewer[bot]'] }]);
|
||||
assert.deepEqual(warnings, []);
|
||||
assert.match(infos[0], /Requested a Copilot review on #9/);
|
||||
});
|
||||
|
||||
test('bot PRs are skipped', async () => {
|
||||
const { calls } = await run({}, 'Bot');
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test('a failed request warns instead of failing', async () => {
|
||||
const { warnings, failures } = await run({ fail: true });
|
||||
assert.match(warnings[0], /Could not request a Copilot review on #9/);
|
||||
assert.deepEqual(failures, []);
|
||||
});
|
||||
|
||||
test('an accepted request GitHub never recorded warns', async () => {
|
||||
const { warnings } = await run({ after: [{ id: 1, event: 'labeled' }] });
|
||||
assert.match(warnings[0], /recorded none/);
|
||||
});
|
||||
|
||||
test('a request filed by another account does not confirm ours', async () => {
|
||||
const { warnings } = await run({ after: [copilotRequest(1, 'other'), copilotReview(2, LATER)] });
|
||||
assert.match(warnings[0], /recorded none/);
|
||||
});
|
||||
|
||||
test('an earlier request by the same account does not confirm this one', async () => {
|
||||
const { warnings } = await run({ timeline: [copilotRequest(1, 'ours', OLD), copilotReview(2, LATER)] });
|
||||
assert.match(warnings[0], /recorded none/);
|
||||
});
|
||||
|
||||
test('a Copilot review still pending is logged, not warned', async () => {
|
||||
const { infos, warnings } = await run({ timeline: [copilotReview(1, OLD), copilotRequest(2, 'other')] });
|
||||
assert.deepEqual(warnings, []);
|
||||
assert.match(infos[0], /requested by someone is still pending on #9/);
|
||||
});
|
||||
|
||||
test('a Copilot request that was removed is not pending', async () => {
|
||||
const { warnings } = await run({ timeline: [copilotRequest(1, 'other'), copilotRemoval(2)] });
|
||||
assert.match(warnings[0], /recorded none/);
|
||||
});
|
||||
|
||||
test('a completed review under the bot account login ends the pending request', async () => {
|
||||
const timeline = [
|
||||
copilotRequest(1, 'other', OLD),
|
||||
copilotReview(2, LATER, 'copilot-pull-request-reviewer[bot]'),
|
||||
];
|
||||
const { warnings } = await run({ timeline });
|
||||
assert.match(warnings[0], /recorded none/);
|
||||
});
|
||||
|
||||
test('a failed timeline read after the request warns instead of failing', async () => {
|
||||
const { calls, warnings } = await run({ timelineError: 'after' });
|
||||
assert.equal(calls.length, 1);
|
||||
assert.match(warnings[0], /could not confirm it: secondary rate limit/);
|
||||
});
|
||||
|
||||
test('a failed baseline read still requests the review, unconfirmed', async () => {
|
||||
const { calls, warnings } = await run({ timelineError: 'before' });
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0], /goes unconfirmed: secondary rate limit/);
|
||||
});
|
||||
|
||||
test('a rejected token fails the run so it gets rotated', async () => {
|
||||
const { calls, failures } = await run({ whoamiStatus: 401 });
|
||||
assert.equal(calls.length, 0);
|
||||
assert.match(failures[0], /COPILOT_REVIEW_TOKEN was rejected/);
|
||||
});
|
||||
|
||||
test('a failed account lookup still requests the review, unconfirmed', async () => {
|
||||
const { calls, warnings, failures } = await run({ whoamiStatus: 502 });
|
||||
assert.equal(calls.length, 1);
|
||||
assert.deepEqual(failures, []);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0], /Could not identify the requesting account/);
|
||||
});
|
||||
@@ -74,6 +74,9 @@ workflows:
|
||||
- 'docker/login-action@v4.8.0'
|
||||
- 'docker/setup-buildx-action@v4.4.1'
|
||||
- 'pypa/gh-action-pypi-publish@v1.14.3'
|
||||
'.github/workflows/request-copilot-review.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'actions/github-script@v9.0.0'
|
||||
'.github/workflows/stale.yml': []
|
||||
'.github/workflows/status-check-labels.yml':
|
||||
- 'actions/github-script@v9.0.0'
|
||||
|
||||
@@ -25,3 +25,14 @@ jobs:
|
||||
- name: Run tests
|
||||
working-directory: .github/scripts/auto-label-pr
|
||||
run: npm test
|
||||
|
||||
test-request-copilot-review:
|
||||
name: Test request-copilot-review script
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code from GitHub
|
||||
uses: actions/checkout@v7.0.1
|
||||
|
||||
- name: Run tests
|
||||
working-directory: .github/scripts/request-copilot-review
|
||||
run: npm test
|
||||
@@ -0,0 +1,56 @@
|
||||
name: Request Copilot review
|
||||
|
||||
# Requests a Copilot code review when a ready pull request against dev is
|
||||
# opened, reopened or marked ready for review; like the ruleset, not on every
|
||||
# push. The ruleset reviews these too, but it runs the review as the PR author
|
||||
# (or whoever marked it ready), so a contributor without Copilot access gets
|
||||
# none. This runs it as esphome-review-bot, which needs a Copilot seat and
|
||||
# Triage on this repo. COPILOT_REVIEW_TOKEN is an org secret holding its
|
||||
# fine-grained token (Pull requests read and write) and expires: when it is
|
||||
# rejected the run fails, and an org owner signs in as the bot, creates a new
|
||||
# one and replaces the secret.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
- ready_for_review
|
||||
branches:
|
||||
- dev
|
||||
|
||||
permissions: {}
|
||||
|
||||
# Overlapping runs could each take the other's request as their own confirmation.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
request:
|
||||
name: Request Copilot review
|
||||
runs-on: ubuntu-latest
|
||||
# Forks have no review bot token, bot PRs (Dependabot) get no repo secrets,
|
||||
# and drafts are not reviewed.
|
||||
if: >-
|
||||
github.repository == 'esphome/esphome'
|
||||
&& github.event.pull_request.user.type != 'Bot'
|
||||
&& !github.event.pull_request.draft
|
||||
permissions:
|
||||
contents: read # to check out the script below
|
||||
steps:
|
||||
# Checks out the base repo (trusted) only to load the script below,
|
||||
# never the PR's code - this job holds the review bot's token.
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
sparse-checkout: .github/scripts/request-copilot-review
|
||||
persist-credentials: false
|
||||
|
||||
- name: Request Copilot review
|
||||
uses: actions/github-script@v9.0.0
|
||||
with:
|
||||
github-token: ${{ secrets.COPILOT_REVIEW_TOKEN }}
|
||||
script: |
|
||||
const script = require('./.github/scripts/request-copilot-review/index.js');
|
||||
await script({ github, context, core });
|
||||
@@ -151,7 +151,8 @@ Color color_from_light_color_values(LightColorValues val) {
|
||||
auto r = to_uint8_scale(val.get_color_brightness() * val.get_red());
|
||||
auto g = to_uint8_scale(val.get_color_brightness() * val.get_green());
|
||||
auto b = to_uint8_scale(val.get_color_brightness() * val.get_blue());
|
||||
auto w = to_uint8_scale(val.get_white());
|
||||
// White keeps its default of 100% in RGB mode, where it must not count as the strongest channel
|
||||
uint8_t w = val.get_color_mode() == ColorMode::RGB ? 0 : to_uint8_scale(val.get_white());
|
||||
return Color(r, g, b, w);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,45 @@ uint8_t ESPColorCorrection::gamma_correct_(uint8_t value) const {
|
||||
return result;
|
||||
}
|
||||
|
||||
uint16_t ESPColorCorrection::gamma_level_(uint8_t value) const {
|
||||
if (this->gamma_table_ == nullptr)
|
||||
return value * 257;
|
||||
return progmem_read_uint16(&this->gamma_table_[value]);
|
||||
}
|
||||
|
||||
uint8_t ESPColorCorrection::gamma_round_(uint8_t value) const {
|
||||
if (this->gamma_table_ == nullptr)
|
||||
return value;
|
||||
return (progmem_read_uint16(&this->gamma_table_[value]) + 128) / 257;
|
||||
}
|
||||
|
||||
// Lighting every non-zero channel instead would turn a dim red with a trace of green into yellow
|
||||
Color ESPColorCorrection::correct_dark_pixel_(Color color) const {
|
||||
// Compared without the local brightness, which is the same for every channel: the scaled 8-bit
|
||||
// values are too coarse to compare at the lowest brightness
|
||||
uint16_t strengths[4];
|
||||
uint16_t max_strength = 0;
|
||||
bool lit = false;
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
strengths[i] = color[i] * this->max_brightness_[i];
|
||||
max_strength = std::max(max_strength, strengths[i]);
|
||||
lit |= esp_scale8_twice(color[i], this->max_brightness_[i], this->local_brightness_) != 0;
|
||||
}
|
||||
Color res;
|
||||
if (!lit)
|
||||
return res;
|
||||
// Stretch the strongest channel to full scale and round the others against it; the table is too
|
||||
// coarse to compare its lowest levels
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
if (strengths[i] == max_strength) {
|
||||
res[i] = 1;
|
||||
} else if (strengths[i] != 0) {
|
||||
res[i] = this->gamma_level_(strengths[i] * 255 / max_strength) >= 0x8000 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
uint8_t ESPColorCorrection::gamma_uncorrect_(uint8_t value) const {
|
||||
if (this->gamma_table_ == nullptr)
|
||||
return value;
|
||||
|
||||
@@ -40,10 +40,13 @@ class ESPColorCorrection {
|
||||
#endif
|
||||
void set_gamma_table(const uint16_t *table) { this->gamma_table_ = table; }
|
||||
|
||||
/// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma, keeping a lit pixel lit
|
||||
inline Color color_correct(Color color) const ESPHOME_ALWAYS_INLINE {
|
||||
// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma
|
||||
return Color(this->color_correct_red(color.red), this->color_correct_green(color.green),
|
||||
this->color_correct_blue(color.blue), this->color_correct_white(color.white));
|
||||
Color res(this->round_channel_(COLOR_CHANNEL_R, color.red), this->round_channel_(COLOR_CHANNEL_G, color.green),
|
||||
this->round_channel_(COLOR_CHANNEL_B, color.blue), this->round_channel_(COLOR_CHANNEL_W, color.white));
|
||||
if (res.raw_32 == 0 && color.raw_32 != 0)
|
||||
res = this->correct_dark_pixel_(color);
|
||||
return Color(this->limit_(res.red), this->limit_(res.green), this->limit_(res.blue), this->limit_(res.white));
|
||||
}
|
||||
inline uint8_t color_correct_red(uint8_t red) const ESPHOME_ALWAYS_INLINE {
|
||||
return this->color_correct_channel(COLOR_CHANNEL_R, red);
|
||||
@@ -90,6 +93,15 @@ class ESPColorCorrection {
|
||||
#endif
|
||||
return res;
|
||||
}
|
||||
inline uint8_t round_channel_(uint8_t channel, uint8_t value) const ESPHOME_ALWAYS_INLINE {
|
||||
return this->gamma_round_(esp_scale8_twice(value, this->max_brightness_[channel], this->local_brightness_));
|
||||
}
|
||||
/// Forward gamma as the table's 16-bit level
|
||||
uint16_t gamma_level_(uint8_t value) const;
|
||||
/// Forward gamma rounded to uint8, where a low level becomes 0
|
||||
uint8_t gamma_round_(uint8_t value) const;
|
||||
/// The levels of a pixel whose channels all round to 0: 1 for its strongest channels, unless it is black
|
||||
Color correct_dark_pixel_(Color color) const;
|
||||
/// Forward gamma: read uint16 PROGMEM table, convert to uint8
|
||||
uint8_t gamma_correct_(uint8_t value) const;
|
||||
/// Reverse gamma and limit for one stored level
|
||||
|
||||
@@ -36,6 +36,10 @@ class ESPColorAccessor {
|
||||
#if defined(USE_LIGHT_PARTITION) && defined(USE_LIGHT_POWER_ESTIMATION)
|
||||
virtual const ESPColorCorrection *get_color_correction_internal(int32_t index) const { return nullptr; }
|
||||
#endif
|
||||
#ifdef USE_LIGHT_PARTITION
|
||||
// For internal use only: whether the LED at `index` stores a white level.
|
||||
virtual bool has_white_internal(int32_t index) const { return true; }
|
||||
#endif
|
||||
};
|
||||
|
||||
/// Color accessor that is completely at peace with the void of nothingness.
|
||||
@@ -78,6 +82,10 @@ class BufferColorAccessor : public ESPColorAccessor {
|
||||
}
|
||||
void set_effect_data(int32_t index, uint8_t value) override { this->effect_data[index] = value; }
|
||||
|
||||
#ifdef USE_LIGHT_PARTITION
|
||||
bool has_white_internal(int32_t index) const override { return this->channel_colors.has_white(); }
|
||||
#endif
|
||||
|
||||
/// Allocate a zeroed block of buffer_bytes() plus `extra_bytes` for the caller, which start at
|
||||
/// `effect_data + num_leds`, and pass it to set_buffer(). Returns false if it failed.
|
||||
bool allocate(RAMAllocator<uint8_t> &allocator, size_t num_leds, size_t extra_bytes = 0) {
|
||||
@@ -151,7 +159,12 @@ class CorrectedBufferColorAccessor final : public BufferColorAccessor {
|
||||
return this->color_correction->color_uncorrect_channel(channel, this->get_channel_raw(index, channel));
|
||||
}
|
||||
|
||||
void set(int32_t index, Color color) override { this->set_raw(index, this->color_correction->color_correct(color)); }
|
||||
void set(int32_t index, Color color) override {
|
||||
// A white level the strip cannot show must not count as the pixel's strongest channel
|
||||
if (!this->channel_colors.has_white())
|
||||
color.white = 0;
|
||||
this->set_raw(index, this->color_correction->color_correct(color));
|
||||
}
|
||||
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
|
||||
this->set_channel_raw(index, channel, this->color_correction->color_correct_channel(channel, value));
|
||||
}
|
||||
@@ -273,6 +286,10 @@ class ESPColorView final : public ESPColorSettable {
|
||||
return this->accessor_->get_color_correction_internal(this->index_);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_LIGHT_PARTITION
|
||||
// This method is for internal use only.
|
||||
bool has_white_internal() const { return this->accessor_->has_white_internal(this->index_); }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
ESPColorAccessor *const accessor_;
|
||||
|
||||
@@ -83,6 +83,9 @@ class PartitionLightOutput final : public light::AddressableLight {
|
||||
|
||||
void set(int32_t index, Color color) override {
|
||||
light::ESPColorView color_view = this->parent_->get_color_view_(index);
|
||||
// A white level the LED cannot show must not count as the pixel's strongest channel
|
||||
if (!color_view.has_white_internal()) // NOLINT
|
||||
color.white = 0;
|
||||
color_view.set_raw(this->parent_->get_color_correction_(color_view)->color_correct(color));
|
||||
}
|
||||
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
|
||||
@@ -98,6 +101,10 @@ class PartitionLightOutput final : public light::AddressableLight {
|
||||
this->parent_->get_color_view_(index).set_effect_data(value);
|
||||
}
|
||||
|
||||
bool has_white_internal(int32_t index) const override { // NOLINT
|
||||
return this->parent_->get_color_view_(index).has_white_internal();
|
||||
}
|
||||
|
||||
#ifdef USE_LIGHT_POWER_ESTIMATION
|
||||
const light::ESPColorCorrection *get_color_correction_internal(int32_t index) const override { // NOLINT
|
||||
return this->parent_->get_color_correction_(this->parent_->get_color_view_(index));
|
||||
|
||||
@@ -98,7 +98,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.positive_time_period_milliseconds,
|
||||
cv.Range(max=cv.TimePeriod(milliseconds=5000)),
|
||||
),
|
||||
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=True): cv.boolean,
|
||||
cv.Optional(CONF_FIXED_DELAY, default="0us"): cv.All(
|
||||
cv.positive_time_period_microseconds,
|
||||
cv.Range(max=cv.TimePeriod(microseconds=10000)),
|
||||
|
||||
@@ -61,7 +61,7 @@ class SendspinMediaSource final : public SendspinChild,
|
||||
|
||||
bool cached_muted_{false};
|
||||
bool pending_start_{false};
|
||||
bool static_delay_adjustable_{false};
|
||||
bool static_delay_adjustable_{true};
|
||||
};
|
||||
|
||||
} // namespace esphome::sendspin_
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/components/light/esp_color_correction.h"
|
||||
#include "esphome/components/light/esp_color_view.h"
|
||||
|
||||
namespace esphome::light::testing {
|
||||
|
||||
@@ -67,6 +68,69 @@ TEST(GammaCorrection, DeadZoneFixedAtGamma28) {
|
||||
}
|
||||
}
|
||||
|
||||
// A whole pixel keeps its colour when dim: only the strongest channel is lifted to 1.
|
||||
TEST(GammaCorrection, DimPixelKeepsDominantChannel) {
|
||||
GammaFixture fixture(2.8);
|
||||
fixture.correction.set_local_brightness(13);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 30, 0, 0)), Color(1, 0, 0, 0));
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(0, 0, 255, 30)), Color(0, 0, 1, 0));
|
||||
}
|
||||
|
||||
// Orange at 2% brightness and below: the table reads 1 for both channels there, and at the lowest
|
||||
// step both scale to the same 8-bit value, so neither can be used to compare them.
|
||||
TEST(GammaCorrection, VeryDimPixelKeepsDominantChannel) {
|
||||
GammaFixture fixture(2.8);
|
||||
for (uint8_t brightness : {1, 2, 3, 4, 5, 6}) {
|
||||
fixture.correction.set_local_brightness(brightness);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 130, 0, 0)), Color(1, 0, 0, 0))
|
||||
<< "brightness=" << int(brightness);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(GammaCorrection, DimPixelKeepsSimilarChannels) {
|
||||
GammaFixture fixture(2.8);
|
||||
fixture.correction.set_local_brightness(13);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 255, 255, 0)), Color(1, 1, 1, 0));
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 230, 0, 0)), Color(1, 1, 0, 0));
|
||||
fixture.correction.set_local_brightness(1);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 250, 250, 0)), Color(1, 1, 1, 0));
|
||||
}
|
||||
|
||||
// A channel that color_correct sets to 0% stays dark even when it is the strongest in the pixel.
|
||||
TEST(GammaCorrection, DimPixelLeavesDisabledChannelDark) {
|
||||
GammaFixture fixture(2.8);
|
||||
fixture.correction.set_max_brightness(Color(255, 0, 255, 255));
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(1, 255, 0, 0)), Color(1, 0, 0, 0));
|
||||
}
|
||||
|
||||
// A strip without white drops the white level before the pixel is rounded, so it cannot outrank red.
|
||||
TEST(GammaCorrection, UnusedWhiteDoesNotDarkenRgbStrip) {
|
||||
GammaFixture fixture(2.8);
|
||||
fixture.correction.set_local_brightness(13);
|
||||
std::array<uint8_t, 3> color_data{};
|
||||
std::array<uint8_t, 1> effect_data{};
|
||||
CorrectedBufferColorAccessor accessor(color_data.data(), effect_data.data(), ChannelColors{0, 1, 2},
|
||||
&fixture.correction);
|
||||
accessor.set(0, Color(128, 0, 0, 255));
|
||||
EXPECT_EQ(color_data, (std::array<uint8_t, 3>{1, 0, 0}));
|
||||
}
|
||||
|
||||
TEST(GammaCorrection, LitPixelDropsChannelThatRoundsToZero) {
|
||||
GammaFixture fixture(2.8);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 5, 0, 0)), Color(255, 0, 0, 0));
|
||||
}
|
||||
|
||||
// The pixel-level form of esphome/esphome#18842: a non-zero pixel never goes fully dark.
|
||||
TEST(GammaCorrection, NonZeroPixelStaysLit) {
|
||||
for (double gamma : {1.0, 2.2, 2.8, 4.0}) {
|
||||
GammaFixture fixture(gamma);
|
||||
for (int i = 1; i < 256; i++) {
|
||||
EXPECT_GE(fixture.correction.color_correct(Color(i, 0, 0, 0)).red, 1) << "gamma=" << gamma << " index=" << i;
|
||||
}
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(0, 0, 0, 0)), Color(0, 0, 0, 0)) << "gamma=" << gamma;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(GammaCorrection, ReverseSearchFindsLargestIndexLessEqualTarget) {
|
||||
auto table = build_gamma_table(2.8);
|
||||
for (uint16_t target : {0, 128, 129, 135, 1000, 32768, 65535}) {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import esphome.codegen as cg
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
async def to_code_testing(config):
|
||||
# The accessor hooks that partitions use, and the gamma table of the light under test
|
||||
cg.add_define("USE_LIGHT_PARTITION")
|
||||
cg.add_define("USE_LIGHT_GAMMA_LUT")
|
||||
|
||||
manifest.to_code = to_code_testing
|
||||
manifest.dependencies = manifest.dependencies + ["light"]
|
||||
@@ -0,0 +1,56 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/components/light/addressable_light.h"
|
||||
#include "esphome/components/light/light_state.h"
|
||||
#include "esphome/components/partition/light_partition.h"
|
||||
|
||||
namespace esphome::partition::testing {
|
||||
|
||||
namespace {
|
||||
|
||||
// One RGB pixel in memory
|
||||
class RgbStrip : public light::AddressableLight {
|
||||
public:
|
||||
RgbStrip()
|
||||
: internal_accessor_(this->buffer_.data(), this->buffer_.data() + 3, light::ChannelColors{0, 1, 2},
|
||||
&this->correction_) {
|
||||
this->accessor_ = &this->internal_accessor_;
|
||||
}
|
||||
int32_t size() const override { return 1; }
|
||||
void clear_effect_data() override {}
|
||||
light::LightTraits get_traits() override { return {}; }
|
||||
void write_state(light::LightState *state) override {}
|
||||
|
||||
protected:
|
||||
std::array<uint8_t, 4> buffer_{};
|
||||
light::CorrectedBufferColorAccessor internal_accessor_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// The partition corrects a pixel before the strip drops its white level, so it has to drop it first.
|
||||
TEST(PartitionWhite, UnusedWhiteDoesNotDarkenRgbSegment) {
|
||||
light::GammaTable table{};
|
||||
for (int i = 1; i < 256; i++)
|
||||
table.lut[i] = std::max(1.0, std::round(std::pow(i / 255.0, 2.8) * 65535.0));
|
||||
table.gamma_x100 = 280;
|
||||
|
||||
RgbStrip strip;
|
||||
light::LightState strip_state(&strip);
|
||||
PartitionLightOutput partition({AddressableSegment(&strip_state, 0, 1, false)});
|
||||
light::LightState partition_state(&partition);
|
||||
partition_state.set_gamma_table(&table);
|
||||
partition.setup_state(&partition_state);
|
||||
partition_state.current_values.set_state(1.0f);
|
||||
partition_state.current_values.set_brightness(13 / 255.0f);
|
||||
partition.update_state(&partition_state);
|
||||
|
||||
partition[0] = Color(128, 0, 0, 255);
|
||||
EXPECT_EQ(strip[0].get_raw(), Color(1, 0, 0, 0));
|
||||
}
|
||||
|
||||
} // namespace esphome::partition::testing
|
||||
Reference in new issue
Block a user