api-example.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. #
  3. # Sample Socket I/O to CGMiner API
  4. #
  5. function getsock($addr, $port)
  6. {
  7. $socket = null;
  8. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  9. if ($socket === false || $socket === null)
  10. {
  11. $error = socket_strerror(socket_last_error());
  12. $msg = "socket create(TCP) failed";
  13. echo "ERR: $msg '$error'\n";
  14. return null;
  15. }
  16. $res = socket_connect($socket, $addr, $port);
  17. if ($res === false)
  18. {
  19. $error = socket_strerror(socket_last_error());
  20. $msg = "socket connect($addr,$port) failed";
  21. echo "ERR: $msg '$error'\n";
  22. socket_close($socket);
  23. return null;
  24. }
  25. return $socket;
  26. }
  27. #
  28. # Slow ...
  29. function readsockline($socket)
  30. {
  31. $line = '';
  32. while (true)
  33. {
  34. $byte = socket_read($socket, 1);
  35. if ($byte === false || $byte === '')
  36. break;
  37. if ($byte === "\0")
  38. break;
  39. $line .= $byte;
  40. }
  41. return $line;
  42. }
  43. #
  44. function request($cmd)
  45. {
  46. $socket = getsock('127.0.0.1', 4028);
  47. if ($socket != null)
  48. {
  49. socket_write($socket, $cmd, strlen($cmd));
  50. $line = readsockline($socket);
  51. socket_close($socket);
  52. if (strlen($line) == 0)
  53. {
  54. echo "WARN: '$cmd' returned nothing\n";
  55. return $line;
  56. }
  57. print "$cmd returned '$line'\n";
  58. if (substr($line,0,1) == '{')
  59. return json_decode($line, true);
  60. $data = array();
  61. $objs = explode('|', $line);
  62. foreach ($objs as $obj)
  63. {
  64. if (strlen($obj) > 0)
  65. {
  66. $items = explode(',', $obj);
  67. $item = $items[0];
  68. $id = explode('=', $items[0], 2);
  69. if (count($id) == 1 or !ctype_digit($id[1]))
  70. $name = $id[0];
  71. else
  72. $name = $id[0].$id[1];
  73. if (strlen($name) == 0)
  74. $name = 'null';
  75. if (isset($data[$name]))
  76. {
  77. $num = 1;
  78. while (isset($data[$name.$num]))
  79. $num++;
  80. $name .= $num;
  81. }
  82. $counter = 0;
  83. foreach ($items as $item)
  84. {
  85. $id = explode('=', $item, 2);
  86. if (count($id) == 2)
  87. $data[$name][$id[0]] = $id[1];
  88. else
  89. $data[$name][$counter] = $id[0];
  90. $counter++;
  91. }
  92. }
  93. }
  94. return $data;
  95. }
  96. return null;
  97. }
  98. #
  99. if (isset($argv) and count($argv) > 1)
  100. $r = request($argv[1]);
  101. else
  102. $r = request('summary');
  103. #
  104. echo print_r($r, true)."\n";
  105. #
  106. ?>