ONUController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. <?php
  2. namespace FTTHBundle\Controller;
  3. use MapBundle\Util\GeoDecode;
  4. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  5. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use MapBundle\Entity\Location;
  10. use FTTHBundle\Entity\ONU;
  11. use FTTHBundle\Entity\NAP;
  12. use Symfony\Component\Form\Extension\Core\Type\TextType;
  13. use Symfony\Component\Form\Extension\Core\Type\DateType;
  14. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  15. use WebserviceBundle\Form\Type\RemoteClientType;
  16. use MapBundle\Form\Type\RemoteMapType;
  17. use FOS\RestBundle\Controller\Annotations\RouteResource;
  18. /**
  19. * ONU controller.
  20. * @RouteResource("ONU")
  21. */
  22. class ONUController extends Controller
  23. {
  24. public function importAction()
  25. {
  26. $adminPool = $this->get('sonata.admin.pool');
  27. $webservice = $this->get("webservice");
  28. $translator = $this->get('translator');
  29. $flashbag = $this->get('session')->getFlashBag();
  30. $urlObjects = $this->container->hasParameter('remote_get_objects_url');
  31. $urlObjectTypes = $this->container->hasParameter('remote_get_object_type_url');
  32. $_types = array();
  33. $disabled = false;
  34. $objectTypeId = 0;
  35. if (!$urlObjects) {
  36. $flashbag->add("error", $translator->trans("msg_no_defined_ftth_url", array(), "FTTHBundle"));
  37. $disabled = true;
  38. } else {
  39. if (!$urlObjectTypes) {
  40. $flashbag->add("error", $translator->trans("msg_no_defined_ftth_url", array(), "FTTHBundle"));
  41. $disabled = true;
  42. } else {
  43. $urlObjectTypes = $this->getParameter('remote_get_object_type_url');
  44. $filters = array('name' => 'ONU');
  45. $_types = $webservice->getData($urlObjectTypes, $filters, array(), null, null);
  46. }
  47. if (empty($_types)) {
  48. $flashbag->add("error", $translator->trans("msg_no_onu_in_map", array(), "FTTHBundle"));
  49. $disabled = true;
  50. $objectTypeId = 0;
  51. } else {
  52. $disabled = false;
  53. $objectTypeId = $_types[0]['id'];
  54. }
  55. }
  56. $form = $this->createFormBuilder()
  57. ->add('mapId', RemoteMapType::class, array('label' => $translator->trans("form.label_map", array(), "FTTHBundle"), 'disabled' => $disabled))
  58. ->add('clientId', RemoteClientType::class, array('label' => $translator->trans("form.label_client", array(), "FTTHBundle"), 'disabled' => $disabled))
  59. ->getForm();
  60. $flashbag->add("warning", $translator->trans("msg_select_map", array(), "FTTHBundle"));
  61. return $this->render('FTTHBundle:ONU:onu_import.html.twig', array(
  62. 'base_template' => $adminPool->getTemplate('layout'),
  63. 'admin_pool' => $adminPool,
  64. 'admin' => $adminPool->getAdminByClass("FTTHBundle\Entity\ONU"),
  65. 'objectTypeId' => $objectTypeId,
  66. 'form' => $form->createView(),
  67. 'disabled' => $disabled
  68. ));
  69. }
  70. /**
  71. * Queda pendiente enviar un comando para actualizar masivamente los devices
  72. * /admin/ftth/onu/onu_save?_=1508847664462&limit=100&mapId=3&offset=0&clientId=1
  73. */
  74. public function onuSaveAction(Request $request)
  75. {
  76. $em = $this->get('doctrine')->getManager();
  77. $webservice = $this->get("webservice");
  78. $tenancy_service = $this->get("base_tenancy.tenancy_service");
  79. $mapId = $request->get('mapId');
  80. $clientId = $request->get('clientId');
  81. if (is_null($mapId) || empty($mapId) || is_null($clientId) || empty($clientId)) {
  82. $response = new Response(
  83. json_encode(array()),
  84. Response::HTTP_OK,
  85. array('content-type' => 'application/json')
  86. );
  87. return $response;
  88. }
  89. $limit = $request->get('limit');
  90. $offset = $request->get('offset');
  91. $objectTypeId = $request->get('objectTypeId');
  92. $urlObjectTypes = $this->getParameter('remote_get_objects_url');
  93. $filters = array('type' => $objectTypeId, 'map' => $mapId);
  94. $_onus = $webservice->getData($urlObjectTypes, $filters, array(), $limit, $offset);
  95. $return = array();
  96. foreach ($_onus as $onu) {
  97. $object = $em->getRepository("FTTHBundle:ONU")->findOneByPonSerialNumber($onu['text']);
  98. if (is_null($object)) {
  99. $object = new ONU();
  100. $object->setClientId($clientId);
  101. $object->setTenancyId($tenancy_service->getTenancyIdCurrent());
  102. $object->setPonSerialNumber($onu['text']);
  103. $em->persist($object);
  104. $em->flush();
  105. $return[] = "ONU create {$onu['text']}";
  106. }
  107. $location = $object->getLocation();
  108. $action = "update";
  109. if (is_null($location)) {
  110. $location = new Location();
  111. $em->persist($location);
  112. $em->flush();
  113. $object->setLocation($location);
  114. $action = "create";
  115. }
  116. $data = json_decode($onu['vector']['data'], true);
  117. $mapLocation = $data[0];
  118. $mapLocation['zoom'] = 17;
  119. $mapLocation['onu'] = "{$object->getPonSerialNumber()}";
  120. $mapLocation['map_object_id'] = $onu['id'];
  121. $location->setJsonExtraData($mapLocation);
  122. $location->setObjectTypeId($objectTypeId);
  123. $location->setMapId($mapId);
  124. $em->persist($location);
  125. $object->setUpdated(new \DateTime());
  126. $return[] = "LOCATION (id {$location->getId()}) {$action} - ONU (id {$object->getId()}) {$onu['text']} - " . json_encode($mapLocation);
  127. }
  128. $em->flush();
  129. $response = new Response(
  130. json_encode($return),
  131. Response::HTTP_OK,
  132. array('content-type' => 'application/json')
  133. );
  134. return $response;
  135. }
  136. /**
  137. * @param Request $request
  138. * @return JsonResponse
  139. */
  140. public function getDistanceNapOnuAction(Request $request)
  141. {
  142. $lat = $request->query->get('lat', '');
  143. $lng = $request->query->get('lng', '');
  144. $napId = $request->query->get('napId', 0);
  145. if (isset($lat) && isset($lng)) {
  146. // calculo las distancias
  147. $naps = $this->calculateDistance($lat, $lng, $napId);
  148. // ordeno las distancias con valores positivos
  149. usort($naps, array($this, "orderDistances"));
  150. } else {
  151. $naps = [];
  152. }
  153. $response = new JsonResponse();
  154. $response->setData(['results' => json_encode($naps)]);
  155. return $response;
  156. }
  157. /**
  158. * Calcula la distancia de los NAP al punto pasado.
  159. * @param $lat
  160. * @param $lng
  161. * @param $napId
  162. * @return array Retorna una array con los datos de los NAP y con las distancias calculadas.
  163. */
  164. private function calculateDistance($lat, $lng, $napId)
  165. {
  166. $translator = $this->get('translator');
  167. $naps = array();
  168. $em = $this->container->get("doctrine.orm.entity_manager");
  169. $qb = $em->createQueryBuilder();
  170. $query = $qb->select('n')
  171. ->from(NAP::class, 'n');
  172. $napsQuery = $query->getQuery()->execute();
  173. $geodecode = new GeoDecode();
  174. $d = $this->container->hasParameter('onu.distance.nap');
  175. if ($d) {
  176. $distanceNap = $this->container->getParameter('onu.distance.nap');
  177. } else {
  178. $distanceNap = null;
  179. }
  180. // mensajes de errores
  181. $without_olt = $translator->trans("without_olt", array(), "FTTHBundle");
  182. $out_of_range = " [" . $translator->trans("out_of_range", array(), "FTTHBundle") . "]";
  183. $onu_distance_nap_not_configurated = " [" . $translator->trans("onu_distance_nap_not_configurated", array(), "FTTHBundle") . "]";
  184. $nap_not_positioned = " [" . $translator->trans("nap_not_positioned", array(), "FTTHBundle") . "]";
  185. foreach ($napsQuery as $nap) {
  186. if ($nap->getExtraData() != null) {
  187. $nap->setContainer($this->container);
  188. // Seteamos la dirección - direccion o null
  189. $address = $nap->getData('address');
  190. $dataNap = [
  191. 'id' => $nap->getId(),
  192. 'name' => $nap->getName(),
  193. 'distance' => -1,
  194. 'distanceMessage' => '',
  195. 'freePort' => $nap->getFreePort(),
  196. 'address' => $address == null ? '' : $address,
  197. 'olt' => $nap->getOlt() == null ? $without_olt : $nap->getOlt()->getName(),
  198. 'slot' => $nap->getSlot(),
  199. 'link' => $nap->getLink()
  200. ];
  201. if ($nap->getlat() != null && $nap->getlng() != null) {
  202. $distance = $geodecode->distanceGeoPoints($lat, $lng, $nap->getlat(), $nap->getlng(), true);
  203. $dataNap['distance'] = $distance;
  204. // Si tenemos distancia de referencia y se encuentra en rango, seteamos y continuamos
  205. if ($distanceNap != null) {
  206. if ($distanceNap < $distance) {
  207. $dataNap['distanceMessage'] = $out_of_range;
  208. }
  209. } else {
  210. $dataNap['distanceMessage'] = $onu_distance_nap_not_configurated;
  211. }
  212. } else {
  213. $dataNap['distanceMessage'] = $nap_not_positioned;
  214. }
  215. $naps[$nap->getId()] = $dataNap;
  216. } else {
  217. $dataNap = [
  218. 'id' => $nap->getId(),
  219. 'name' => $nap->getName(),
  220. 'distance' => -1,
  221. 'distanceMessage' => $nap_not_positioned,
  222. 'freePort' => $nap->getFreePort(),
  223. 'address' => '',
  224. 'olt' => $nap->getOlt() == null ? $without_olt : $nap->getOlt()->getName(),
  225. 'slot' => $nap->getSlot(),
  226. 'link' => $nap->getLink()
  227. ];
  228. $naps[$nap->getId()] = $dataNap;
  229. }
  230. }
  231. return $naps;
  232. }
  233. /**
  234. * Ordena por las distancias, poniendo los -1 al final.
  235. * @param float $a
  236. * @param float $b
  237. * @return int Retorna -1 en caso de que $a < $b y 1 en caso contrario.
  238. */
  239. public function orderDistances($a, $b)
  240. {
  241. $a = (float)$a["distance"];
  242. $b = (float)$b["distance"];
  243. if ($a == $b) {
  244. return 0;
  245. }
  246. return ($a < $b) ? -1 : 1;
  247. }
  248. /**
  249. * chequea la position si esta libre, según nap
  250. * @param Request $request
  251. *
  252. * @return JsonResponse
  253. */
  254. public function ajaxCheckPositionAction(Request $request)
  255. {
  256. $result = 'ok';
  257. $position = $request->get('position');
  258. $napId = $request->get('nap');
  259. if ($position && $napId) {
  260. $em = $this->getDoctrine()->getManager();
  261. $nap = $em->getRepository(NAP::class)->find($napId);
  262. if ($nap) {
  263. $onus = $em->getRepository(ONU::class)->findByOLTSlotLink($nap);
  264. foreach ($onus as $onu) {
  265. if ($onu->getPosition() == $position) {
  266. $result = 'error';
  267. break;
  268. }
  269. }
  270. }
  271. }
  272. return new JsonResponse(compact('result'));
  273. }
  274. }