Exemple #1
0
    def on_removeWidget(self, a='', b=''):
        print("ScreenWidgets.on_removeWidget")
        print("remove obj from screen ", self.screen)
        print("widgetEdit", self.widgetEdit)

        self.q = QueryPopup()
        self.q.setAction("Remove widget",
                         "Really remove widget: %s" % self.widgetEdit, None,
                         "Cancel", self.on_removeWidgetConfirme, "Remove")
        self.q.run()
Exemple #2
0
	def calibrate(self):
		print("calibrate")
		self.calTStart = self.th.getTimestamp()
		self.calCompas = []
		self.calHeel = []
		self.calPitch = []
		self.calBuf = {'x':[], 'y':[],'z':[]}
		self.calibrateStep = 1
		
		self.orientation.setOffset([0.0,0.0,0.0])
		self.gyroFlipt.setOffset([0.0,0.0,0.0])
		
		self.calibationTimeStart = self.th.getTimestamp()
		self.queryMessage = QueryPopup()
		self.queryMessage.setAction(
			"Calibrating ...", 
			"In the process of calibarion gyro, heel, pitch sensor...", 
			self.on_calibation_cancel, "Cancel calibration now!", 
			None, None
			)
		self.queryMessage.run()
Exemple #3
0
    def startEditWizard(self):
        print("startEditWizard")
        obj = self.sw.getWeObj(self.sw.widgetEdit['screen'],
                               self.sw.widgetEdit['wi'])

        if obj.settingsNeedIt() == False:
            print("no need for more steps ")
            q = QueryPopup()
            q.setAction("Widget edit", "This widget don't have a settings :/",
                        None, "OK", None, None)
            q.run()
        else:
            self.actionType = 'edit'
            self.on_start_editW()
Exemple #4
0
    def startEditWizard(self):
        print("startEditWizard")
        obj = self.sw.wConfig[self.sw.widgetEdit['screen']][
            self.sw.widgetEdit['wi']]['obj']

        print("""screen {} wi {} obj{} all wConf{}""".format(
            self.sw.widgetEdit['screen'], self.sw.widgetEdit['wi'], obj,
            self.sw.wConfig[self.sw.widgetEdit['screen']][
                self.sw.widgetEdit['wi']]))
        if obj.settingsNeedIt() == False:
            print("no need for more steps ")
            q = QueryPopup()
            q.setAction("Widget edit", "This widget don't have a settings :/",
                        None, "OK", None, None)
            q.run()
        else:
            self.actionType = 'edit'
            self.on_start_editW()
Exemple #5
0
class ScreenWidgets:
    def __init__(self, gui):
        self.gui = gui

    def makeSensorsList(self):
        print("ScreenWidgets.makeSensorsList")
        sl = self.gui.sen.sensorsList
        print("have now: ", len(sl), " sensors registered")
        for s in sl:
            print('''    sensor: {}        class:{}
        values: {}
        '''.format(s.getTitle(), type(s), s.getValuesOptions()))

        #sys.exit(0)

    def solveScrolSize(self, bl):
        #bl = bl.parent
        hs = 0.0
        try:
            bl = bl.children[0]
        except:
            print("EE - no children[0]")
        print("type", type(bl))
        print("children count", len(bl.children))
        print("parent type", type(bl.parent))

        for c in bl.children:

            hs += c.height
        #self.queryWidget.size = [self.queryWidget.size[0],hs+cm(1)]
        return [bl.size[0], hs + self.gui.btH]

    def getWidgetsTypeList(self):
        print("ScreenWidgets.getWidgetsTypeList")
        return self.widgetsTypeList

    def updateValsInWConfig(self, si='', wi='', sfw='', c=''):
        #print("updateValsInWConfig si",si," wi",wi,"\n    sfw",sfw,"\n    c",c)
        self.wConfig[si][wi]['pos'] = list(sfw.pos)
        self.wConfig[si][wi]['scale'] = sfw.scale
        self.wConfig[si][wi]['rotation'] = sfw.rotation
        self.bubble.startTimer(self, self.bubbleTimeOut)

    def saveConfig(self):
        print("ScreenWidgets.saveConfig")  #,self.wConfig)

        print(" clean stuff befoare save to file")
        for s in self.wConfig:
            for w in s:
                w['obj'] = ''

        #print("-------------------------------------------")
        #print(self.wConfig)
        #print("-------------------------------------------")

        print("save config Widgets res:",
              DataSR_save(self.wConfig, self.wConfigPath))

    def setGui(self, a='', b=''):
        print("ScreenWidgets.setGui")
        self.flSize = ObjectProperty([.0, .0])

        self.widgetsTypeList = [
            {
                'name': "Numeric",
                'obj': Widget_cn(),
                'objName': 'Widget_cn',
                'thumb': 'widget_numeric.png'
            },
            {
                'name': 'Bubble',
                'obj': WidgetBubble(),
                'objName': 'WidgetBubble',
                'thumb': 'widget_bubble.png'
            },
            {
                'name': 'Niddle guage',
                'obj': Widget_niddle(),
                'objName': 'Widget_niddle',
                'thumb': 'widget_niddle.png'
            },
            {
                'name': "Compass",
                'obj': ScreenCompass(),
                'objName': 'ScreenCompass',
                'thumb': 'widget_compass.png'
            },
            {
                'name': "Circular progress",
                'obj': Widget_circularProgress(),
                'objName': 'Widget_circularProgress',
                'thumb': 'widget_niddle_circular.png'
            },
        ]

        self.fa = FileActions()
        self.wConfigPath = self.fa.join(self.gui.workingFolderAdress,
                                        'ykpilotWidgets.conf')
        if self.fa.isFile(self.wConfigPath) == False:
            print("screen widgets no config file setting default")
            self.wConfig = [[{
                'name': 'ScreenCompass',
                'obj': "",
                'objName': 'ScreenCompass',
                'callback': ['gpsD', 'comCal', 'comCalAccelGyro'],
                'pos': [10, 10],
                'scale': 1.0,
                'rotation': 0.0
            }]]
        else:
            print("screen widgets resuming config")
            self.wConfig = DataSR_restore(self.wConfigPath)
            print(self.wConfig)
            print("------------------------------")
            #sys.exit(0)

        self.screen = 0
        self.screens = len(self.wConfig) + 1
        self.bubble = None
        self.bubbleTimeOut = 5.0
        self.goFullscreenIn = 8.0
        #self.gui = gui
        self.editMode = False
        #self.clockUWFS = None
        self.WAEDV = WidgetsAEDV(self)

        self.buildW()
        return 0

    def screenBack(self, a='', b=''):
        self.gui.screenChange("Widgets{}".format(self.screen))

    def getWeObj(self, si, wi):
        return self.getWe(si, wi)['obj']

    def getWe(self, si, wi):
        return self.wConfig[si][wi]

    def on_widgetSelected(self, screen='', wi='', sfw='', d=''):
        print("on_widgetSelected d", d)
        print("    ->pos", d.pos)
        colision = sfw.collide_point(d.pos[0], d.pos[1])
        if colision == False:
            return False

        #self.widgetEdit = self.wConfig[screen][wi]['obj']
        self.widgetEdit = {'screen': screen, 'wi': wi}
        weObj = self.getWeObj(screen, wi)

        print("    -> ", weObj)
        print("    -> col", colision)

        try:
            sfw = weObj.parent
        except:
            sfw = weObj.getWidget().parent
        fl = sfw.parent

        if self.bubble == None:
            self.bubble = bubbleRemEdit()
        else:
            p = self.bubble.parent
            p.remove_widget(self.bubble)

        self.bubble.startTimer(self, self.bubbleTimeOut)
        sfw.bind(pos=self.bubble.setPosForWidget)
        self.bubble.setPosForWidget(sfw, sfw.pos)

        fl.add_widget(self.bubble)

    def bindScatter(self, sfw, si, wi):
        sfw.bind(pos=partial(self.updateValsInWConfig, si, wi))
        sfw.bind(scale=partial(self.updateValsInWConfig, si, wi))
        sfw.bind(rotation=partial(self.updateValsInWConfig, si, wi))
        sfw.bind(on_touch_down=partial(self.on_widgetSelected, si, wi))

    def unbindScatter(self, sfw, si, wi):
        sfw.unbind(pos=partial(self.updateValsInWConfig, si, wi))
        sfw.unbind(scale=partial(self.updateValsInWConfig, si, wi))
        sfw.unbind(rotation=partial(self.updateValsInWConfig, si, wi))
        sfw.unbind(on_touch_down=partial(self.on_widgetSelected, si, wi))

    def rebuildWs(self, a='', b=''):
        print("ScreenWidgets.rebuildWs")
        tScreen = self.screen
        print("--- so cleanAll !!")
        self.cleanAll()
        print("--- so cleanAll !! DONE")

        print("--- so build !!")
        self.buildW()
        print("--- so build !! DONE")
        self.updateIt()
        self.gui.screenChange(("Widgets%s" % tScreen))

    def cleanAll(self, a='', b=''):
        print("ScreenWidgets.cleanAll")
        if self.editMode:
            print("is in edit mode exiting ...")
            self.on_btEdit()

        print("goint by widgets in wConfig")
        for si, s in enumerate(self.wConfig):
            for wi, w in enumerate(s):
                obj = w['obj']

                if obj == "":
                    w['obj'] = None
                else:
                    print("widget ", w['objName'], ' type', type(obj))
                    try:
                        p = obj.parent
                        obj2Remove = obj
                    except:
                        ot = obj.getWidget()
                        p = ot.parent
                        obj2Remove = ot
                    print("remove from parent [", p, "]...")
                    if p == None:
                        break

                    print("remove from parent scatter")
                    p.remove_widget(obj2Remove)
                    pScater = p.parent
                    print("remove scater from fLayout")
                    pScater.remove_widget(p)
                    print("unbind scatter")
                    self.unbindScatter(p, si, wi)

                    print("remove callbacks...")
                    for cal in w['callback']:
                        print("sensor", cal)
                        unSub = "self.gui.sen.{}.removeCallBack(obj)".format(
                            cal)
                        #print("go with:",unSub)
                        exec(unSub)
                    w['obj'] = None

        print("removing nav bt's...")
        for bt in self.navBts:
            p = bt.parent
            p.remove_widget(bt)

        print("removing fls...")
        for fl in self.fls:
            p = fl.parent
            p.remove_widget(fl)

        self.gui.rl.current = "Widgets"
        print("removing screens...")
        for scr in self.screenObjs:
            self.gui.rl.remove_widget(scr)

        print("DONE")
        #sys.exit(0)

    def buildW(self):
        print("ScreenWidgets.buildW")

        print("- screens now count is", self.screens)
        self.fls = []
        self.screenObjs = []
        self.flsOrgs = []
        self.navBts = []
        self.navAddBts = []
        for si in range(self.screens):
            screen = Screen(name="Widgets%s" % si)
            self.screenObjs.append(screen)
            self.flsOrgs.append(None)
            fl = FloatLayout()
            fl.bind(size=self.flChangeSize)
            self.fls.append(fl)
            #fl.add_widget(Label(text="widgets%s"%si))
            #self.flsOrgs[si] = fl.on_touch_down
            #fl.on_touch_down = self.on_touch
            screen.add_widget(fl)

            try:
                self.setUpGui(si, fl, self.wConfig[si])
            except:
                self.setUpGui(si, fl, [])

            self.gui.rl.add_widget(screen)
            self.flChangeSize(b=fl.size)

        print("    DONE")

    def flChangeSize(self, a='', b=''):
        print("flChangeSize", a, "\n", b)
        self.flSize = b
        y = b[1] - self.gui.btH
        for b in self.navBts:
            b.y = y

    def addWidgetOnScreen(self, wObj, callback=None):
        print("ScreenWidgets.add widget on screen", wObj)

        if len(self.wConfig) <= self.screen:
            print("adding first widget on screen !", self.screen)
            self.wConfig.append([])

        self.wConfig[self.screen].append({
            'name': wObj['name'],
            'obj': "",
            'objName': wObj['objName'],
            'callback': wObj['obj'].getCallbacks(),
            'pos': [10, 10],
            'scale': 1.0,
            'rotation': 0.0
        })
        '''
        self.wConfig[self.screen].append({
            'name': 'ScreenCompass',
            'obj': ScreenCompass(),
            'objName': 'ScreenCompass',
            'callback': ['gpsD','comCal', 'comCalAccelGyro'],
            'pos': [200,200],
            'scale':1.0,
            'rotation':0.0
            })'''

        #sys.exit(0)
        self.saveConfig()

        tScreen = self.screen
        self.rebuildWs()
        self.gui.screenChange(("Widgets%s" % tScreen))

    def updateIt(self, a='', b=''):
        print("ScreenWidgets.updateIt")
        if self.gui.rl.current == "Widgets":
            self.gui.screenChange("Widgets0")
            return 0

        print("current screen:", self.gui.rl.current[7:])
        self.screen = int(self.gui.rl.current[7:])
        #print("wConfig",self.wConfig)
        #print("len",len(self.wConfig))
        #print("screen",self.screen)

        if len(self.wConfig) > self.screen:
            print("updating widgets on screen...")
            for w in self.wConfig[self.screen]:
                o = w['obj']
                try:
                    o.updateIt()
                except:
                    pass
        else:
            print("EE - nothing to update :( no widgets in screen",
                  self.screen)

    def on_toggleFullScreen(self, a='', b=''):
        print("on_toggleFullScreen")
        if self.gui.ab.height > 0.0:
            self.gui.ab.height = 0.0
        else:
            self.gui.ab.height = self.gui.btH

    def on_editWidget(self, a='', b=''):
        print("on_editWidget")
        print("widgetEdit", self.widgetEdit)
        #self.WAEDV = WidgetsAEDV(self)
        self.WAEDV.startEditWizard()

    def on_removeWidget(self, a='', b=''):
        print("ScreenWidgets.on_removeWidget")
        print("remove obj from screen ", self.screen)
        print("widgetEdit", self.widgetEdit)

        self.q = QueryPopup()
        self.q.setAction("Remove widget",
                         "Really remove widget: %s" % self.widgetEdit, None,
                         "Cancel", self.on_removeWidgetConfirme, "Remove")
        self.q.run()

    def on_removeWidgetConfirme(self, a='', b=''):
        print("on_removeWidgetConfirme")
        print("looking for object in wConfig")
        for si, s in enumerate(self.wConfig):
            print("screen", si)
            for wi, w in enumerate(s):
                print("widget", wi, " -> ", w['objName'])
                if [si, wi
                    ] == [self.widgetEdit['screen'], self.widgetEdit['wi']]:
                    self.cleanAll()
                    self.wConfig[si].pop(wi)
                    print("so widget removed. save new config")
                    self.saveConfig()
                    tScreen = self.screen
                    self.buildW()
                    self.gui.screenChange("Widgets%s" % tScreen)
                    return True

    def on_bgRelease(self, a='', b=''):
        print("ScreenWidgets.on_bgRelease")
        if self.editMode == True:
            self.on_btEdit(a)
            return True

    def setUpGui(self, screen, bWidget, widgets):
        print("ScreenWidgets.setUpGui ")  #,bWidget," widgets\n",widgets)

        for i, w in enumerate(widgets):
            print("building widget [", w['name'], "]")
            exec("widgets[i]['obj'] = %s()" % w['objName'])
            o = widgets[i]['obj']

            if w['objName'] != 'ScreenCompass':
                print(
                    "passing atr setting to Widget_cn or 'Widget_niddle or WidgetBubble"
                )
                atr = w['atr']
                atr['screen'] = screen
                atr['valHandler'] = w['valHandler']
                o.setValuesFromDic(atr)
                print("    done")
            print("setGui")
            o.setGui(self.gui)

            print("add widget")
            sfw = ScatterForWidget(widgetSize=o.getSize())
            sfw.rotation = self.wConfig[screen][i]['rotation']
            sfw.scale = self.wConfig[screen][i]['scale']
            sfw.pos = self.wConfig[screen][i]['pos']

            sfw.add_widget(o.getWidget())
            self.bindScatter(sfw, screen, i)
            bWidget.add_widget(sfw)

            print("\- - adding callbacks:", w['callback'])
            for c in w['callback']:
                if c != '':
                    print("callback to:", c)
                    if c == 'gps':
                        print("changing gps to gpsD")
                        c = 'gpsD'
                    print("add it ....")
                    eval("self.gui.sen.%s.addCallBack(o)" % (c))
                    print("    DONE")
                    #print("o",o)
                    #print("widgets[i]['obj']",widgets[i]['obj'])
                    #print("self.gui.sen.gps",self.gui.sen.gpsD.callBacksForUpdate)

        self.addNavBts(bWidget)
        #self.updateWidgetFromScatter()

    def on_screenLeft(self, a=''):
        print("ScreenWidgets.on_screenLeft")
        #self.on_btEdit()
        s = self.screen - 1
        if s < 0:
            s = self.screens - 1
        self.screen = s
        self.gui.screenChange("Widgets%s" % s)

    def on_screenRight(self, a=''):
        print("ScreenWidgets.on_screenRight")
        #self.on_btEdit()
        s = self.screen + 1
        if s >= self.screens:
            s = 0
        self.screen = s
        self.gui.screenChange("Widgets%s" % s)

    def startAddWidgetDialog(self, a=''):
        print("ScreenWidgets.on_screenLeft")
        #self.WAEDV = WidgetsAEDV(self)
        self.WAEDV.startWizard()

    def addNavBts(self, w):
        print("ScreenWidgets.addNavBts")
        navBtColor = (.9, .0, .0, 0.6)

        #sys.exit()
        btAdd = Button(text="<",
                       size=[self.gui.btH, self.gui.btH],
                       size_hint=(None, None),
                       background_color=navBtColor,
                       on_release=self.on_screenLeft)
        w.add_widget(btAdd)
        self.navBts.append(btAdd)

        btAdd = Button(text="+",
                       size=[self.gui.btH, self.gui.btH],
                       size_hint=(None, None),
                       background_color=navBtColor,
                       on_release=self.startAddWidgetDialog)
        w.add_widget(btAdd)
        #btAdd.top = self.gui.btH
        btAdd.x = self.gui.btH
        self.navBts.append(btAdd)
        self.navAddBts.append(btAdd)

        btAdd = Button(text=">",
                       size=[self.gui.btH, self.gui.btH],
                       size_hint=(None, None),
                       background_color=navBtColor,
                       on_release=self.on_screenRight)
        w.add_widget(btAdd)
        btAdd.x = self.gui.btH * 2.0
        self.navBts.append(btAdd)

        btAdd = Button(text="F",
                       size=[self.gui.btH, self.gui.btH],
                       size_hint=(None, None),
                       background_color=navBtColor,
                       on_release=self.on_toggleFullScreen)
        w.add_widget(btAdd)
        btAdd.x = self.gui.btH * 3.0
        self.navBts.append(btAdd)
Exemple #6
0
class sensors:
	
	ready = False
	running = False
	platform = ''
	context = None
	sensorsCount = 3
	# x - on side
	# y - upright
	# z - flat
	upAxisNames = {
		'x' : 'on side',
		'y' : 'portret',
		'z' : 'flat'
		}
	upAxis = "z"
	
	def __init__(self,gui):
		self.gui = gui
		self.boat = {}

		self.sensorsList = []

		self.th = TimeHelper()
		self.fa = FileActions()
		
		self.playingFromFile = False
		self.FromFile = ""
		self.FromFileData = {}
		self.replayFps = 60
		
		self.filesToPlay = self.fa.getFileList( self.gui.workingFolderAdress )
		print("files to play --\ \n",str(self.filesToPlay))
		sPlaFroFil = Spinner(
			values = list(self.filesToPlay),
			text = "play from file:",
			size_hint = (None,None),
			size = (self.gui.btH*4,self.gui.btH)		
			)
		sPlaFroFil.bind(text=self.on_PlaFroFile)
		bl = self.gui.rl.ids.bl_sensorsPlaFroFil
		bl.add_widget(sPlaFroFil)
		
		print("new Spinner with updated list DONE")
		#self.wHeelBoat = waveCicleHolder(gui,'boat_heel')
		
		
		self.calibrateStep = 0
		self.recordToFile = "ready"
		self.toFileList = []
		
		self.mic = micData(gui)
		#self.mic.runIt()
		self.device = deviceSensors(gui)
		self.sensorsList.append( self.device )
		self.device.initSensors()
		
		
		self.gpsD = gpsData(gui, {
			'lat': self.gui.rl.ids.senLGpsLat,
			'lon': self.gui.rl.ids.senLGpsLon,
			'sog': self.gui.rl.ids.senLGpsSog,
			'lSRacSog': self.gui.rl.ids.lSRacSog,
			'lSRacSogMax': self.gui.rl.ids.lSRacSogMax,
			'lSRacSogAvg': self.gui.rl.ids.lSRacSogAvg,
			'cog': self.gui.rl.ids.senLGpsCog,
			'accur': self.gui.rl.ids.senLGpsAcc
			})
		self.sensorsList.append( self.gpsD )
		
		self.gyro = xyzData(gui, "gyro", [
			self.gui.rl.ids.senLGyrX,
			self.gui.rl.ids.senLGyrY,
			self.gui.rl.ids.senLGyrZ
			])
		self.sensorsList.append( self.gyro )
		
		self.gyroFlipt = xyzData(gui, "gyroFlipt",[
			self.gui.rl.ids.senLGyrCalX,
			self.gui.rl.ids.senLGyrCalY,
			self.gui.rl.ids.senLGyrCalZ
			])
		self.sensorsList.append( self.gyroFlipt )
		
		self.accel = xyzData(gui, "accel", [
			self.gui.rl.ids.senLAccX,
			self.gui.rl.ids.senLAccY,
			self.gui.rl.ids.senLAccZ
			])
		self.sensorsList.append( self.accel )
		
		self.spacialOrientation = xyzData(gui, "spacorientation", [
			self.gui.rl.ids.senLSpaOriX,
			self.gui.rl.ids.senLSpaOriY,
			self.gui.rl.ids.senLSpaOriZ
			])
		self.sensorsList.append( self.spacialOrientation )
		
		self.accelFlipt = xyzData(gui, "accelFlipt")
		self.sensorsList.append( self.accelFlipt )
		
		self.orientation = xyzData(gui, "orientation")
		self.sensorsList.append( self.orientation )
		
		self.comCal = xyzData(gui, "comCal", [
			self.gui.rl.ids.senLComCalX,
			self.gui.rl.ids.senLComCalY,
			self.gui.rl.ids.senLComCalZ
			])
		self.sensorsList.append( self.comCal )
		
		self.comCalAccelGyro = xyzData(gui, "comCalAccelGyro")
		self.sensorsList.append( self.comCalAccelGyro )
		
		if kivy.platform == 'android':
			#self.request_android_permissions2()
			print("trying ... gps ...")
			try:
				gps.configure( 
					on_location=self.on_gps_location,
					on_status=self.on_gps_status
					)
				self.request_android_permissions1()
				print("	gps OK")
			except:
				print("no gps :(")
				
				
			print("trying ... accelerometers ...")
			try:
				accelerometer.enable()
				print("	accelerometers OK")
			except:
				print("no accelerometers")
				
			print("trying ... spacial orientation ...")
			try:
				spatialorientation.enable_listener()
				print("	spacial orientation OK")
			except:
				print("no spacial orientation")
				
			print("trying ... gyroscope ...")
			try:
				gyroscope.enable()
				print("	gyroscope OK")
			except:
				print("no accelerometers")
		
			print("trying ... compass calibrated...")
			try:
				compass.enable()
				print("	compass calibrated OK")
			except:
				print("no compass calibrated")
	
	def sinHistoryArrayToGraph(self, a=[],avgSize=90):
		if len(a)>0:
			points = []
			pOld = 0.0
			try:
				m = min (a[-avgSize:])
				pdif = 1.0/(max(a[-avgSize:])-m)
				for i,y in enumerate(a):
					pOld = (y + pOld )/2.0
					points.append([i,(pOld-m)*pdif])
				return points
			except:
				return [[0,0]]
		else:
			return [[0,0]]
	
	def sinWaveAnalitic(self,buf,samplingSize_=30):
		blen = len(buf)
		bavg = sum(buf)/blen
		bmin = min(buf)
		bmax = max(buf)
		
		bufforMinimumAnalitic = 30
		samplingSize = samplingSize_
		
		upSlopesC = 0
		downSlopesC = 0
		slop = 0
		
		if blen > bufforMinimumAnalitic:
			lastSlopeDir = 0
			for i in range(30,blen,1):
				sufix = sum(buf[ i-samplingSize:i ])/(samplingSize-1)
				slop = 0
				if sufix > bavg:
					slop = 1
				else:
					slop = -1
					
				if lastSlopeDir != slop:
					
					if slop > 0:
						upSlopesC+=1
					else:
						downSlopesC+=1
					
					lastSlopeDir = slop
		
		return {
			'last': buf[-1],
			'filtert': (sum(buf[-4:])/3.0),
			'ups': upSlopesC,
			'downs': downSlopesC,
			'len': blen,
			'avg': bavg,
			'min': bmin,
			'max': bmax,
			'current': slop
			}
			
	
	def calibrateIter(self):
		print("calibrate iter [%s]"%self.calibrateStep)
		step = self.calibrateStep
		calLastFor = self.th.getTimestamp() - self.calibationTimeStart
		
		if calLastFor > (60*5): # 5 min
			self.calibrateStep = 0
			self.queryMessage.dismiss()
		
		if step == 1:
			bufLen = len(self.calBuf)
			self.calCompas.append(self.comCal.hdg)
			comRes = self.sinWaveAnalitic(self.calCompas)
			print("	calibrate gyro [ ups %s downs %s ]" % ( comRes['ups'], comRes['downs'] ) )
			gf = self.gyroFlipt.getVals()
			self.calBuf['x'].append(gf[0])
			self.calBuf['y'].append(gf[1])
			self.calBuf['z'].append(gf[2])
			self.calHeel.append(self.orientation.x)
			self.calPitch.append(self.orientation.y)
			
			print("z axis:")
			print( self.sinWaveAnalitic(self.calBuf['z']) )
			print("compas axis:")
			print( comRes )

			whatInOn = str("calibrating in progress ... [%s/2][%s/2] %s"%(comRes['ups'],comRes['downs'],round(self.comCal.hdg,1)))
			
			self.queryMessage.ids.bt_cancel.text = str(
				self.th.getNiceHowMuchTimeItsTaking( calLastFor ) 
				)
			
			#self.gui.rl.ids.bModSimCal.text = whatInOn
			self.queryMessage.title = whatInOn
			
			waitUpTo = 2
			if comRes['ups'] == waitUpTo and comRes['downs'] == waitUpTo:
				step = 2
			
		if step == 2:
			avgx = sum(self.calBuf['x'])/len(self.calBuf['x'])
			avgy = sum(self.calBuf['y'])/len(self.calBuf['y'])
			avgz = sum(self.calBuf['z'])/len(self.calBuf['z'])
			
			tSpand = float(self.th.getTimestamp() - self.calTStart)
			heelHz = (self.sinWaveAnalitic(self.calBuf['x'],4)['downs']/tSpand)
			pitchHz = (self.sinWaveAnalitic(self.calBuf['y'],4)['downs']/tSpand)
			self.gui.rl.ids.lModSimGyroHeelHz.text = str(round(heelHz,2))
			self.gui.rl.ids.lModSimGyroPitchHz.text = str(round(pitchHz,2))
			
			print("	avg ",avgx,avgy, avgz)
			self.gyroFlipt.setOffset([avgx,avgy,avgz])
			
			self.orientation.setOffset([
				sum(self.calHeel)/len(self.calHeel),
				sum(self.calPitch)/len(self.calPitch),
				0.0
				])
			
			self.calBuf = {'x':[], 'y':[],'z':[]}
			self.calCompas = []
			self.calibrateStep = 0 
			self.gui.rl.ids.bModSimCal.text = str("Calibrated at %s"%self.th.getNiceDateFromTimestamp())
			self.queryMessage.dismiss()
		
			dataToFila = {
				"gyroFlipt.offset": [avgx,avgy,avgz],
				"orientation.offset": [
					sum(self.calHeel)/len(self.calHeel),
					sum(self.calPitch)/len(self.calPitch),
					0.0
					],
				"heelHz": heelHz,
				"pitchHz": pitchHz
				}
			
			DataSR_save(dataToFila, "ykpilot_calibration.conf")
			print("config file on drive. ykpilot_calibration.conf")
			
		
	def calibrate(self):
		print("calibrate")
		self.calTStart = self.th.getTimestamp()
		self.calCompas = []
		self.calHeel = []
		self.calPitch = []
		self.calBuf = {'x':[], 'y':[],'z':[]}
		self.calibrateStep = 1
		
		self.orientation.setOffset([0.0,0.0,0.0])
		self.gyroFlipt.setOffset([0.0,0.0,0.0])
		
		self.calibationTimeStart = self.th.getTimestamp()
		self.queryMessage = QueryPopup()
		self.queryMessage.setAction(
			"Calibrating ...", 
			"In the process of calibarion gyro, heel, pitch sensor...", 
			self.on_calibation_cancel, "Cancel calibration now!", 
			None, None
			)
		self.queryMessage.run()
	
	def on_calibation_cancel(self):
		print("on_calibation_cancel")
		self.calibrateStep = 0
		
	
	def buidPlayer(self, toReturn ):
		print("buidPlayer ---------------------------------------------------")
		bl = BoxLayout(
			orientation="vertical",
			)
		bl.add_widget(toReturn)
		self.playerBL = BoxLayout(
			orientation = "horizontal",
			size_hint = (self.gui.btH, None),
			height = self.gui.btH
			) 
		self.playerBt = Button(
			text=">",
			size_hint = (None, None),
			size = (self.gui.btH, self.gui.btH)
			)
		self.playerBt.bind(on_release=self.on_PlayFromFile_play)
		self.playerBL.add_widget(self.playerBt)
		self.playerSeek = Slider(
			min = 0.0,
			max = 1.0,
			value = 0.0,
			size_hint = ( None, None),
			size = (self.gui.btH*2, self.gui.btH)
			)
		self.gui.rl.bind(size=self.playerUpdateSize)
		self.playerBL.add_widget(self.playerSeek)
		self.playerTimer = Label(
			text="00:00:00",
			size_hint = (None, None),
			size = (self.gui.btH*4.1, self.gui.btH)
			)
		self.playerBL.add_widget(self.playerTimer)
		bl.add_widget(self.playerBL)
		
		#self.playerBL.height = 0.0
		#self.playerBL.visible = False
		self.playerHide()
		
		if self.gui.platform == 'pc':
			self.on_PlaFroFile(None, "ykpilot_record_2020_05_16_17_30_58.rec")
		
		return bl
		
		
	
	def playerShow(self):
		self.gui.hide_widget( self.playerBL, False )
			
	def playerHide(self):
		self.gui.hide_widget( self.playerBL )
		
		
	def playerUpdateSize(self, *args):
		self.playerSeek.width = self.gui.rl.width - (self.gui.btH*4.2)
		#self.playerTimer.pos = self.playerSeek.pos
		
	def on_PlaFroFile(self,obj,text):
		print("on_PlaFroFile [",text,"]")
		self.playerShow()
		file = "%s%s" % (
			self.gui.workingFolderAdress,
			text
			)
		print("loading file [",file,"]")
		self.FromFileData = DataSR_restore(file)
		print("	element in file",len(self.FromFileData))
		d = self.FromFileData
		tStart = d[0]['timeStamp']
		tEnd = d[-1]['timeStamp']
		self.playerTimer.text = self.th.getNiceHowMuchTimeItsTaking( tEnd-tStart )
		self.playerSeek.max = tEnd-tStart
		self.playerSeek.value = 0.0
		self.replayTStart = tStart
		self.replayTCurrent = 0.0
		self.replayTLast = 0.0
		

	
	def on_PlayFromFile_play(self,obj):
		print("on_PlayFromFile_play")
		if self.playingFromFile == False:
			print("pause")
			self.playingFromFile = True
			self.playerBt.text = "||"
			self.playerIterClock = Clock.schedule_interval(self.playerIter, 1.0/float(self.replayFps))
		else:
			print("play")
			self.playingFromFile = False
			self.playerBt.text = ">"
			Clock.unschedule( self.playerIterClock )
			
	
	def playerIter(self, a):
		try:
			aobeo = self.replayTCurrent
		except:
			print("EE - player Iter but no file to play :(")
			return 0
		
		self.replayTCurrent+= 1.0/float(self.replayFps)
		self.playerSeek.value = self.replayTCurrent
		
		#print("player", self.replayTCurrent)
		for e in self.FromFileData:
			tStart = self.replayTStart+self.replayTLast
			tEnd = self.replayTStart+self.replayTCurrent
			if e['timeStamp'] > tStart and e['timeStamp'] <= tEnd:
				#print("gps", e['gps'][0:2])
				
				try:
					self.gui.sen.gpsD.update({
						'lat': e['gps'][0],
						'lon': e['gps'][1],
						'bearing': e['gps'][2],
						'speed': e['gps'][3],
						'accuracy': 0.0					
						})
				except:
					pass
				
				self.gui.sen.gyro.setVal( e['gyro'] )
				self.gui.sen.accel.setVal( e['accel'] )
				self.gui.sen.comCal.setVal( e['comCal'] )
				self.gui.sen.spacialOrientation.setVal( e['space'] )
				
		self.replayTLast = self.replayTCurrent	
		
		if self.replayTLast > (tEnd):
			self.on_PlayFromFile_play(None)	
	
	def on_recordToFile(self):
		#print("on_recordToFile ",self.recordToFile)
		if self.recordToFile == "active":
			self.recordToFile = "ready"
			if len(self.toFileList)>0:
				fileName = "%srecord_%s.rec"% (
					self.gui.workingFolderAdress,
					self.th.getNiceFileNameFromTimestamp() 
					)
				DataSR_save(self.toFileList, fileName)
				print("writing lines (%s) to file %s"%(len(self.toFileList),fileName))
				self.toFileList = []
			self.gui.rl.ids.b_sensorsRecToFil.text = "Record to file"	
		else:
			self.recordToFile = "active"
			self.gui.rl.ids.b_sensorsRecToFil.text = "recording ..."	

	@mainthread
	def on_gps_location(self, **kwargs):
		#print("gps raw(%s)"%(kwargs))
		self.gpsD.update(kwargs)
	
	@mainthread
	def on_gps_status(self, stype, status):
		if status == 'gps: available':
			self.gpsD.status = 'ready'
		else:
			self.gpsD.status = 'busy'
		print("gps status stype(%s) status(%s)"%(stype,status))
		
	def request_android_permissions1(self):
		print("request permissions ")
		from android.permissions import request_permissions, Permission

		def callback( permissions, results):
			if all([res for res in results]):
				print("permissions OK!")
			else:
				print("permissions no bueno :(")
				
		request_permissions([Permission.ACCESS_COARSE_LOCATION,
                             Permission.ACCESS_FINE_LOCATION,
							 Permission.WRITE_SETTINGS,
							 Permission.READ_EXTERNAL_STORAGE,
							 Permission.WRITE_EXTERNAL_STORAGE,
							 Permission.WAKE_LOCK		
                             ], callback)
	
	
	
	def gps_start(self, mt, md):
		print("gps_start")
		gps.start(mt,md)
		
	def gps_stop(self):
		print("gps_stop")
		gps.stop()
	
	def update(self,fromWho, vals):
		#print("sensors.update fromWho[{}]".format(fromWho))
		self.boat = {
			'cogError': 0.0,
			'hdg': self.comCal.hdg,
			'cog': self.gpsD.cog,
			'sog': self.gpsD.sog,
			'lat': self.gpsD.lat,
			'lon': self.gpsD.lon,
			'gRot': self.gyroFlipt.axis['z'][-1] if len(self.gyroFlipt.axis['z'])>0 else 0.0
			}
	
	def interval(self,u):
		debPrints = False
		if debPrints: print("sensors.interval...")
		
		self.device.iter()
		
		try:
			accelVal = accelerometer.acceleration[:3]
			if debPrints: print("accelVal %s	%s	%s"%(accelVal[0],accelVal[1],accelVal[2]))
			if not accelVal == (None,None,None):
				self.accel.setVal(list(accelVal))
		except Exception:
			if debPrints: print("accelerometer nooo :(")	
			if debPrints: print( traceback.format_exc() )
		
		try:
			space = spatialorientation.orientation
			for i in range(0,3,1):
				space[i] = math.degrees(space[i])
			if debPrints: print("spatialorientation %s	%s	%s"%(space[0],space[1],space[2]))
			if not space == (None,None,None):
				self.spacialOrientation.setVal(list(space))
		except Exception:
			if debPrints: print("spatialorientation nooo :(")	
			if debPrints: print( traceback.format_exc() )
		
		try:
			gyroVal = gyroscope.rotation
			if debPrints: print("gyroVal")
			#print(gyroVal)
			if gyroVal[:3] != (None, None, None):
				self.gyro.setVal(list(gyroVal[:3]))
		except Exception:
			if debPrints: print("gyroscope nooo :(")
			if debPrints: print( traceback.format_exc() )
			
			
		try:
			compVal = compass.orientation
			if debPrints: print("compVal")
			#print(compVal)
			if compVal[:3] != (None, None, None):
				self.comCal.setVal(list(compVal[:3]))
		except Exception:
			if debPrints: print("compass calibrated nooo :(")
			if debPrints: print( traceback.format_exc() )
		
		if self.calibrateStep != 0:
			self.calibrateIter()

		if self.recordToFile == "active":
			line = {
				"gps": self.gpsD.getVals(),
				"timeStamp": self.th.getTimestamp(True),
				"accel": self.accel.getVals(),
				"gyro": self.gyro.getVals(),
				"comCal": self.comCal.getVals(),
				"space": self.spacialOrientation.getVals()
				}
			self.toFileList.append(line)

	def run(self):
		#pass
		#self.mic.runIt()
		iterTime = (1.0/15.0) if self.gui.platform == 'android' else 1.0
		self.intervalEvent = Clock.schedule_interval( self.interval, iterTime )