bulletin_broad_show.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include <config_file.h>
  2. #include <boost/algorithm/string/split.hpp>
  3. #include <boost/algorithm/string.hpp>
  4. #include <fstream>
  5. #include <unistd.h>
  6. #include <ctime>
  7. #include "bulletin_broad_show.h"
  8. #include "mine_business.h"
  9. #include <sys/stat.h>
  10. #include "log.h"
  11. bulletin_broad_show::bulletin_broad_show()
  12. {
  13. }
  14. bulletin_broad_show* bulletin_broad_show::inst()
  15. {
  16. static bulletin_broad_show mb;
  17. return &mb;
  18. }
  19. void bulletin_broad_show::OnInit(config_file * config)
  20. {
  21. if (config == nullptr)
  22. {
  23. return;
  24. }
  25. //公告牌显示设置
  26. m_bulletin_board_time = config->get("bulletinboard.showtime",1*60);
  27. std::string tmpSz = config->get("bulletinboard.show_filepath","../log/bulletin");
  28. set_bulletin_board_path(tmpSz);
  29. m_bulletin_board_file_name = config->get("bulletinboard.show_filename","bulletin.txt");
  30. }
  31. void bulletin_broad_show::CreateDirectoryEx(const std::string & sPathName )
  32. {
  33. std::vector<std::string> vecSegTag;
  34. boost::split(vecSegTag, sPathName, boost::is_any_of("/"));
  35. if (vecSegTag.size() == 1) //数据发生错误
  36. {
  37. return;
  38. }
  39. std::string curPath = "";
  40. for (int i = 0 ; i < (int)vecSegTag.size() ; i++)
  41. {
  42. curPath += vecSegTag[i];
  43. if(vecSegTag[i].length() > 1 && vecSegTag[i][0] != '.' )
  44. {
  45. int a = access(curPath.c_str(), F_OK);
  46. if(a == -1)
  47. {
  48. mkdir(curPath.c_str(),0755);
  49. }
  50. }
  51. curPath += "/";
  52. }
  53. }
  54. void bulletin_broad_show::run_bulletin_board()
  55. {
  56. time_t t = std::time(nullptr);
  57. if (t - m_lastshow_bulletin_time > m_bulletin_board_time )
  58. {
  59. //把当前文件写到文件中
  60. m_lastshow_bulletin_time = t;
  61. uint32_t num = mine_business::inst()->get_mine_display_staff_num();
  62. std::string path = m_bulletin_board_path;
  63. static bool g_bCreatePath = false;
  64. if (!g_bCreatePath)
  65. {
  66. CreateDirectoryEx(path); //创建目录
  67. g_bCreatePath = true;
  68. }
  69. path += "/" + m_bulletin_board_file_name;
  70. std::ofstream f1(path.c_str());//打开文件用于写,若文件不存在就创建它
  71. if(!f1.is_open()) {
  72. return;//打开文件失败则结束运行
  73. }
  74. std::string szText = "井下当前总人数: " + std::to_string(num) + "人";
  75. f1 << szText << std::endl;
  76. f1.close(); //关闭文件
  77. log_info("show_bulletin_board : %s" ,szText.c_str());
  78. }
  79. }
  80. void bulletin_broad_show::set_bulletin_board_path(std::string & path)
  81. {
  82. if (path.empty()) return;
  83. for(unsigned i = path.length() - 1 ; i > 0 ;i--)
  84. {
  85. if ( path[i] == '/')
  86. path.pop_back();
  87. else
  88. break;
  89. }
  90. m_bulletin_board_path = path;
  91. }