Beispiel #1
0
def startApplication():
    """Start application."""
    LogUtils.writeInfo("Starting application...")
    SlaveHandler.getInstance()
    ServerValidation.getInstance()
    FeedbackSender.getInstance()
    server = OSCServer()
    sc_thread = Thread(target=server.server_start())
    sc_thread.start()
Beispiel #2
0
    def authorizeUser(self):
        """Authorize user for the service account."""
        try:
            fileName = Path(
                os.path.abspath(
                    os.path.join(os.path.abspath(os.pardir),
                                 Config.GOOGLE_DRIVE_CREDENTIALS)))
            credentials = ServiceAccountCredentials.from_json_keyfile_name(
                fileName, scopes='https://www.googleapis.com/auth/drive')

            service = build('drive', 'v3', credentials=credentials)
            return service
        except Exception as e:
            LogUtils.writeWarning("Google Drive authorization failure : " +
                                  str(e))
            return None
Beispiel #3
0
    def getAllFiles(self):
        """Print all the files accessible by the service account."""
        try:
            results = self.service.files().list(
                pageSize=10,
                fields="nextPageToken, files(id, name)").execute()
            items = results.get('files', [])

            if not items:
                print('No files found.')
            else:
                print('Files:')
                for item in items:
                    print(u'{0} ({1})'.format(item['name'], item['id']))
        except Exception as e:
            LogUtils.writeWarning("Get files from Google Drive failure : " +
                                  str(e))
def handle(self, *varargs):
    """Handler for OSC data. Initiates validation and action based on [varargs]."""
    if len(varargs) != 3:
        LogUtils.writeCritical(
            "Parameter validation failure : Incorrect number of parameters sent in OSC message"
        )
        FeedbackSender.getInstance().sendMessage(
            ModuleType.EXIT,
            "Parameter validation failure : Incorrect number of parameters sent in OSC message"
        )
        return
    id_lg = varargs[0]
    encoding = varargs[1]
    data = varargs[2]
    LogUtils.writeInfo("Query received." + str(self) + " " + str(id_lg) + " " +
                       str(encoding) + " " + str(data))
    serverVal = ServerValidation.getInstance()
    if not (serverVal.validateID(id_lg)):
        LogUtils.writeWarning("Server validation failure : ")
        return
    try:
        mod_type = ModuleType((encoding, str(self)[len(serverVal.basePath):]))
    except Exception as e:
        LogUtils.writeWarning("Server validation failure : " + str(e))
        return

    OSCServer.OSCServer.getInstance().slaveinstance.sendMessage(mod_type, data)

    if mod_type is ModuleType.EXIT:
        OSCServer.OSCServer.getInstance().server_end()
    elif mod_type is ModuleType.GESTURE:
        kmldata = KMLData.fromJson(data)
        generateGesture(kmldata, serverVal.ipaddress)
    elif mod_type is ModuleType.FLYTO:
        generateFlyTo(data, serverVal.ipaddress)
    elif mod_type is ModuleType.POI:
        kmldata = KMLData.fromJson(data)
        generatePOI(kmldata, serverVal.ipaddress)
    elif mod_type is ModuleType.TOUR:
        tourdata = TourData.fromJson(data)
        generateTour(tourdata, serverVal.ipaddress)
    elif mod_type is ModuleType.OVERLAY:
        overlaydata = OverlayData.fromJson(data)
        generateOverlay(overlaydata, serverVal.ipaddress)
    else:
        LogUtils.writeWarning("Module type not handled failure.")
def generatePOI(data, ip):
    """Generate KML file for POI [data]."""
    LogUtils.writeInfo("KML generation for POI.")
    try:
        kml = simplekml.Kml()
        pnt = kml.newpoint(name=data.title, description=data.description, coords=[(data.longitude, data.latitude)])
        pnt.lookat.gxaltitudemode = simplekml.GxAltitudeMode.relativetoseafloor
        pnt.lookat.latitude = data.latitude
        pnt.lookat.longitude = data.longitude
        pnt.lookat.range = KMLUtils.convertZoomToRange(data.zoom)
        pnt.lookat.heading = data.bearing
        pnt.lookat.tilt = data.tilt
        path = KMLUtils.getFilePath()
        kml.save(path)
        multipart_form_data = {'kml': (path, open(path, 'r'))}
        requests.post(DeployUtils.getURL(ip), files=multipart_form_data)
    except Exception as e:
        LogUtils.writeWarning("KML generation for POI failure : " + str(e))
        FeedbackSender.getInstance().sendMessage(ModuleType.GESTURE, "KML generation for POI failure.")
Beispiel #6
0
 def downloadFile(self, fileID):
     """Download file from Google Drive for [fileID]."""
     try:
         request = self.service.files().get_media(fileId=fileID)
         fh = io.BytesIO()
         downloader = MediaIoBaseDownload(fh, request)
         done = False
         while done is False:
             done = downloader.next_chunk()
         fileName = KMLUtils.getFilePath()
         kmlfile = open(fileName, 'w+')
         kmlfile.write(fh.getvalue().decode("utf-8"))
         return True
     except Exception as e:
         print(str(e))
         LogUtils.writeWarning("Google Drive file download failure : " +
                               str(e))
         FeedbackSender.getInstance().sendMessage(
             ModuleType.TOUR, "File download failure for tour.")
         return False
 def test_logEntry(self):
     with self.assertLogs(logging.getLogger(), logging.INFO):
         LogUtils.writeInfo('Default test')
     with self.assertLogs(logging.getLogger(), logging.WARNING):
         LogUtils.writeWarning('Default test')
     with self.assertLogs(logging.getLogger(), logging.CRITICAL):
         LogUtils.writeCritical('Default test')
def generateTour(data, ip):
    """Generate KML file for tour [data]."""
    LogUtils.writeInfo("KML generation for tour.")
    try:
        fr = FileRequests.getInstance()
        if fr is not None:
            fr.downloadFile(data.fileID)
            multipart_form_data = {
                'kml':
                (KMLUtils.getFilePath(), open(KMLUtils.getFilePath(), 'r'))
            }
            requests.post(DeployUtils.getURL(ip), files=multipart_form_data)
        else:
            LogUtils.writeWarning("Authorization for drive access failure.")
    except Exception as e:
        LogUtils.writeWarning("KML generation for tour failure : " + str(e))
        FeedbackSender.getInstance().sendMessage(
            ModuleType.TOUR, "KML generation for tour failure.")
Beispiel #9
0
 def server_end(self):
     """Exit OSC server."""
     LogUtils.writeInfo("Shutting down server...")
     print("Closing server on {}".format(self.server.server_address))
     self.server.shutdown()
Beispiel #10
0
 def server_start(self):
     """Start OSC server forever."""
     LogUtils.writeInfo("Starting server...")
     print("Serving on {}".format(self.server.server_address))
     self.server.serve_forever()
Beispiel #11
0
def generateOverlay(data, ip):
    """Generate KML file for Overlay [data]."""
    LogUtils.writeInfo("KML generation for Overlay.")
    try:
        kml = simplekml.Kml()
        for i in data.itemData:
            if isinstance(i, PlacemarkData):
                pnt = kml.newpoint(name=i.title,
                                   description=i.desc,
                                   coords=[(i.longitude, i.latitude, i.zIndex)
                                           ])
                pnt.style.iconstyle.color = i.iconColor
                pnt.style.iconstyle.scale = i.iconSize
                pnt.lookat.gxaltitudemode = simplekml.GxAltitudeMode.relativetoseafloor
                pnt.lookat.latitude = data.latitude
                pnt.lookat.longitude = data.longitude
                pnt.lookat.range = KMLUtils.convertZoomToRange(data.zoom)
                pnt.lookat.heading = data.bearing
                pnt.lookat.tilt = data.tilt
            elif isinstance(i, LineData):
                line = kml.newlinestring(name=i.title,
                                         description=i.desc,
                                         coords=[(i.points[0].longitude,
                                                  i.points[0].latitude,
                                                  i.points[0].zIndex),
                                                 (i.points[1].longitude,
                                                  i.points[1].latitude,
                                                  i.points[1].zIndex)])
                line.style.linestyle.color = i.color
                line.style.linestyle.width = i.width
                line.lookat.gxaltitudemode = simplekml.GxAltitudeMode.relativetoseafloor
                line.lookat.latitude = data.latitude
                line.lookat.longitude = data.longitude
                line.lookat.range = KMLUtils.convertZoomToRange(data.zoom)
                line.lookat.heading = data.bearing
                line.lookat.tilt = data.tilt
            elif isinstance(i, PolygonData):
                poly = kml.newpolygon(name=i.title, description=i.desc)
                poly.style.linestyle.color = i.strokeColor
                poly.style.linestyle.width = i.width
                poly.style.polystyle.color = i.color
                boundary = []
                for j in i.points:
                    boundary.append((j.longitude, j.latitude, j.zIndex))
                poly.outerboundaryis = boundary
                poly.lookat.gxaltitudemode = simplekml.GxAltitudeMode.relativetoseafloor
                poly.lookat.latitude = data.latitude
                poly.lookat.longitude = data.longitude
                poly.lookat.range = KMLUtils.convertZoomToRange(data.zoom)
                poly.lookat.heading = data.bearing
                poly.lookat.tilt = data.tilt
            elif isinstance(i, ImageData):
                photo = kml.newphotooverlay(name=i.title, description=i.desc)
                photo.point.coords = [(i.longitude, i.latitude, i.zIndex)]
                photo.style.iconstyle.icon.href = 'lg.png'
                photo.lookat.gxaltitudemode = simplekml.GxAltitudeMode.relativetoseafloor
                photo.lookat.latitude = data.latitude
                photo.lookat.longitude = data.longitude
                photo.lookat.range = KMLUtils.convertZoomToRange(data.zoom)
                photo.lookat.heading = data.bearing
                photo.lookat.tilt = data.tilt
                kml.addfile('lg.png')
        path = KMLUtils.getFilePath()
        kml.savekmz(path)
        multipart_form_data = {'kml': (path, open(path, 'r'))}
        requests.post(DeployUtils.getURL(ip), files=multipart_form_data)
    except Exception as e:
        LogUtils.writeWarning("KML generation for overlay failure : " + str(e))
        FeedbackSender.getInstance().sendMessage(
            ModuleType.GESTURE, "KML generation for overlay failure.")
Beispiel #12
0
 def test_pathExistence(self):
     LogUtils.setUpLogs()
     self.assertEqual(LogUtils.path.exists(), True)