1
0
moha/db_functions.php

124 lines
2.9 KiB
PHP
Raw Normal View History

2021-12-30 16:18:32 +01:00
<?php
function storeDB($db, $filepath)
{
$data = serialize($db);
$fp = fopen($filePath, "w");
fwrite($fp, $data);
fclose($fp);
}
function mkDevicesDB($topic, $json)
{
global $devices, $listProperties, $indexDevices, $dbInit, $logFh;
foreach ($json as $device)
{
//print_r($device);
$fn = $device->friendly_name;
$devices[$topic][$fn] = new device;
$devices[$topic][$fn]->topic = $topic;
$devices[$topic][$fn]->device = $device;
$devices[$topic][$fn]->type = $device->type;
$devices[$topic][$fn]->ieeeAddress = $device->ieee_address;
$devices[$topic][$fn]->friendlyName = $device->friendly_name;
if ( !empty($devices[$topic][$fn]->powerSource ) )
{
$devices[$topic][$fn]->powerSource = $device->power_source;
}
if ($device->definition != null)
{
$devices[$topic][$fn]->description = $device->definition->description;
}
searchProperty($fn, $devices[$topic][$fn], $device, $listProperties);
$indexDevices[$device->ieee_address] = $device->friendly_name;
}
$dbInit = true;
fwrite($logFh, print_r($devices, true));
echo "Devices DB made" .EOL;
//print_r($devices);
}
function searchProperty($fn, $device, $object, $listProperties)
{
$objectArray = (array)$object;
foreach($listProperties as $key => $value)
{
if (in_array($value, $objectArray))
{
//echo "$value trouvé =>";
$device->$key = $value;
//echo $device->$key . EOL;
}
}
}
function changeDevice($topic, $fn, $device)
{
//print_r($device);
iterateDevice($topic, $fn, $device, $device->json);
}
function iterateDevice($topic, $fn, $device, $object)
{
global $changed;
//echo "device =>";print_r($device);echo EOL;
foreach($object as $key => $value)
{
$oldValue = 0;
//echo "key =>"; print_r($key); echo EOL;
//echo "value =>"; print_r($value); echo EOL;
//echo "type : " . gettype($value) .EOL;
if (gettype($value) == "object")
{
//echo " is Object" . EOL;
if (!property_exists($device, $key))
{
$device->{$key} = null;
}
//echo "iterating" . EOL;
iterateDevice($topic, $fn, $device, $value);
}elseif (gettype($value) == "array")
{
//echo "is array" . EOL;
iterateDevice($topic, $fn, $device, $value);
}else
{
if (empty($device->$key) or $value != null)
{
if (isset($device->$key)) $oldValue = $device->$key;
if ($oldValue != $value)
{
$device->{$key} = $value;
$changed[$fn]["key"] = $key;
$changed[$fn]["value"] = $value;
//echo "oldvalue => " . print_r($oldValue, true) . EOL;
if (empty($oldValue))
{
echo "Initializing " . $key;
}else
{
echo "changed " . $key . " value " . $oldValue;;
}
echo " to " . $value . EOL;
}
//print_r($device->functions);
if (!empty($device->functions))
{
echo "executing notifications functions " . EOL;
foreach($device->functions as $function)
{
//print_r($function);
$function($topic, $fn, $key, $value);
}
}
}
}
}
}
?>