Skip to content

Instantly share code, notes, and snippets.

@gdamjan
Created December 16, 2010 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gdamjan/744078 to your computer and use it in GitHub Desktop.
Save gdamjan/744078 to your computer and use it in GitHub Desktop.
somethingmeter in C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define INTERFACE "ppp0"
#define IOBASE 0x0378 /* printer port base address */
#define PWM_PERIOD 1000 /* micro seconds */
#define MAX_DUTY_CYCLE 650 /* micro seconds */
#define MAX_RX_RATE (3500000 / 8) /* 4 mbit/s */
#define MAX_TX_RATE (760000 / 8) /* 500kbit/s */
#define REFRESH_INTERVAL 0.5 /* 0.5 seconds */
#define MICROSECONDS 1000000
int sendport(int i)
{
if (!ioperm(IOBASE, 1, 1)) {
outb((unsigned char)i, IOBASE);
return 1;
}
else { return 0; }
}
/*
duty_cycle in percent 0-100%
always sleeps PWM_PERIOD uS
*/
void pwm(int percent)
{
unsigned int duty_cycle;
if (percent > 100)
percent = 100;
duty_cycle = MAX_DUTY_CYCLE * percent / 100;
if (duty_cycle > 0) {
sendport(1);
usleep(duty_cycle);
}
sendport(0);
usleep(PWM_PERIOD - duty_cycle);
}
void get_bytes(unsigned long *receive, unsigned long *transmit)
{
char line[4096];
unsigned long a[16];
int len;
FILE *fd = fopen("/proc/net/dev", "r");
while (fgets(line, sizeof(line), fd)) {
sscanf(line, " " INTERFACE ": %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
&a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7],
&a[8], &a[9], &a[10], &a[11], &a[12], &a[13], &a[14], &a[15]);
}
fclose(fd);
*receive = a[0];
*transmit = a[8];
}
int main(int argc, char* argv[])
{
unsigned long receive, prev_receive, transmit, prev_transmit;
unsigned long tx_rate, rx_rate;
unsigned int usec;
get_bytes(&prev_receive, &prev_transmit);
while (1) {
get_bytes(&receive, &transmit);
rx_rate = (receive - prev_receive) / REFRESH_INTERVAL;
rx_rate = 100 * rx_rate / MAX_RX_RATE; // percent of MAX
tx_rate = (transmit - prev_transmit) / REFRESH_INTERVAL;
tx_rate = 100 * tx_rate / MAX_TX_RATE; // percent of MAX
printf("%lu%% %lu%%\n", rx_rate, tx_rate);
prev_transmit = transmit;
prev_receive = receive;
usec = 0;
while (usec < REFRESH_INTERVAL * MICROSECONDS) {
pwm(rx_rate);
usec += PWM_PERIOD;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment