params.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #pragma once
  2. #include <future>
  3. #include <map>
  4. #include <string>
  5. #include <tuple>
  6. #include <utility>
  7. #include <vector>
  8. #include "common/queue.h"
  9. enum ParamKeyType {
  10. PERSISTENT = 0x02,
  11. CLEAR_ON_MANAGER_START = 0x04,
  12. CLEAR_ON_ONROAD_TRANSITION = 0x08,
  13. CLEAR_ON_OFFROAD_TRANSITION = 0x10,
  14. DONT_LOG = 0x20,
  15. DEVELOPMENT_ONLY = 0x40,
  16. ALL = 0xFFFFFFFF
  17. };
  18. class Params {
  19. public:
  20. explicit Params(const std::string &path = {});
  21. ~Params();
  22. // Not copyable.
  23. Params(const Params&) = delete;
  24. Params& operator=(const Params&) = delete;
  25. std::vector<std::string> allKeys() const;
  26. bool checkKey(const std::string &key);
  27. ParamKeyType getKeyType(const std::string &key);
  28. inline std::string getParamPath(const std::string &key = {}) {
  29. return params_path + params_prefix + (key.empty() ? "" : "/" + key);
  30. }
  31. // Delete a value
  32. int remove(const std::string &key);
  33. void clearAll(ParamKeyType type);
  34. // helpers for reading values
  35. std::string get(const std::string &key, bool block = false);
  36. inline bool getBool(const std::string &key, bool block = false) {
  37. return get(key, block) == "1";
  38. }
  39. std::map<std::string, std::string> readAll();
  40. // helpers for writing values
  41. int put(const char *key, const char *val, size_t value_size);
  42. inline int put(const std::string &key, const std::string &val) {
  43. return put(key.c_str(), val.data(), val.size());
  44. }
  45. inline int putBool(const std::string &key, bool val) {
  46. return put(key.c_str(), val ? "1" : "0", 1);
  47. }
  48. void putNonBlocking(const std::string &key, const std::string &val);
  49. inline void putBoolNonBlocking(const std::string &key, bool val) {
  50. putNonBlocking(key, val ? "1" : "0");
  51. }
  52. private:
  53. void asyncWriteThread();
  54. std::string params_path;
  55. std::string params_prefix;
  56. // for nonblocking write
  57. std::future<void> future;
  58. SafeQueue<std::pair<std::string, std::string>> queue;
  59. };