#include <string>
#include <sstream>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
void Helper();
bool IsNumber(const std::string& str);
std::string ToHex(const std::string& hex);
//quart tty0 -d 60
int main(int argc, char *argv[])
{
if(argc < 4)
{
Helper();
return -1;
}
int fd = open(argv[1], O_RDWR);
if (fd < 0)
{
printf("open %s failed!=> %s\n",argv[1], strerror(errno));
close(fd);
//return -1;
}
if(argv[2][0] !='-')
{
printf("Data type error!\n");
Helper();
close(fd);
return -1;
}
std::string str = argv[3];
switch (argv[2][1])
{
case 'd':
{
//decimal
if(!IsNumber(str))
{
printf("Parameter error!\n");
Helper();
close(fd);
return -1;
}
write(fd, str.c_str(), str.length());
break;
}
case 'h':
{
//hexadecimal
std::string tmp = ToHex(str);
if(tmp.length() == 0)
{
printf("Parameter error!\n");
Helper();
close(fd);
return -1;
}
write(fd, tmp.c_str(), tmp.length());
break;
}
case 's':
{
//string
write(fd, str.c_str(), str.length());
break;
}
default:
Helper();
break;
}
close(fd);
return 0;
}
void Helper()
{
printf("Useage:\n");
printf(" quart tty0 -i 60\n");
printf(" quart tty0 -h 60\n");
printf(" quart tty0 -s \"60\"\n");
}
bool IsNumber(const std::string& str)
{
std::istringstream iss(str);
double d;
if (!(iss >> d))
return false;
char c;
if (iss >> c)
return false;
return true;
}
std::string ToHex(const std::string& hex)
{
if (hex.length() % 2 != 0)
{
return std::string();
}
auto hexCharToVal = [](char c) -> unsigned char
{
if (c >= '0' && c <= '9') return static_cast<unsigned char>(c - '0');
if (c >= 'A' && c <= 'F') return static_cast<unsigned char>(c - 'A' + 10);
if (c >= 'a' && c <= 'f') return static_cast<unsigned char>(c - 'a' + 10);
return static_cast<unsigned char>(0);
};
std::string result;
result.reserve(hex.length() / 2);
for (size_t i = 0; i < hex.length(); i += 2)
{
unsigned char high = hexCharToVal(hex[i]);
unsigned char low = hexCharToVal(hex[i + 1]);
unsigned char byte = (high << 4) | low;
result.push_back(static_cast<char>(byte));
}
return result;
}