<?php
namespace App\Centralstage\DeviceBundle\EventSubscriber;
use App\Centralstage\DeviceBundle\Event\DevicepushEvent as Devicepush;
use App\Centralstage\DeviceBundle\Models\DeviceDataModel;
use App\Centralstage\CoreBundle\Utils\FileHelper;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class DevicepushSubscriber implements EventSubscriberInterface
{
CONST collectionFolder = "collection/";
private $fileSizeInBytes = 5242880; // 5mb in bytes
//private $fileSizeInBytes = 1000000; // 1mb in bytes
public function onDevicePush(Devicepush $devicepush): void
{
try{
//DATA
$EventData = $devicepush->getData();
$deviceDetails = $EventData["deviceDetails"];
$rawData = $EventData["rawData"];
$timestamp = $EventData["devicetimestamp"];
$currentDT = $EventData["currentDT"];
unset($EventData); //free memory
if(is_string($rawData) && !empty($timestamp)){
$NewFile_Bool = true;
$dataArray = json_decode($rawData, true);
if(isset($dataArray["deviceStateTable"])){
$deviceStateTable = $dataArray["deviceStateTable"];
$folderPath = DeviceDataModel::getFolderPath($deviceDetails, $currentDT);
$collectionDir = $folderPath.self::collectionFolder;
if(!file_exists($collectionDir)){ //check dir existing
FileHelper::createDir($collectionDir);
}else{
/*** $lastDataFile = isset($deviceDetails["deviceLastDataID"]) ? (file_exists($folderPath.$deviceDetails["deviceLastDataID"].".json") ? file_get_contents($folderPath.$deviceDetails["deviceLastDataID"].".json") : false) : false;
$currentFile = is_string($lastDataFile) ? json_decode($lastDataFile, true) : false; ****/
$currentFile = !empty($deviceDetails["deviceLastDataID"]) ? $deviceDetails["deviceLastDataID"] : false;
if(!empty($currentFile)){
/** $currentFile = isset($currentFile["timestamp"]) ? $currentFile["timestamp"] : 0; **/
$selectedFile = $collectionDir.$currentFile.".json";
$fileSize = FileHelper::getFileSize($selectedFile);
if(!empty($fileSize) && ($fileSize < $this->fileSizeInBytes)){ // less than 5mb size in bytes
$NewFileName = $collectionDir.$timestamp.".json";
$data = json_decode(file_get_contents($selectedFile, true), true);
if(!isset($data[$timestamp])){
$data[$timestamp] = [];
}
$data[$timestamp][] = $deviceStateTable;
$JsonData = json_encode($data);
file_put_contents($selectedFile, $JsonData);
unset($data, $JsonData); //free Storage
FileHelper::renameFile($selectedFile, $NewFileName);
$NewFile_Bool = false;
}
}
}
if($NewFile_Bool){
$result = [$timestamp => [$deviceStateTable]];
$result = json_encode($result);
$outputfile = "{$collectionDir}{$timestamp}.json";
file_put_contents($outputfile, $result);
}
}
}
}catch (\Exception $exception) { $error = $exception->getMessage(); }
}
public static function getSubscribedEvents(): array
{
return [
'device.collection.push' => 'onDevicePush'
];
}
}