Skip to content

Instantly share code, notes, and snippets.

@twilightty
Last active May 30, 2024 17:41
Show Gist options
  • Save twilightty/032d4ddb42455219459d4a076c642c70 to your computer and use it in GitHub Desktop.
Save twilightty/032d4ddb42455219459d4a076c642c70 to your computer and use it in GitHub Desktop.
//#include <bits/stdc++.h> =)))))
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define DEFAULT_NUM_SENSORS 1
#define DEFAULT_SAMPLING_TIME 10
#define DEFAULT_SIMULATION_INTERVAL 3600
#define MAX_RPM 3000.0
#define RESOLUTION 0.2
typedef struct {
double currentRPM;
} SpeedSensor;
double generateRandomRPM() {
return (rand() / (double)RAND_MAX) * MAX_RPM;
}
double roundToResolution(double value) {
return ((int)(value / RESOLUTION + 0.5)) * RESOLUTION;
}
void measureRPM(SpeedSensor *sensor) {
sensor->currentRPM = roundToResolution(generateRandomRPM());
}
void getCurrentTime(char *buffer) {
time_t now = time(NULL);
struct tm *tm_ptr = localtime(&now);
strftime(buffer, 20, "%Y:%m:%d %H:%M:%S", tm_ptr);
}
void incrementTime(char *timeStr, int seconds) {
struct tm tm;
strptime(timeStr, "%Y:%m:%d %H:%M:%S", &tm);
tm.tm_sec += seconds;
mktime(&tm);
strftime(timeStr, 20, "%Y:%m:%d %H:%M:%S", &tm);
}
void parseArguments(int argc, char *argv[], int *numSensors, int *samplingTime, int *simulationInterval) {
*numSensors = DEFAULT_NUM_SENSORS;
*samplingTime = DEFAULT_SAMPLING_TIME;
*simulationInterval = DEFAULT_SIMULATION_INTERVAL;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-n") == 0 && i + 1 < argc) {
*numSensors = atoi(argv[++i]);
} else if (strcmp(argv[i], "-st") == 0 && i + 1 < argc) {
*samplingTime = atoi(argv[++i]);
} else if (strcmp(argv[i], "-si") == 0 && i + 1 < argc) {
*simulationInterval = atoi(argv[++i]);
}
}
}
int main(int argc, char *argv[]) {
int numSensors, samplingTime, simulationInterval;
parseArguments(argc, argv, &numSensors, &samplingTime, &simulationInterval);
SpeedSensor *sensors = malloc(numSensors * sizeof(SpeedSensor));
FILE *outFile = fopen("speed_data.csv", "w");
if (outFile == NULL) {
perror("Error opening file");
free(sensors);
return 1;
}
fprintf(outFile, "id,time,value\n");
char currentTime[20];
getCurrentTime(currentTime);
for (int elapsed = 0; elapsed <= simulationInterval; elapsed += samplingTime) {
for (int i = 0; i < numSensors; ++i) {
measureRPM(&sensors[i]);
fprintf(outFile, "%d,%s,%.1f\n", i + 1, currentTime, sensors[i].currentRPM);
}
incrementTime(currentTime, samplingTime);
sleep(samplingTime);
}
fclose(outFile);
free(sensors);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment