通过ping某个服务器,检测设备是否internet
是联通的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#define dbg(fmt, args...) printf("\033[1m[ %s ] %03d: "fmt"\033[0m\n\r", __FUNCTION__, __LINE__, ##args)
static unsigned int check_interval = 1;
#define INTERVAL_MAX (1024)
#define INTERVAL_MIN (2)
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define LED_RED "/sys/class/leds/red:system/trigger"
#define LED_GREEN "/sys/class/leds/green:system/trigger"
#define LED_BLUE "/sys/class/leds/blue:system/trigger"
#define GPIO_RED "/sys/class/leds/red:system/brightness"
#define GPIO_GREEN "/sys/class/leds/green:system/brightness"
#define GPIO_BLUE "/sys/class/leds/blue:system/brightness"
#define ROOT_SVR "A.root-servers.net"
static void set_led(int online)
{
static int last_state = 2;
char cmd[128] = {0};
int cur_state = online ? 1 : 0;
if (last_state == cur_state) {
return;
}
if (online) {
/*set green/white*/
last_state = 1;
if (0 == access(LED_RED, F_OK) &&
0 == access(LED_GREEN, F_OK) &&
0 == access(LED_BLUE, F_OK)) {
snprintf(cmd, sizeof(cmd), "echo none > %s", LED_RED);
system(cmd);
snprintf(cmd, sizeof(cmd), "echo default-on > %s", LED_GREEN);
system(cmd);
snprintf(cmd, sizeof(cmd), "echo none > %s", LED_BLUE);
system(cmd);
} else if (0 == access(GPIO_RED, F_OK) &&
0 == access(GPIO_GREEN, F_OK) &&
0 == access(GPIO_BLUE, F_OK)) {
snprintf(cmd, sizeof(cmd), "echo 0 > %s", GPIO_RED);
system(cmd);
snprintf(cmd, sizeof(cmd), "echo 1 > %s", GPIO_GREEN);
system(cmd);
snprintf(cmd, sizeof(cmd), "echo 0 > %s", GPIO_BLUE);
system(cmd);
}
} else {
last_state = 0;
/*set red*/
if (0 == access(LED_RED, F_OK) &&
0 == access(LED_GREEN, F_OK) &&
0 == access(LED_BLUE, F_OK)) {
snprintf(cmd, sizeof(cmd), "echo default-on > %s", LED_RED);
system(cmd);
snprintf(cmd, sizeof(cmd), "echo none > %s", LED_GREEN);
system(cmd);
snprintf(cmd, sizeof(cmd), "echo none > %s", LED_BLUE);
system(cmd);
} else if (0 == access(GPIO_RED, F_OK) &&
0 == access(GPIO_GREEN, F_OK) &&
0 == access(GPIO_BLUE, F_OK)) {
snprintf(cmd, sizeof(cmd), "echo 1 > %s", GPIO_RED);
system(cmd);
snprintf(cmd, sizeof(cmd), "echo 0 > %s", GPIO_GREEN);
system(cmd);
snprintf(cmd, sizeof(cmd), "echo 0 > %s", GPIO_BLUE);
system(cmd);
}
}
return;
}
static int led_check(void)
{
int ret = 1;
char cmd[128] = {0};
snprintf(cmd, sizeof(cmd), "ping %s -c 1 -w 1 -4", ROOT_SVR);
ret = system(cmd);
set_led(0 == ret);
return ret;
}
int main(int argc, char const *argv[])
{
while (1) {
check_interval = MAX(INTERVAL_MIN, check_interval);
check_interval = MIN(INTERVAL_MAX, check_interval);
/*do the mission at once*/
if (led_check() != 0) {
/*to check quickly if fail*/
check_interval = INTERVAL_MIN;
}
sleep(check_interval);
dbg("sleep %us", check_interval);
check_interval = check_interval << 1;
}
return 0;
}
标签:LED,在线,snprintf,检测,cmd,system,Linux,GPIO,sizeof
From: https://www.cnblogs.com/adam-ma/p/17994793