Skip to content

Instantly share code, notes, and snippets.

@ipid
Last active January 15, 2020 15:24
Show Gist options
  • Save ipid/68ff6e1f44076ba0fff75ed620baa844 to your computer and use it in GitHub Desktop.
Save ipid/68ff6e1f44076ba0fff75ed620baa844 to your computer and use it in GitHub Desktop.
Simple warning light flashing in your terminal. Written in C++17 with ncurses.
/*
Simple warning light flashing in your terminal.
Compile with the following arguments:
<YOUR COMPILER> --std=c++17 -O2 -lcurses -o warn-light warn-light.cc
*/
#include <ncurses.h>
#include <stdint.h>
#include <unistd.h>
#include <array>
#include <iostream>
constexpr uint64_t kDelayTimeMs = 100;
void fillScreenWithColorPair(int colorPair) {
int height, width;
getmaxyx(stdscr, height, width);
attron(COLOR_PAIR(colorPair));
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
mvaddch(y, x, ' ');
}
}
attroff(COLOR_PAIR(colorPair));
refresh();
}
int curses_main() {
// Curcularly display these color pairs
std::array<int, 6> colorPairs = {0, 1, 0, 2, 0, 3};
for (int i = 0;; i = (i + 1) % colorPairs.size()) {
fillScreenWithColorPair(colorPairs[i]);
usleep(1000 * kDelayTimeMs);
}
return 0;
}
int main() {
// Initialize the terminal
initscr();
cbreak();
noecho();
keypad(stdscr, true);
clear();
// Initialize the color mechanism
start_color();
use_default_colors();
const auto dummyColor = COLOR_BLACK;
init_pair(1, dummyColor, COLOR_GREEN);
init_pair(2, dummyColor, COLOR_RED);
init_pair(3, dummyColor, COLOR_BLUE);
// Check if colors are too few
if (COLORS <= 2) {
endwin();
std::cout << "ERROR: Too few colors.\n" << std::endl;
return 1;
}
int res = curses_main();
endwin();
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment