Advertisement
Guest User

Untitled

a guest
Nov 19th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import * as functions from 'firebase-functions';
  2. import * as turf from '@turf/turf'
  3. import { database, initializeApp } from 'firebase-admin';
  4. import * as admin from 'firebase-admin'
  5. import * as firebasedatabase from '@firebase/database'
  6. import { FirebaseDatabase } from '@firebase/database-types';
  7. import { ChildrenNode } from '@firebase/database/dist/src/core/snap/ChildrenNode';
  8. import { querystring } from '@firebase/util';
  9. import { QueryDocumentSnapshot } from '@google-cloud/firestore';
  10. import { GeoJSONObject, geojsonType, featureCollection, feature, geometry } from '@turf/turf';
  11. import { ref } from 'firebase-functions/lib/providers/database';
  12. import { json } from 'body-parser';
  13.  
  14.  
  15.  
  16.  
  17. export const onSensorUpdate = functions.database
  18.     .ref('/Sensori/{sensorId}/feeds/{monthId}/{dayId}/{hourId}/{feedId}/')
  19.     .onUpdate((change, context) => {
  20.  
  21.         const before = change.before.val()
  22.  
  23.         const after = change.after.val()
  24.  
  25.         if (before.field02 + 3 === after.field02) {
  26.             console.log("il campo è stato già aggiornato")
  27.             return null
  28.         }
  29.         const newval = average2(after.field02)
  30.         const timeEdited = Date.now()
  31.         return change.after.ref.update({ field02: newval })
  32.  
  33.  
  34.     })
  35.  
  36.  
  37.  
  38. export const onUserAuthentication = functions.auth
  39.     .user().onCreate((user) => {
  40.  
  41.  
  42.         const admin = require('firebase-admin');
  43.         admin.initializeApp(functions.config().firebase)
  44.  
  45.         var db = admin.database().ref('Users')
  46.         db.child(user.uid + '/type/').set("Citizien");
  47.         db.child(user.uid + '/areas/').set("area1");
  48.         console.log(user.uid);
  49.  
  50.         return 0
  51.     })
  52.  
  53. export const onZoneCreate = functions.database
  54.     .ref('/Zones/Areas/{CAP}/{IDzona}')
  55.     .onCreate((snapshot, context) => {
  56.  
  57.  
  58.         const cap: string = context.params.CAP
  59.         const IDZona: string = context.params.IDzona
  60.         console.log('new zone (id Zona:' + IDZona + ') from CAP ' + cap)
  61.  
  62.  
  63.         const feature = snapshot.val();
  64.         const vettoreCoordinatePoligono: number[][][] = feature.geometry.coordinates
  65.  
  66.  
  67.         console.log("VettoreCorordinate" + vettoreCoordinatePoligono);
  68.  
  69.         var ref = snapshot.ref
  70.         var root = ref.root
  71.         var poly = turf.helpers.polygon(vettoreCoordinatePoligono, { name: 'poly1' })
  72.  
  73.         console.log(poly)
  74.         console.log(poly.geometry)
  75.         console.log(poly.geometry.coordinates)
  76.  
  77.         var risultato = getSquareDivisionTurf(poly.geometry, 0.01); //0.01 = 1km
  78.  
  79.         //TO-DO : set FeatureCollection come segue,e poi nel campo features metterci tutte le feature da visualizzare
  80.         var featureCollection = [{
  81.             type: "FeatureCollection",
  82.             //In features vanno tutti i record che vanno presi nel nodo /cap/idzona (e questo sarà un vettore )
  83.             features: [{/*risultatozona1*/ }, {/*risultatozona2*/ }],
  84.             properties: {
  85.  
  86.             }
  87.         }]
  88.  
  89.         //INIZIALIZZAZIONE DELLA SEZIONE DATI PER LA NUOVA ZONA INSERITA
  90.         var initializeZoneData = {
  91.             feeds: 0,
  92.             private: {
  93.                 averageH: {
  94.                     no2: 0,
  95.                     pm1: 0,
  96.                     pm10: 0,
  97.                     pm2_5: 0,
  98.                     pressione: 0,
  99.                     temperatura: 0,
  100.                     umidità: 0,
  101.                     voc: 0
  102.                 },
  103.                 lastFeeds: {
  104.                     last: 0
  105.                 }
  106.  
  107.             },
  108.             public: {
  109.                 averageD: {
  110.                     no2: 0,
  111.                     pm1: 0,
  112.                     pm10: 0,
  113.                     pm2_5: 0,
  114.                     pressione: 0,
  115.                     temperatura: 0,
  116.                     umidità: 0,
  117.                     voc: 0
  118.  
  119.                 }
  120.  
  121.             }
  122.  
  123.         }
  124.  
  125.         root.child('ZoneData/Areas/' + cap + '/' + IDZona).set(initializeZoneData)
  126.  
  127.         return root.child('Zones/AreasKM/' + cap + "/" + IDZona).set(risultato).then(() => {
  128.             console.log('Write succeeded!');
  129.             console.log(risultato)
  130.         });
  131.  
  132.  
  133.     })
  134.  
  135. export const onZoneKMCreate = functions.database
  136.     .ref("Zones/AreasKM/{CAP}/{IDzona}/{IDBBox}")
  137.     .onCreate((snapshot, context) => {
  138.  
  139.         const cap: string = context.params.CAP
  140.         const IDZona: string = context.params.IDzona
  141.         const IDBBox: string = context.params.IDBBox
  142.         const root = snapshot.ref.root
  143.  
  144.         var initializeZoneData = {
  145.             feeds: 0,
  146.             private: {
  147.                 averageH: {
  148.                     no2: 0,
  149.                     pm1: 0,
  150.                     pm10: 0,
  151.                     pm2_5: 0,
  152.                     pressione: 0,
  153.                     temperatura: 0,
  154.                     umidità: 0,
  155.                     voc: 0
  156.                 },
  157.                 lastFeeds: {
  158.                     last: 0
  159.                 }
  160.  
  161.             },
  162.             public: {
  163.                 averageD: {
  164.                     no2: 0,
  165.                     pm1: 0,
  166.                     pm10: 0,
  167.                     pm2_5: 0,
  168.                     pressione: 0,
  169.                     temperatura: 0,
  170.                     umidità: 0,
  171.                     voc: 0
  172.  
  173.                 }
  174.  
  175.             }
  176.  
  177.         }
  178.         var vectorBBox: any = snapshot.val
  179.  
  180.  
  181.         return root.child('ZoneData/AreasKM/' + cap + '/' + IDZona + '/' + IDBBox).set(initializeZoneData)
  182.  
  183.  
  184.  
  185.     })
  186.  
  187.  
  188. export const provaForEach = functions.database
  189.     .ref('provaForEach/Eventi/{eventId}')
  190.     .onCreate((snapshot, context) => {
  191.  
  192.         var refParent = snapshot.ref.parent.parent
  193.         var refUsers = refParent.child('Users')
  194.         var path: database.Reference
  195.  
  196.         var query = refUsers.once('value', function (usersSnapshot) {
  197.             usersSnapshot.forEach(function (child) {
  198.  
  199.                 if (child.val().cognome == "Tela") {
  200.                     console.log(child.key, child.val())
  201.                     child.ref.root.child("provaForEach").child(child.val().nome).set("Ok")
  202.                     return true
  203.                 }
  204.  
  205.                 return false
  206.             })
  207.         })
  208.  
  209.         return refParent.child("Risultato").set("risultato")
  210.  
  211.  
  212.  
  213.     })
  214.  
  215. //________________________________FUNZIONE ONSENSORCREATE_____________________________________________
  216.  
  217. export const onFeedCreate = functions.database
  218.     .ref('/Sensori/{sensorId}/feeds/{monthId}/{dayId}/{hourId}/{feedId}/')
  219.     .onCreate((snapshot, context) => {
  220.  
  221.         //const structure=context.params.Header.Structure
  222.  
  223.  
  224.         const feedId: string = context.params.monthId + context.params.dayId + context.params.hourId + context.params.feedId
  225.         const sensorId = context.params.sensorId
  226.         console.log('new feed (id Feed:' + feedId + ') from' + sensorId)
  227.  
  228.         //PRELEVO VALORI DEL FEED APPENA ARRIVATO
  229.         const feed = snapshot.val()
  230.  
  231.         //INIZIALIZZAZIONE DEI REFERENCE UTILI AL DATABASE (areas, areasKM)
  232.         var ref = snapshot.ref,
  233.             root = ref.root,
  234.             zoneRef = root.child('Zones'),
  235.             areas = zoneRef.child('Areas'),
  236.             areasKM = zoneRef.child('AreasKM')
  237.  
  238.         //PRELEVO LNG E LAT PER ISTANZIARE IL PUNTO
  239.         var latitude = feed.latitude
  240.         var longitude = feed.longitude
  241.         var lnglat: number[] = [longitude, latitude]
  242.  
  243.         //CHIAMO LA FUNZIONE CHE ESEGUE LA RICERCA DEL PUNTO NELLE ZONE CHE NE AGGIORNERA' ANCHE LE MEDIE
  244.         updateAverages(areas, lnglat, feed, context)
  245.  
  246.         //CHIAMO LA FUNZIONE CHE ESEGUE LA RICERCA DEL PUNTO NELLE ZONE A KM QUADRATO CHE NE AGGIORNERA' ANCHE LE MEDIE
  247.         // var pathAreaKM = getPathAreasKM(areasKM, lnglat)
  248.  
  249.  
  250.  
  251.         var lastFeedAdded = {
  252.             date: feedId,
  253.             areasKM: areasKM.key,
  254.             sensor: sensorId
  255.  
  256.  
  257.         }
  258.  
  259.         return root.ref.child('LastUpdate').set(lastFeedAdded)
  260.     })
  261.  
  262. //_____________________________________________________________________
  263. //_____________________FUNZIONI UTILITARIE_____________________________
  264. //_____________________________________________________________________
  265.  
  266.  
  267. //QUESTA è LA FUNZIONE CHE AGGIORNA LE MEDIE, PRENDE COME PARAMETRI:
  268. // 1)il riferimento al nodo dove sono contenute le aree;
  269. // 2)long e lat del punto, per effettuare il controllo;
  270. // 3)il context del nuovo feed
  271. //Questa funzione richiama:
  272. // 'updateDataNodeZone' -> aggiorna le medie del Poligono
  273. // '
  274.  
  275. function updateAverages(areas: database.Reference, lnglat: number[], feed: any, context: functions.EventContext): void {
  276.  
  277.     //turf.booleanPointInPolygon(polygonCenterTurf(llbPolygon), polygon)
  278.     var path: database.Reference
  279.     var point = turf.point(lnglat)
  280.     const monthID = context.params.monthId
  281.     const dayID = context.params.dayId
  282.     const hourID = context.params.hourId
  283.     const feedID = context.params.feedId
  284.     const sensorId = context.params.sensorId
  285.  
  286.  
  287.     var query = areas.once('value', function (areasSnapshot) {
  288.         areasSnapshot.forEach(
  289.             function (childCapSnapshot) {
  290.  
  291.                 var flag = childCapSnapshot.forEach(
  292.                     function (childZoneSnapshot) {
  293.  
  294.                         const vettoreCoordinatePoligono: number[][][] = childZoneSnapshot.val().geometry.coordinates
  295.                         var polygon = turf.polygon(vettoreCoordinatePoligono)
  296.  
  297.                         if (turf.booleanPointInPolygon(point, polygon)) {
  298.  
  299.                             path = childZoneSnapshot.ref
  300.  
  301.                             updateDataNodeZone(path, feed, context)
  302.                             searchSquarePolygon(path, lnglat, feed, context)
  303.                             return true
  304.                         }
  305.  
  306.                         return false
  307.                     })
  308.                 if (flag == false) {
  309.                     console.log("Record non corrispondente a nessun poligono.")
  310.                     areas.root.child("FeedsOutOfZones").push({ ID: sensorId + ": " + monthID + dayID + hourID + feedID })
  311.  
  312.                 }
  313.                 return flag
  314.             }
  315.  
  316.         )
  317.     })
  318.  
  319. }
  320.  
  321.  
  322. function searchSquarePolygon(zone: database.Reference, lnglat: number[], feed: any, context: functions.EventContext): void {
  323.  
  324.     var path: database.Reference
  325.     var point = turf.point(lnglat)
  326.     var zonekey = zone.key
  327.     var capkey = zone.parent.key
  328.     var zoneKM = zone.root.child('Zones').child('AreasKM').child(capkey).child(zonekey)
  329.     const monthID = context.params.monthId
  330.     const dayID = context.params.dayId
  331.     const hourID = context.params.hourId
  332.     const feedID = context.params.feedId
  333.     const sensorId = context.params.sensorId
  334.  
  335.     console.log("ZoneKM:" + zoneKM.toString())
  336.     zoneKM.once('value', function (childZoneSnapshot) {
  337.         var flag = childZoneSnapshot.forEach(
  338.             function (childSquareSnapshot) {
  339.  
  340.                 const vettoreCoordinatePoligono: number[][][] = childSquareSnapshot.val().geometry.coordinates
  341.                 var polygon = turf.polygon(vettoreCoordinatePoligono)
  342.                 console.log(vettoreCoordinatePoligono)
  343.  
  344.                 if (turf.booleanPointInPolygon(point, polygon)) {
  345.  
  346.                     path = childSquareSnapshot.ref
  347.                     updateDataNodeZoneKM(path, feed, context)
  348.                     return true
  349.                 }
  350.                 return false
  351.  
  352.             })
  353.         if (flag == false) {
  354.             console.log("Record non corrispondente a nessun km quadrato.")
  355.             zone.root.child("FeedsOutOfSquares").push({ ID: sensorId + ": " + monthID + dayID + hourID + feedID })
  356.         }
  357.  
  358.     })
  359.  
  360. }
  361.  
  362. function updateDataNodeZoneKM(path: database.Reference, feed: any, context: functions.EventContext) {
  363.  
  364.     const squarekey = path.key
  365.     const zonekey = path.parent.key
  366.     const capkey = path.parent.parent.key
  367.     const root = path.root
  368.  
  369.     const monthID = context.params.monthId
  370.     const dayID = context.params.dayId
  371.     const hourID = context.params.hourId
  372.     const feedID = context.params.feedId
  373.     const sensorId = context.params.sensorId
  374.  
  375.     var node: database.Reference = root.child('ZoneData').child('AreasKM').child(capkey).child(zonekey).child(squarekey)
  376.     var feedsNode = node.child('feeds')
  377.     var privateNode = node.child('private')
  378.     var publicNode = node.child('public')
  379.  
  380.     feedsNode.push({ month: monthID, day: dayID, hour: hourID, feed: feed, sensor: sensorId, hour_day: hourID + dayID })
  381.  
  382.     //QUERY CHE AGGIORNA LA MEDIA GIORNALIERA
  383.     var queryAverageD = publicNode.once('value', function (publicSnapshot) {
  384.         var i = 0
  385.         publicSnapshot.child('averageD').forEach(function (fieldSnapshot) {
  386.             var fieldRef = fieldSnapshot.ref
  387.             var fieldkey: string = fieldSnapshot.ref.key
  388.             var val: number = fieldSnapshot.val()
  389.             var newval = feed[fieldkey]
  390.  
  391.             if (val == 0) {
  392.                 fieldRef.set(newval)
  393.  
  394.             } else {
  395.  
  396.                 feedsNode.orderByChild('day')
  397.                     .equalTo(dayID)
  398.                     .once('value', function (feedsNodeSnapshot) {
  399.  
  400.                         var numFeedForDay = feedsNodeSnapshot.numChildren()
  401.                         var sum = 0
  402.  
  403.                         feedsNodeSnapshot.forEach(function (feedIDSnapshot) {
  404.                             var x = feedIDSnapshot.val()
  405.                             sum = sum + x.feed[fieldkey]
  406.                             return false
  407.                         })
  408.                         var averageD = sum / numFeedForDay
  409.                         fieldRef.set((averageD))
  410.                     })
  411.             }
  412.             return false
  413.         })
  414.     })
  415.  
  416.     //QUERY CHE AGGIORNA LA MEDIA ORARIA
  417.     var queryAverageH = privateNode.once('value', function (publicSnapshot) {
  418.         var i = 0
  419.         publicSnapshot.child('averageH').forEach(function (fieldSnapshot) {
  420.             var fieldRef = fieldSnapshot.ref
  421.             var fieldkey: string = fieldSnapshot.ref.key
  422.             var val: number = fieldSnapshot.val()
  423.             var newval = feed[fieldkey]
  424.  
  425.             if (val == 0) {
  426.                 fieldRef.set(newval)
  427.  
  428.             } else {
  429.  
  430.                 feedsNode.orderByChild('hour_day')
  431.                     .equalTo(hourID + dayID)
  432.                     .once('value', function (feedsNodeSnapshot) {
  433.  
  434.                         var numFeedForDay = feedsNodeSnapshot.numChildren()
  435.                         var sum = 0
  436.  
  437.                         feedsNodeSnapshot.forEach(function (feedIDSnapshot) {
  438.                             var x = feedIDSnapshot.val()
  439.                             sum = sum + x.feed[fieldkey]
  440.                             return false
  441.                         })
  442.                         var averageD = sum / numFeedForDay
  443.                         fieldRef.set((averageD))
  444.                     })
  445.             }
  446.             return false
  447.         })
  448.     })
  449. }
  450.  
  451. function updateDataNodeZone(path: database.Reference, feed: any, context: functions.EventContext) {
  452.  
  453.     const zonekey = path.key
  454.     const capkey = path.parent.key
  455.     const root = path.root
  456.     const monthID = context.params.monthId
  457.     const dayID = context.params.dayId
  458.     const hourID = context.params.hourId
  459.     const feedID = context.params.feedId
  460.     const sensorId = context.params.sensorId
  461.  
  462.     var node: database.Reference = root.child('ZoneData').child('Areas').child(capkey).child(zonekey)
  463.     var feedsNode = node.child('feeds')
  464.     var privateNode = node.child('private')
  465.     var publicNode = node.child('public')
  466.  
  467.     feedsNode.push({ month: monthID, day: dayID, hour: hourID, feed: feed, sensor: sensorId, hour_day: hourID + dayID })
  468.  
  469.     //QUERY CHE AGGIORNA LA MEDIA GIORNALIERA
  470.     var queryAverageD = publicNode.once('value', function (publicSnapshot) {
  471.         var i = 0
  472.         publicSnapshot.child('averageD').forEach(function (fieldSnapshot) {
  473.             var fieldRef = fieldSnapshot.ref
  474.             var fieldkey: string = fieldSnapshot.ref.key
  475.             var val: number = fieldSnapshot.val()
  476.             var newval = feed[fieldkey]
  477.  
  478.             if (val == 0) {
  479.                 fieldRef.set(newval)
  480.  
  481.             } else {
  482.  
  483.                 feedsNode.orderByChild('day')
  484.                     .equalTo(dayID)
  485.                     .once('value', function (feedsNodeSnapshot) {
  486.  
  487.                         var numFeedForDay = feedsNodeSnapshot.numChildren()
  488.                         var sum = 0
  489.  
  490.                         feedsNodeSnapshot.forEach(function (feedIDSnapshot) {
  491.                             var x = feedIDSnapshot.val()
  492.                             sum = sum + x.feed[fieldkey]
  493.                             return false
  494.                         })
  495.                         var averageD = sum / numFeedForDay
  496.                         fieldRef.set((averageD))
  497.                     })
  498.             }
  499.             return false
  500.         })
  501.     })
  502.  
  503.     //QUERY CHE AGGIORNA LA MEDIA ORARIA
  504.     var queryAverageH = privateNode.once('value', function (publicSnapshot) {
  505.         var i = 0
  506.         publicSnapshot.child('averageH').forEach(function (fieldSnapshot) {
  507.             var fieldRef = fieldSnapshot.ref
  508.             var fieldkey: string = fieldSnapshot.ref.key
  509.             var val: number = fieldSnapshot.val()
  510.             var newval = feed[fieldkey]
  511.  
  512.             if (val == 0) {
  513.                 fieldRef.set(newval)
  514.  
  515.             } else {
  516.  
  517.                 feedsNode.orderByChild('hour_day')
  518.                     .equalTo(hourID + dayID)
  519.                     .once('value', function (feedsNodeSnapshot) {
  520.  
  521.                         var numFeedForDay = feedsNodeSnapshot.numChildren()
  522.                         var sum = 0
  523.  
  524.                         feedsNodeSnapshot.forEach(function (feedIDSnapshot) {
  525.                             var x = feedIDSnapshot.val()
  526.                             sum = sum + x.feed[fieldkey]
  527.                             return false
  528.                         })
  529.                         var averageD = sum / numFeedForDay
  530.                         fieldRef.set((averageD))
  531.                     })
  532.             }
  533.             return false
  534.         })
  535.     })
  536.  
  537. }
  538.  
  539.  
  540.  
  541.  
  542.  
  543.  
  544. // // ______________________FUNZIONI GEOMETRIA CON LIBRERIA TURF ___________________________________________________
  545. // //_______________________________________________________________________________________________________________
  546.  
  547. function getSquareDivisionTurf(polygon: turf.Polygon, mq: number) {
  548.  
  549.     var bound = getBoundsRectangleTurf(polygon);
  550.  
  551.     var lowx: number,
  552.         highx: number,
  553.         lowy,
  554.         highy,
  555.         lats: number[] = [0],
  556.         lngs: number[] = [0],
  557.         vertices = polygon.coordinates[0],
  558.         verticeslength: number = vertices.length
  559.  
  560.  
  561.     for (var i = 0; i < verticeslength; i++) {
  562.  
  563.         lngs[i] = vertices[i][0];
  564.         lats[i] = vertices[i][1];
  565.     }
  566.  
  567.     lats.sort();
  568.     lngs.sort();
  569.  
  570.     //VALORI VARIABILI
  571.  
  572.     lowx = +lngs[0].toFixed(2);
  573.     highx = lowx + mq;      //mq= 0.01 or 0.05
  574.     lowy = +lats[0].toFixed(2);
  575.     highy = lowy + mq;      //mq= 0.01 or 0.05
  576.  
  577.     var startHighX = highx;
  578.     var startLowX = lowx;
  579.  
  580.  
  581.     var sw = turf.helpers.point([lowx, lowy]);
  582.     var ne = turf.helpers.point([highx, highy]);
  583.     var line = turf.lineString([sw.geometry.coordinates, ne.geometry.coordinates])
  584.     var llb = turf.bbox(line);
  585.     //Creo il poligono Di forma quadrata sul Bound quadrato llb
  586.     var llbPolygon = turf.bboxPolygon(llb).geometry
  587.  
  588.     //calcolo il centro di del poligono di forma quadrata
  589.     turf.centerOfMass
  590.     var centro = polygonCenterTurf(llbPolygon)  //DA SOSTITUIRE CON --> turf.centerOfMass
  591.     //in realtà non uso questa variabile
  592.  
  593.     var x = 0;
  594.     var y = 0;
  595.     var i = 0;
  596.     var elements = [];
  597.  
  598.     //DA SOSTITUIRE CON --> turf.centerOfMass
  599.     //DA SOSTITUIRE CON --> turf.centerOfMass
  600.     //DA SOSTITUIRE CON --> turf.centerOfMass
  601.     //DA SOSTITUIRE CON --> turf.centerOfMass
  602.     while (turf.booleanPointInPolygon(polygonCenterTurf(llbPolygon), bound)) {
  603.  
  604.         while (turf.booleanPointInPolygon(polygonCenterTurf(llbPolygon), bound)) {
  605.  
  606.             sw = turf.helpers.point([lowx, lowy]);
  607.             ne = turf.helpers.point([highx, highy]);
  608.             line = turf.lineString([sw.geometry.coordinates, ne.geometry.coordinates])
  609.             llb = turf.bbox(line);
  610.             llbPolygon = turf.bboxPolygon(llb).geometry
  611.             var name = "X:" + x + " Y:" + y + "";
  612.  
  613.             if (turf.booleanPointInPolygon(polygonCenterTurf(llbPolygon), polygon)) {
  614.                 elements[i] =
  615.                     {
  616.                         type: "Feature",
  617.                         properties: {
  618.                             name: name
  619.                         },
  620.                         bbox: [llb[0], llb[1], llb[2], llb[3]],  //left, bottom, right, top
  621.                         geometry: {
  622.                             type: "Polygon",
  623.                             coordinates: [
  624.                                 [
  625.                                     [llb[0], llb[1]],
  626.                                     [llb[2], llb[1]],
  627.                                     [llb[2], llb[3]],
  628.                                     [llb[0], llb[3]],
  629.                                     [llb[0], llb[1]],
  630.                                 ]
  631.                             ]
  632.                         }
  633.                     };
  634.  
  635.                 i++
  636.             }
  637.  
  638.             highx = highx + mq; //aumento longitudine massima
  639.             lowx = lowx + mq;   //aumento latitudine massima    
  640.             x++;
  641.  
  642.         }
  643.         //Resetto la longitudine a quella sul margine sinistro
  644.         highx = startHighX;
  645.         lowx = startLowX;
  646.         //Incremento la latitudine
  647.         highy = highy + mq;
  648.         lowy = lowy + mq;
  649.  
  650.         //Istanzio il nuovo rettangolo al "piano" superiore in latitudine
  651.         sw = turf.helpers.point([lowx, lowy]);
  652.         ne = turf.helpers.point([highx, highy]);
  653.         line = turf.lineString([sw.geometry.coordinates, ne.geometry.coordinates])
  654.         llb = turf.bbox(line);
  655.         llbPolygon = turf.bboxPolygon(llb).geometry
  656.  
  657.         y++;
  658.         x = 0;
  659.     }
  660.  
  661.     return elements;
  662.  
  663. }
  664. function polygonCenterTurf(poly: turf.Polygon) {
  665.  
  666.  
  667.     var lowx,
  668.         highx,
  669.         lowy,
  670.         highy,
  671.         lats: number[] = [0],
  672.         lngs: number[] = [0],
  673.         vertices = poly.coordinates[0]
  674.  
  675.     for (var i = 0; i < vertices.length; i++) {
  676.         lngs[i] = vertices[i][0];
  677.         lats[i] = vertices[i][1];
  678.     }
  679.  
  680.     lats.sort();
  681.     lngs.sort();
  682.     lowx = lngs[0];
  683.     highx = lngs[vertices.length - 1];
  684.     lowy = lats[0];
  685.     highy = lats[vertices.length - 1];
  686.  
  687.     var center_x: number = lowx + ((highx - lowx) / 2);
  688.     var center_y: number = lowy + ((highy - lowy) / 2);
  689.  
  690.     var centerPoint = turf.helpers.point([center_x, center_y])
  691.     return centerPoint
  692. }
  693. function getBoundsRectangleTurf(poly: turf.Polygon): turf.Polygon {
  694.  
  695.  
  696.     var lowx: number,
  697.         highx: number,
  698.         lowy: number,
  699.         highy: number,
  700.         lats: number[] = [0],
  701.         lngs: number[] = [0],
  702.         vertices: number[][] = poly.coordinates[0]
  703.  
  704.  
  705.     for (var i = 0; i < vertices.length; i++) {
  706.         lngs[i] = vertices[i][0];
  707.         lats[i] = vertices[i][1];
  708.     }
  709.  
  710.     lats.sort();
  711.     lngs.sort();
  712.  
  713.     lowy = lats[0];
  714.     highy = lats[vertices.length - 1];
  715.     lowx = lngs[0];
  716.     highx = lngs[vertices.length - 1];
  717.  
  718.  
  719.     var sw = turf.helpers.point([lowx, lowy]);
  720.     var ne = turf.helpers.point([highx, highy]);
  721.     var line = turf.lineString([sw.geometry.coordinates, ne.geometry.coordinates])
  722.     var llb = turf.bbox(line);
  723.  
  724.     return turf.bboxPolygon(llb).geometry;
  725. }
  726. //__________________________________________________________________________________________________________________
  727.  
  728.  
  729.  
  730. //___________________________FUNZIONI DI PROVA_________________________________________________
  731. function average2(val: string): number {
  732.     let x: number
  733.     x = +val;
  734.  
  735.     return x + 3
  736. }
  737.  
  738. //_____________________________________________________________________________________________
  739.  
  740. export const provaRequest = functions.https.onRequest((request, response) => {
  741.  
  742.     // i parametri vengono presi dalla form tipo così:
  743.     //       VENGONO PRESI PER IL CAMPO name__
  744.     //                                       ||  
  745.     //                                       \/
  746.     // <form action="https://us-central1-sensesquaredb.cloudfunctions.net/provaRequest" method = "post" id = "nameform" >
  747.     //                                       ||  
  748.     //                                       \/
  749.     //            nome: <input type="text"  name = "nome" > <br>
  750.     //         cognome: <input type="text"  name = "cognome" > <br>
  751.     // </form>
  752.  
  753.     var nome = request.body.nome       // <- accendo al campo con "name"="nome"
  754.     var cognome = request.body.cognome // <- accendo al campo con "name"="cognome"
  755.     var stringa = [nome, cognome]
  756.  
  757.  
  758.     console.log(nome + cognome)
  759.  
  760.     response.set('Access-Control-Allow-Origin', "*")
  761.     response.set('Access-Control-Allow-Methods', 'POST')
  762.  
  763.     response.end(JSON.stringify({
  764.         stringa
  765.     }))
  766.  
  767.  
  768. })
  769.  
  770. //___________________________________________________________________________________
  771. //__________________________richieste HTTP___________________________________________
  772. export const getAreasBoughtFromUid = functions.https.onRequest((request, response) => {
  773.     //var uid= request.body.uid
  774.     //VALORI DI PROVA
  775.     var uid = 'XijVJNa0U1YNoZDY9JTecABgMHq1'
  776.  
  777.     response.set('Access-Control-Allow-Origin', "*")
  778.     response.set('Access-Control-Allow-Methods', 'POST')
  779.  
  780.     const app = admin.initializeApp(functions.config().firebase)
  781.     areasJsonResponse(response, uid, app)
  782.  
  783.  
  784. })
  785.  
  786. function areasJsonResponse(response: functions.Response, uid: string, app: admin.app.App) {
  787.  
  788.     var rootRef = admin.database().ref()
  789.     var nodeUsers = rootRef.child('Users')
  790.  
  791.     nodeUsers.child(uid).on('value', function (nodeUserSnapshot) {
  792.         var nodeUserVal = nodeUserSnapshot.val()
  793.         console.log("a: " + nodeUserVal)
  794.  
  795.         if (nodeUserVal['type'] == 'A') { //Tipo A = cittadino
  796.             //TO-DO il client deve controllare se è stato mandato il flag
  797.             //per controllare se è un cittadino e non un cliente
  798.  
  799.             var flagValue = { "0": "" }
  800.             response.end(flagValue)
  801.         }
  802.         if (nodeUserVal['type'] == 'B') { //Tipo B = cliente pagante
  803.  
  804.             var areas: any[] = []
  805.  
  806.             nodeUserSnapshot.ref.child('areas')
  807.                 .on('value', function (nodeAreasSnapshot) {
  808.                     var i: number = 0
  809.                     nodeAreasSnapshot.forEach(function (areaSnapshot) {
  810.                         areas[i] = areaSnapshot.val()
  811.                         i++
  812.                         return false
  813.  
  814.                     })
  815.                     response.end(JSON.stringify({
  816.                         areas
  817.                     }))
  818.                 })
  819.         }
  820.         app.delete()
  821.     })
  822.  
  823.  
  824.  
  825. }
  826.  
  827. export const polygonGeojsonRequest = functions.https.onRequest((request, response) => {
  828.  
  829.     var areas: any[] // = request.body.areas
  830.     // VALORI DI PROVA  
  831.     areas = [{
  832.         cap: 'CAP-20100',
  833.         zone: 'ZONA-01'
  834.     }, {
  835.         cap: 'CAP-20100',
  836.         zone: 'ZONA-02'
  837.     },]
  838.  
  839.     response.set('Access-Control-Allow-Origin', "*")
  840.     response.set('Access-Control-Allow-Methods', 'POST')
  841.     const app = admin.initializeApp(functions.config().firebase)
  842.     geoJsonResponse(response, areas, app)
  843. });
  844.  
  845. function geoJsonResponse(response: functions.Response, areas: any[], app: admin.app.App) {
  846.  
  847.     var nodeZones = admin.database().ref('Zones')
  848.     var nodeAreas = nodeZones.child('Areas')
  849.  
  850.     var i: number
  851.     var jsonAreas: any[] = []
  852.     var cap: string
  853.     var zone: string
  854.  
  855.     nodeAreas.once('value', function (nodeAreasSnapshot) {
  856.  
  857.  
  858.         for (i = 0; i < areas.length; i++) {
  859.  
  860.             cap = areas[i].cap
  861.             zone = areas[i].zone
  862.  
  863.             var feature = nodeAreasSnapshot.val()[cap][zone]
  864.             var jsonFeature = {
  865.                 geometry: feature.geometry,
  866.                 properties: feature.geometry,
  867.                 type: feature.type
  868.             }
  869.             jsonAreas[i] = jsonFeature
  870.  
  871.         }
  872.  
  873.         response.end(JSON.stringify({
  874.             type: "FeatureCollection",
  875.             features: jsonAreas
  876.         }))
  877.         app.delete()
  878.     })
  879. }
  880.  
  881. //_____________________________________________________________________________________
  882.  
  883.  
  884. export const squaresGeojsonRequest = functions.https.onRequest((request, response) => {
  885.  
  886.     var areas: any[] // = request.body.areas
  887.     // VALORI DI PROVA  
  888.     areas = [{
  889.         cap: 'CAP-20100',
  890.         zone: 'ZONA-01'
  891.     }, {
  892.         cap: 'CAP-20100',
  893.         zone: 'ZONA-02'
  894.     },]
  895.  
  896.     response.set('Access-Control-Allow-Origin', "*")
  897.     response.set('Access-Control-Allow-Methods', 'POST')
  898.  
  899.     const app = admin.initializeApp(functions.config().firebase)
  900.     squaresJsonResponse(response, areas, app)
  901. })
  902.  
  903. function squaresJsonResponse(response: functions.Response, areas: any[], app: admin.app.App) {
  904.  
  905.     var nodeZones = admin.database().ref('Zones')
  906.     var nodeAreasKM = nodeZones.child('AreasKM')
  907.  
  908.     var i: number
  909.     var jsonAreas: any[] = []
  910.     var cap: string
  911.     var zone: string
  912.  
  913.     nodeAreasKM.once('value', function (nodeAreasKMSnapshot) {
  914.        
  915.  
  916.         for (i = 0; i < areas.length; i++) {
  917.  
  918.             cap = areas[i].cap
  919.             zone = areas[i].zone
  920.  
  921.             nodeAreasKM.child(cap).child(zone).on('value', function (nodeAreaKMSnapshot) {
  922.  
  923.                 nodeAreaKMSnapshot.forEach(function (singleSquareSnapshot) {
  924.  
  925.                     var feature = singleSquareSnapshot.val()
  926.  
  927.                     var jsonFeature = {
  928.                         bbox: feature.bbox,
  929.                         geometry: feature.geometry,
  930.                         type: feature.type
  931.                     }
  932.                     jsonAreas.push(jsonFeature)
  933.  
  934.                     return false
  935.                 })
  936.  
  937.  
  938.             })
  939.         }
  940.  
  941.         response.end(JSON.stringify({
  942.             type: "FeatureCollection",
  943.             features: jsonAreas
  944.         }))
  945.         app.delete()
  946.  
  947.  
  948.     })
  949. }
  950.  
  951.  
  952.  
  953. // function buildPaths(areasBought: any[]): string[] {
  954. //     var zone = 'Zones/Areas'
  955. //     var i: number
  956. //     var refDatabaseString: string[] = []
  957.  
  958. //     for (i = 0; i < areasBought.length; i++) {
  959. //         refDatabaseString[i] = zone + '/' + areasBought[i]['cap'] + "/" + areasBought[i]['zone']
  960.  
  961. //     }
  962.  
  963. //     return refDatabaseString
  964. // }
  965.  
  966.  
  967. // function geoJsonResponse(response: functions.Response, areasRef: database.Reference, zones: any[]) {
  968. //     var i: number = 0
  969. //     var jsonZones: string = undefined
  970.  
  971. //     areasRef.once('value', function (areasSnapshot) {
  972.  
  973. //         areasSnapshot.forEach(function (childCapSnapshot) {
  974.  
  975. //             if (i < zones.length) {
  976. //                 var queryCap = childCapSnapshot.ref
  977. //                     .orderByKey()
  978. //                     .equalTo(zones[i]['capkey'])
  979. //                     .once('value', function (childCapFoundSnapshot) {
  980.  
  981. //                         childCapFoundSnapshot.forEach(function (childZoneSnapshot) {
  982. //                             childZoneSnapshot.ref
  983. //                                 .orderByKey()
  984. //                                 .equalTo(zones[i]['zonekey'])
  985.  
  986. //                         })
  987.  
  988. //                     })
  989.  
  990. //             } else
  991. //                 return true
  992. //             i = i + 1
  993. //             return false
  994.  
  995. //         })
  996.  
  997.  
  998.  
  999.  
  1000.  
  1001. //     })
  1002.  
  1003. //     for (i = 0; i < areas.length; i++) {
  1004.  
  1005. //         areas[i].once('value', function (childZoneSnapshot) {
  1006.  
  1007. //             if (jsonZones == undefined) {
  1008. //                 jsonZones = childZoneSnapshot.val()
  1009.  
  1010. //                 response.send(JSON.stringify(
  1011. //                     jsonZones
  1012.  
  1013. //                 ))
  1014. //             }
  1015. //             else
  1016. //                 jsonZones = jsonZones + "," + childZoneSnapshot.val()
  1017.  
  1018. //             if (i == areas.length - 1) {
  1019. //                 response.end(JSON.stringify({
  1020. //                     jsonZones
  1021.  
  1022. //                 }))
  1023. //             }
  1024. //         })
  1025.  
  1026. //     }
  1027.  
  1028. //     response.end(JSON.stringify({
  1029. //         geoJsonResponse
  1030.  
  1031. //     }))
  1032.  
  1033. // }
  1034.  
  1035. // function geoJsonResponse(zona: string[]): string[] {
  1036. //     var i: number
  1037. //     var zone = 'Zones/Areas/CAP-20100'
  1038. //     var ref: string[]=[]
  1039.  
  1040. //     for (i = 0; i < zona.length; i++) {
  1041.  
  1042. //         ref[i] = zone +'/'+ zona[i]
  1043. //             console.log('Sono nell if')
  1044. //     }
  1045. //     return ref
  1046. // }
  1047.  
  1048.  
  1049.  
  1050. function sleep(milliseconds) {
  1051.     var start = new Date().getTime();
  1052.     for (var i = 0; i < 1e7; i++) {
  1053.         if ((new Date().getTime() - start) > milliseconds) {
  1054.             break;
  1055.         }
  1056.     }
  1057. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement