PicoScenes API Docs
 
Loading...
Searching...
No Matches
SystemTools.hxx
Go to the documentation of this file.
1//
2// Created by Zhiping Jiang on 1/26/21.
3//
4
5#ifndef SYSTEM_TOOLS_HXX
6#define SYSTEM_TOOLS_HXX
7
8#include <chrono>
9#include <optional>
10#include <iostream>
11#include <fstream>
12#include <vector>
13#include <array>
14#include <random>
15#include <condition_variable>
16#include <filesystem>
17#include <type_traits>
18#if !(defined(_WIN32) || defined(WIN32))
19#include <net/if.h>
20#include <arpa/inet.h>
21#endif
22#include "BoostHeaders.hxx"
23#include "LoggingService.hxx"
24#include "TimeTools.hxx"
25
26using namespace std::chrono_literals;
27namespace fs = std::filesystem;
28
29namespace SystemTools {
30 namespace Shared {
35 uint32_t getUID();
36
41 uint32_t getPID();
42
47 uint32_t getParentPID();
48
53 std::string getCurrentUserName();
54
60 std::string getFilePathForPID(uint32_t pid);
61
67
73
79 std::string getProcessName(uint32_t pid);
80
87 std::string invokeCommandLineCommand(const std::string& cmdString, int* returnStatus = nullptr);
88
93 std::string getKernelVersion();
94
99 uint8_t getCPUNumber();
100
106
111 void openURLWithDefaultBrowser(const std::string& url);
112 }
113
114 namespace File {
119 std::string getHomeDirectory();
120
126 bool checkCommandExists(const std::string& command);
127
133 std::vector<struct timespec> getAccessChangeModifyTimeOfFile(const std::string& file);
134
141 bool touchFile(const std::string& file, std::optional<struct timespec> targetTimeOrNow);
142
148 std::string getFileOwner(const std::string& filePath);
149
155 std::vector<uint8_t> readContentFromFile(const std::string& file);
156
162 std::string readContentFromFileAsString(const std::string& file);
163
169 std::vector<std::string> readContentFromFileLineByLine(const std::string& filePath);
170
177 void writeContent2File(const std::string& file, const uint8_t* buffer, size_t bufferLength);
178
184 void writeContent2File(const std::string& file, const std::string& content);
185
191 bool removeFile(const std::string& filePath);
192
200 std::vector<fs::path> listFilesWithExtension(fs::path folderPath, std::string prefix = "", std::string surfix = "");
201
209 std::vector<fs::path> listFilesRecursivelyWithExtension(fs::path folderPath, std::string prefix = "", std::string surfix = "");
210
217 template<typename ParseType>
218 ParseType readValueFromFilePath(const std::string& path) {
219 std::fstream fin(path, std::ios::in);
220 std::string line;
221 std::getline(fin, line);
222 fin.close();
223 if (line.empty()) {
224 throw std::invalid_argument(fmt::sprintf("The result of path \"%s\" is empty! \n", path));
225 }
226
227 if constexpr (std::is_same_v<ParseType, std::string>) {
228 return line;
229 } else {
230 double valueD = std::stod(line); // boost::lexical_cast cannot recognize '0x3' style
231 return static_cast<ParseType>(valueD);
232 }
233 }
234
243 template<typename ParseType>
244 int writeValue2FilePath(const std::string& path, const ParseType& value, const std::string& formatStr = "{}") {
245 auto valueString = fmt::format(fmt::runtime(formatStr), value);
246 std::fstream fout(path, std::ios::out);
247 try {
248 fout << valueString;
249 fout.close();
250 return 0;
251 } catch (const std::exception&) {
252 throw std::runtime_error(fmt::format("Cannot write value {} to path {}.", value, path));
253 }
254 }
255 };
256
257 namespace Net {
263
269 std::tuple<bool, std::string, std::optional<TimePoint_System_Millisecond>> checkInternetConnectionAndGetGMTTime(bool forceRefresh = false);
270
278 std::vector<uint8_t> curlDownloadNoBody(const std::string& url, uint32_t timeout_ms = 0, long* httpResponseCode = nullptr);
279
287 std::vector<uint8_t> curlDownload(const std::string& url, uint32_t timeout_ms = 0, long* httpResponseCode = nullptr);
288
296 std::string curlDownloadContentAsString(const std::string& url, uint32_t timeout_ms = 0, long* httpResponseCode = nullptr);
297
308 int udpSendData(const std::string& sessionName, const uint8_t* data, uint32_t bufferLength, const std::string& targetIP, uint16_t targetPoint, std::optional<uint16_t> sourcePort = std::nullopt);
309 }
310
311 namespace Math {
319 template<typename DataType>
320 DataType uniformRandomNumberWithinRange(DataType min, DataType max) {
321 static std::random_device r;
322 static std::default_random_engine randomEngine(r());
323 static std::uniform_int_distribution<DataType> randomGenerator(min, max);
324 return randomGenerator(randomEngine);
325 }
326 }
327
328 namespace Persistence {
335 std::string boostPropertyTree2JSON(const pt::ptree& tree, bool prettyOutput = true);
336
342 pt::ptree jSON2BoostPropertyTree(const std::string& jsonContent);
343
350 std::string boostPropertyTree2INI(const pt::ptree& tree, bool prettyOutput = true);
351
357 pt::ptree INI2BoostPropertyTree(const std::string& iniContent);
358 }
359
360 namespace Thread {
366 std::string getThreadName(uint64_t threadId);
367
373 void setThreadName(uint64_t threadId, const std::string& threadName);
374
379 std::string getCurrentThreadName();
380
385 void setName4CurrentThread(const std::string& threadName);
386
392 }
393
394 namespace Misc {
399 std::string getCPUGovernor();
400
406 bool isPackageInstalled(const std::string& packageName);
407 }
408}
409
410#endif //SYSTEM_TOOLS_HXX
std::string getFileOwner(const std::string &filePath)
Gets the owner of a file.
bool touchFile(const std::string &file, std::optional< struct timespec > targetTimeOrNow)
Updates the access and modification times of a file.
bool removeFile(const std::string &filePath)
Removes a file.
std::vector< std::string > readContentFromFileLineByLine(const std::string &filePath)
Reads the content of a file line by line.
std::vector< fs::path > listFilesRecursivelyWithExtension(fs::path folderPath, std::string prefix="", std::string surfix="")
Recursively lists files in a directory with a specific prefix and suffix.
std::vector< fs::path > listFilesWithExtension(fs::path folderPath, std::string prefix="", std::string surfix="")
Lists files in a directory with a specific prefix and suffix.
std::string readContentFromFileAsString(const std::string &file)
Reads the content of a file into a string.
void writeContent2File(const std::string &file, const uint8_t *buffer, size_t bufferLength)
Writes a buffer of bytes to a file.
int writeValue2FilePath(const std::string &path, const ParseType &value, const std::string &formatStr="{}")
Writes a value to a file path.
bool checkCommandExists(const std::string &command)
Checks if a command exists in the system.
ParseType readValueFromFilePath(const std::string &path)
Reads a value from a file path.
std::string getHomeDirectory()
Gets the home directory of the current user.
std::vector< struct timespec > getAccessChangeModifyTimeOfFile(const std::string &file)
Gets the access, change, and modify times of a file.
std::vector< uint8_t > readContentFromFile(const std::string &file)
Reads the content of a file into a vector of bytes.
DataType uniformRandomNumberWithinRange(DataType min, DataType max)
Generates a uniform random number within a specified range.
std::string getCPUGovernor()
Gets the current CPU governor.
bool isPackageInstalled(const std::string &packageName)
Checks if a package is installed.
std::vector< uint8_t > curlDownloadNoBody(const std::string &url, uint32_t timeout_ms=0, long *httpResponseCode=nullptr)
Downloads data from a URL without the body.
std::vector< uint8_t > curlDownload(const std::string &url, uint32_t timeout_ms=0, long *httpResponseCode=nullptr)
Downloads data from a URL.
std::string curlDownloadContentAsString(const std::string &url, uint32_t timeout_ms=0, long *httpResponseCode=nullptr)
Downloads content from a URL as a string.
int udpSendData(const std::string &sessionName, const uint8_t *data, uint32_t bufferLength, const std::string &targetIP, uint16_t targetPoint, std::optional< uint16_t > sourcePort=std::nullopt)
Sends data over UDP.
bool hasInternetConnection()
Checks if there is an internet connection.
std::tuple< bool, std::string, std::optional< TimePoint_System_Millisecond > > checkInternetConnectionAndGetGMTTime(bool forceRefresh=false)
Checks internet connection and gets GMT time.
std::string boostPropertyTree2INI(const pt::ptree &tree, bool prettyOutput=true)
Converts a Boost property tree to an INI string.
pt::ptree jSON2BoostPropertyTree(const std::string &jsonContent)
Converts a JSON string to a Boost property tree.
std::string boostPropertyTree2JSON(const pt::ptree &tree, bool prettyOutput=true)
Converts a Boost property tree to a JSON string.
pt::ptree INI2BoostPropertyTree(const std::string &iniContent)
Converts an INI string to a Boost property tree.
std::string getProcessName(uint32_t pid)
Gets the name of a process given its process ID.
uint32_t getPID()
Gets the process ID of the current process.
void openURLWithDefaultBrowser(const std::string &url)
Opens a URL with the default web browser.
std::string invokeCommandLineCommand(const std::string &cmdString, int *returnStatus=nullptr)
Invokes a command line command and returns its output.
uint8_t getCPUNumber()
Gets the number of CPU cores.
std::string getKernelVersion()
Gets the kernel version of the operating system.
std::string getCurrentProcessFullPath()
Gets the full path of the current process.
uint32_t getParentPID()
Gets the parent process ID of the current process.
uint32_t getUID()
Gets the user ID of the current process.
std::string getCurrentCommandLineContent()
Gets the command line content of the current process.
std::string getCurrentUserName()
Gets the current user's name.
uint64_t getSystemFreeMemory()
Gets the amount of free memory in the system.
std::string getFilePathForPID(uint32_t pid)
Gets the file path for a given process ID.
void setName4CurrentThread(const std::string &threadName)
Sets the name of the current thread.
std::string getCurrentThreadName()
Gets the name of the current thread.
uint64_t getCurrentThreadId()
Gets the ID of the current thread.
std::string getThreadName(uint64_t threadId)
Gets the name of a thread given its ID.
void setThreadName(uint64_t threadId, const std::string &threadName)
Sets the name of a thread given its ID.