Просмотр исходного кода

FD3-223 Comando para crear devices

Guillermo Espinoza 7 лет назад
Родитель
Сommit
85b2154c95
2 измененных файлов с 147 добавлено и 16 удалено
  1. 78 0
      Command/CreateDeviceCommand.php
  2. 69 16
      EventListener/DeviceListener.php

+ 78 - 0
Command/CreateDeviceCommand.php

@@ -0,0 +1,78 @@
+<?php
+
+namespace DeviceBundle\Command;
+
+use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Input\InputOption;
+use Symfony\Component\Console\Output\OutputInterface;
+use Buzz\Message\RequestInterface as HttpRequestInterface;
+
+class CreateDeviceCommand extends ContainerAwareCommand
+{
+
+    protected function configure()
+    {
+        $this
+            ->setName('device:create')
+            ->setDescription('Create Device command')
+            ->setHelp('Create Device command')
+            ->addArgument('type', InputOption::VALUE_REQUIRED, 'Device Type. e.g. FTTHBundle:ONU, FTTHBundle:OLT')
+            ->addOption('id', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Device id. e.g. --id=1 --id=2')
+            ->addOption('url', null, InputOption::VALUE_OPTIONAL, 'Device POST url for device creation')
+            ->addOption('username', null, InputOption::VALUE_OPTIONAL, 'Username', 'admin')
+            ->addOption('password', null, InputOption::VALUE_OPTIONAL, 'User password', 'adminpass')
+        ;
+    }
+
+    /**
+     * @param InputInterface $input
+     * @param OutputInterface $output
+     */
+    protected function execute(InputInterface $input, OutputInterface $output)
+    {
+        $ids = $input->getOption('id');
+        $url = $input->getOption('url');
+        $username = $input->getOption('username');
+        $password = $input->getOption('password');
+        try {
+            // busco por device type e id
+            $container = $this->getContainer();
+            $em = $container->get('doctrine.orm.entity_manager');
+            $repository = $em->getRepository($input->getArgument('type'));
+            $entities = array();
+            if (!empty($ids)) {
+                if (!is_array($ids)) {
+                    $ids = array($ids);
+                }
+                foreach ($ids as $id) {
+                    if ($entity = $repository->find($id)) {
+                        $entities[] = $entity;
+                    } else {
+                        $output->writeln("Entity id <error>{$id}</error> not found!");
+                    }
+                }
+            } else {
+                $entities = $repository->findAll();
+            }
+
+            // llamada POST para guardar el device
+            if (!$url && $container->hasParameter('device_post_url')) {
+                $url = $container->getParameter('device_post_url');
+            }
+            $deviceListener = $container->get('device.device_listener');
+            foreach ($entities as $entity) {
+                $response = $deviceListener->send($entity, $url, HttpRequestInterface::METHOD_POST, compact('username', 'password'));
+                if (json_decode($response)) {
+                    $output->writeln('<info>Device created!</info>');
+                    $output->writeln($response);
+                } else {
+                    $output->writeln("Error: Device for entity id <error>{$id}</error> not created!");
+                }
+            }
+        } catch (\Exception $ex) {
+            $output->writeln($ex->getMessage());
+        }
+    }
+
+}

+ 69 - 16
EventListener/DeviceListener.php

@@ -6,6 +6,10 @@ use Doctrine\ORM\Event\LifecycleEventArgs;
 use DeviceBundle\Interfaces\DeviceInterface;
 use WebserviceBundle\Services\Webservice;
 use Buzz\Message\RequestInterface as HttpRequestInterface;
+use Symfony\Bundle\FrameworkBundle\Console\Application;
+use Symfony\Component\Console\Input\ArrayInput;
+use Symfony\Component\Console\Output\BufferedOutput;
+use Symfony\Component\HttpKernel\KernelInterface;
 
 class DeviceListener
 {
@@ -51,24 +55,62 @@ class DeviceListener
      */
     public function postPersist(LifecycleEventArgs $args)
     {
-        if (!$this->enabled) return;
+        if (!$this->enabled) {
+            return;
+        }
 
-        $this->send($args, $this->devicePostUrl, HttpRequestInterface::METHOD_POST);
+        $entity = $args->getEntity();
+        $cmd_args = array(
+            'type:' . get_class($entity),
+            '--id:' . $entity->getId(),
+        );
+        $this->runCommand('device:create', $cmd_args);
+    }
+    
+    /**
+     * Corro el comando para crear el device por AMQP
+     * @global kernel $kernel
+     * 
+     * @param string $name
+     * @param array $args
+     * 
+     * @return string
+     */
+    public function runCommand($name, $cmd_args = array())
+    {
+        global $kernel;
+        
+        $application = new Application($kernel);
+        $application->setAutoExit(false);
+        
+        $input = new ArrayInput(array(
+           'command' => 'amqp:remote',
+           'name' => $name,
+           '--args' => $cmd_args,
+        ));
+        
+        $output = new BufferedOutput();
+        $application->run($input, $output);
+
+        return $output->fetch();
     }
 
     /**
      * @param LifecycleEventArgs $args
+     * 
      * @return mixed
      */
     public function preRemove(LifecycleEventArgs $args)
     {
-        if (!$this->enabled) return;
+        if (!$this->enabled) {
+            return;
+        }
 
         $entity = $args->getEntity();
         if ($entity instanceof DeviceInterface) {
             if ($deviceId = $this->getRemoteDeviceId($entity)) {
-
                 $data = array('id' => $deviceId);
+                
                 return $this->webservice->makeGetRequest($this->deviceDeletePostUrl, HttpRequestInterface::METHOD_DELETE, $data);
             }
         }
@@ -79,36 +121,40 @@ class DeviceListener
      */
     public function postUpdate(LifecycleEventArgs $args)
     {
-        if (!$this->enabled) return;
+        if (!$this->enabled) {
+            return;
+        }
 
         $entity = $args->getEntity();
         if ($entity instanceof DeviceInterface) {
             if ($deviceId = $this->getRemoteDeviceId($entity)) {
                 $url = "{$this->devicePutUrl}{$deviceId}";
-                $this->send($args, $url, HttpRequestInterface::METHOD_PUT);
+                $this->send($entity, $url, HttpRequestInterface::METHOD_PUT);
             } else {
-                $this->send($args, $this->devicePostUrl, HttpRequestInterface::METHOD_POST);
+                $this->send($entity, $this->devicePostUrl, HttpRequestInterface::METHOD_POST);
             }
         }
-
     }
 
     /**
-     * @param LifecycleEventArgs $args
+     * @param DeviceInterface $entity
      * @param string $url
      * @param string $method
+     * @param array $credentials username y password
+     * 
      * @return mixed
      */
-    private function send(LifecycleEventArgs $args, $url, $method)
+    public function send($entity, $url, $method, $credentials = array())
     {
-        if (!$this->enabled) return;
+        if (!$this->enabled) {
+            return;
+        }
 
-        $entity = $args->getEntity();
         if ($entity instanceof DeviceInterface) {
             $data = $entity->getDeviceData();
             $data = $this->addLocationData($entity, $data);
 
-            return $this->webservice->makeGetRequest($url, $method, $data);
+            return $this->webservice->makeGetRequest($url, $method, $data, $credentials);
         }
     }
 
@@ -122,7 +168,9 @@ class DeviceListener
      */
     private function addLocationData($entity, $data)
     {
-        if (!$this->enabled) return;
+        if (!$this->enabled) {
+            return;
+        }
 
         $locationInterface = 'MapBundle\Entity\Interfaces\LocationInterface';
         if (interface_exists($locationInterface) && is_a($entity, $locationInterface)) {
@@ -136,17 +184,19 @@ class DeviceListener
 
     /**
      * @param object $entity
+     * 
      * @return mixed
      */
     private function getRemoteDeviceId($entity)
     {
-        if (!$this->enabled) return;
+        if (!$this->enabled) {
+            return;
+        }
 
         $deviceId = $entity->getId();
         $deviceType = get_class($entity);
         $tenancyId = $entity->getTenancyId();
 
-
         $filters = array('deviceId' => $deviceId, 'deviceType' => $deviceType, 'tenancyId' => $tenancyId);
         $data = $this->webservice->getData("device_post_url", $filters);
 
@@ -159,6 +209,9 @@ class DeviceListener
         return $deviceId;
     }
 
+    /**
+     * @param boolean $enabled
+     */
     function remoteCheck($enabled = true)
     {
         $this->enabled = $enabled;