我是 PHP 新手,我正在编写 PHP 代码以使用 PHPModbus 库从 modbus 设备获取数据。我需要能够每秒显示数据,然后每分钟将数据写入 CSV 文件。
- 我使用 header('Refresh:1') 每秒刷新页面。
- 我将数据作为原始字节获取,我根据参数将其转换为浮点数或整数。
- 然后我将数据存储在一个数组'energymeter_param'中并内爆数组的内容以获得一个我想每60秒写入CSV文件log.csv的字符串。
- 如果您阅读我的代码,您会看到每次秒的值变为 0 时我都在调用 file_put_contents() 函数。[ if(date('s') == 0)]。
- 但有时在刷新页面时,时间会直接从 HH:MM:59 跳到 HH:MM:01,所以我错过了那一分钟日志文件中的数据。
我该如何克服呢?
<?php
// for automatically refreshing the page every one second
header('Refresh: 1');
//setting the time zone and getting the date and time
$timezone = "Asia/Calcutta";
if(function_exists('date_default_timezone_set')){
date_default_timezone_set($timezone);
}
echo date('d-m-Y'). "</br>";
echo date('H:i:s'). "</br>";
//reference to ModbusMaster.php file where the modbus php protocol is defined
require_once dirname(__FILE__) . '/phpmodbus/Phpmodbus/ModbusMaster.php';
// Create Modbus object
$modbus = new ModbusMaster("192.168.1.105", "TCP");
//Energy Meter
// FC3 = Function Code 3 to read holding registers
/*Setting device ID = 5, Starting address as 100 and
number of registers to be read as 120
*/
try {
// FC 3
$recData = $modbus->readMultipleRegisters(5, 100, 120);
}
catch (Exception $e) {
// Print error information if any
echo $modbus;
echo $e;
exit;
}
// Print status information
echo "</br>Status:</br>" . $modbus;
// Conversion
echo "<h2>EN8400</h2>\n";
// Chunk the data array to set of 4 bytes
$values = array_chunk($recData, 4);
//Create an array and set first two values as date and time
$energymeter_param = array();
$energymeter_param[0] = date('Y-m-d H:i:s');
//$energymeter_param[1] = date('H:i:s');
$count = 1;
// Get float from REAL interpretation
//echo "<h3>Energy meter</h3>\n";
//get each parmeter from energy meter and store in the array
foreach($values as $bytes){
/*Since load hours is unsigned long we are converting it
to unsigned long type and scaling to get correct value */
if($count == 59) {
$temp = PhpType::bytes2unsignedint($bytes);
$temp = $temp/3932160;
}
else {
$temp = PhpType::bytes2float($bytes);
//Converting Wh to Kwh
if($count == 31) {
$temp = $temp/1000;
}
}
//store the values in an array
$energymeter_param[$count] = $temp;
$count++;
}
//Store the number of energy meter parameters in a variable
$num_energymeter_param = $count;
echo "<h3>Energy meter array</h3>\n";
//print array
print_r ($energymeter_param)." </br>";
//write the values to a csv file every time seconds becomes 00
if((date('s')) == 00) {
$temprow = implode(',',$energymeter_param);
$temprow.="\n";
$file = 'H:\Appserv\www\Log.csv';
file_put_contents($file, $temprow, FILE_APPEND );
}