Example #1
0
def main():
	botname = None
	voiceword = None
	ircserver = None
	broadcastchan = None
	try:
		cfg = Conf.get('voicebot')
		botname = cfg.get('name')
		voiceword = cfg.get('voiceword')
		ircserver = Conf.get('ircserver')
		broadcastchan = Conf.get('broadcastchan')
	except:
		print "Error: Bad Configuration!"
		print ""
		print "You need a voicebot section with a name and voiceword configured"
		print "Also, ircserver and broadcastchan are needed"
		return 1
	
	print "Voicebot is starting.."
	irc = irclib.IRC()
	irc.add_global_handler("pubmsg", lambda c, e: voiceThem(broadcastchan, voiceword, c, e), -20)
	server = irc.server()
	server.connect(ircserver[0], ircserver[1], botname)
	server.join(broadcastchan)
	print "Connected, joining eventloop."
	irc.process_forever()
Example #2
0
 def __init__(self):
     conf = Conf()
     conf.load('dspd.properties','../config')
     self.statuslog = StatusLog(conf,prefix = 'status_log_local')
     self.conf = conf
     self.dspd_key = conf.get('dspd_key_name')
     self.ard_key = conf.get('ard_key_name')
Example #3
0
def main():
    ''' Start the main application interface '''
    app=QtWidgets.QApplication(sys.argv)

    # Initiate the global configuration
    global conf
    conf=Conf()
    
    # Clean the log file
    if(conf.get("clean_log")=="yes"):
        open(LOG_FILE, "w").close()

    # Show splash-screen
    if(conf.get("splash_screen")=="yes"):
        ss=True
    else:
        ss=False
    if(ss):
        splash=QtWidgets.QSplashScreen(QtWidgets.QPixmap("icons/splash.png"))
        splash.show()
        time.sleep(0.1)
        app.processEvents()
        splash.showMessage("Loading...")

    # Create main window
    w=Window()
    if(ss):
        splash.finish(w)

    # Start application
    sys.exit(app.exec_())
Example #4
0
def main():
    botname = None
    voiceword = None
    ircserver = None
    broadcastchan = None
    try:
        cfg = Conf.get('voicebot')
        botname = cfg.get('name')
        voiceword = cfg.get('voiceword')
        ircserver = Conf.get('ircserver')
        broadcastchan = Conf.get('broadcastchan')
    except:
        print "Error: Bad Configuration!"
        print ""
        print "You need a voicebot section with a name and voiceword configured"
        print "Also, ircserver and broadcastchan are needed"
        return 1

    print "Voicebot is starting.."
    irc = irclib.IRC()
    irc.add_global_handler(
        "pubmsg", lambda c, e: voiceThem(broadcastchan, voiceword, c, e), -20)
    server = irc.server()
    server.connect(ircserver[0], ircserver[1], botname)
    server.join(broadcastchan)
    print "Connected, joining eventloop."
    irc.process_forever()
Example #5
0
    def __init__(self, dev):
        threading.Thread.__init__(self)
        self.daemon = True
        self.context = pyudev.Context()

        self.dev = dev

        self.mountpoint = Conf.get("mountpoint")
        self.attrs = Conf.get("udevAttrs")
Example #6
0
	def __init__(self, dev):
		threading.Thread.__init__(self)
		self.daemon = True
		self.context = pyudev.Context()

		self.dev = dev

		self.mountpoint = Conf.get("mountpoint")
		self.attrs = Conf.get("udevAttrs")
Example #7
0
class Alias:
    ''' Provides the class to handle symptom aliases '''
    
    def __init__(self, conf=False):
        '''
        Initiates the alias object
        Accepts a Conf object as parameter
        '''
        self.data={}
        if(conf):
            self.conf=conf
        else:
            self.conf=Conf()
        self.compile()

    def compile(self):
        ''' Compile the plaintext index files to a program usable format '''
        # Loop over the alias files
        for path, subdirs, files in os.walk(self.conf.get("alias_path")):
            for name in files:
                if(fnmatch(name, "*.txt")):
                    # Open the *.txt files
                    with open(self.conf.get("alias_path")+name, "r") as f:
                        for line in f:
                            # Ignore lines starting with #
                            line=line.rstrip().split("#")[0]
                            if(len(line)==0):
                                pass
                            else:
                                terms=[]
                                # Split words separated by ; and add to the terms
                                for i in line.split(";"):
                                    if(i.strip()):
                                        terms.append(i.strip())
                                # If alias present, add terms to the data
                                if(len(terms)==2):
                                    self.data[terms[-1]]=terms[0]
                                elif(len(terms)>2):
                                    t=terms.pop(0)
                                    for i in terms:
                                        self.data[i]=t

    def get(self, term):
        '''
        Return the alias of the queried symptom

        Parameter:
        term - Queried string

        Return value:
        String containing the alias of the term
        '''
        if(term in self.data):
            return self.data[term]
        else:
            return term
Example #8
0
class Alias:
    ''' Provides the class to handle symptom aliases '''
    def __init__(self, conf=False):
        '''
        Initiates the alias object
        Accepts a Conf object as parameter
        '''
        self.data = {}
        if (conf):
            self.conf = conf
        else:
            self.conf = Conf()
        self.compile()

    def compile(self):
        ''' Compile the plaintext index files to a program usable format '''
        # Loop over the alias files
        for path, subdirs, files in os.walk(self.conf.get("alias_path")):
            for name in files:
                if (fnmatch(name, "*.txt")):
                    # Open the *.txt files
                    with open(self.conf.get("alias_path") + name, "r") as f:
                        for line in f:
                            # Ignore lines starting with #
                            line = line.rstrip().split("#")[0]
                            if (len(line) == 0):
                                pass
                            else:
                                terms = []
                                # Split words separated by ; and add to the terms
                                for i in line.split(";"):
                                    if (i.strip()):
                                        terms.append(i.strip())
                                # If alias present, add terms to the data
                                if (len(terms) == 2):
                                    self.data[terms[-1]] = terms[0]
                                elif (len(terms) > 2):
                                    t = terms.pop(0)
                                    for i in terms:
                                        self.data[i] = t

    def get(self, term):
        '''
        Return the alias of the queried symptom

        Parameter:
        term - Queried string

        Return value:
        String containing the alias of the term
        '''
        if (term in self.data):
            return self.data[term]
        else:
            return term
Example #9
0
	def __init__(self):
		Ether2Any.__init__(self, tap=Conf.get('tunnelEthernet', True))
		
		handlerConf = Conf.get('handler', {'allowFrom': None, 'allowTo': None})
		self.mailHandler = NetMailHandler(self.dev, **handlerConf)
		self.mailTo = Conf.get('mailTo', None)
		self.mailFrom = Conf.get('mailFrom', None)
		
		self.smtpConf = Conf.get('smtp')
		smtpd = Conf.get("smtpd", {'enabled': False})
		if smtpd['enabled']:
			self.smtpd = SMTPServerThread(smtpd['listen'], self.mailHandler)
		else:
			self.smtpd = None
		
		imapConf = Conf.get("imap", {'enabled': False})
		if imapConf['enabled']:
			self.imap = SimpleIMAPClient(imapConf, self.mailTo, self.mailHandler)
		else:
			self.imap = None
		
		self.generator = SpamGenerator()
		
		network = Conf.get('network', {'mtu': 1400})
		self.dev.ifconfig(**network)
Example #10
0
    def __init__(self, dev, networkQueue, writeLock):
        threading.Thread.__init__(self)
        self.daemon = True
        self.quit = False
        self.packetCounter = 0

        self.dev = dev
        self.writeLock = writeLock
        self.networkQueue = networkQueue

        self.mountpoint = Conf.get("mountpoint")
        self.usbNetworkDir = Conf.get("usbNetworkDir")
        self.networkFilePrefix = Conf.get("networkFilePrefix")

        self.writePath = self.mountpoint + "/" + self.usbNetworkDir + "/"
Example #11
0
	def __init__(self, dev, networkQueue, writeLock):
		threading.Thread.__init__(self)
		self.daemon = True
		self.quit = False
		self.packetCounter = 0
		
		self.dev = dev
		self.writeLock = writeLock
		self.networkQueue = networkQueue
		
		self.mountpoint = Conf.get("mountpoint")
		self.usbNetworkDir = Conf.get("usbNetworkDir")
		self.networkFilePrefix = Conf.get("networkFilePrefix")
		
		self.writePath = self.mountpoint + "/" + self.usbNetworkDir + "/"
Example #12
0
	def __init__(self, debug=False):
		Ether2Any.__init__(self, tap=False)
		
		self.debug = debug
		network = Conf.get("network", {'mtu': 1400})
		self.coder = Conf.get("coder", None)
		self.twitterConf = Conf.get("twitter", None)
		self.endpoint = self.twitterConf['endpoint']
		if not self.endpoint:
			print "No endpoint in configuration, please add one."
			sys.exit(1)
		self.dev.ifconfig(**network)
		self.dev.up()

		self._setupTwitter()
		self.downstream = DownstreamThread(dev=self.dev, coder=self.coder, auth=self.auth, endpoint=self.endpoint, debug=self.debug)
		self.downstream.start()
Example #13
0
    def __init__(self, dev, usbwriter, writeLock):
        threading.Thread.__init__(self)
        self.daemon = True
        self.quit = False
        self.packetCounter = 0

        self.dev = dev
        self.usbwriter = usbwriter
        self.writeLock = writeLock
        self.context = pyudev.Context()

        self.mountpoint = Conf.get("mountpoint")
        self.usbNetworkDir = Conf.get("usbNetworkDir")
        self.networkFilePrefix = Conf.get("networkFilePrefix")
        self.sync = Conf.get("sync")

        self.writePath = self.mountpoint + "/" + self.usbNetworkDir + "/"
        self.attrs = Conf.get("udevAttrs")
        self.devname = None
Example #14
0
	def __init__(self):
		Ether2Any.__init__(self, tap=False)
		
		network = Conf.get("network", {'mtu': 1500})
		
		self.dev.ifconfig(**network)
		self.dev.up()
		
		self.reader = UdevReader(self.dev)
		self.reader.start()
Example #15
0
    def __init__(self):
        Ether2Any.__init__(self, tap=False)

        network = Conf.get("network", {'mtu': 1500})

        self.dev.ifconfig(**network)
        self.dev.up()

        self.reader = UdevReader(self.dev)
        self.reader.start()
Example #16
0
	def __init__(self, dev, usbwriter, writeLock):
		threading.Thread.__init__(self)
		self.daemon = True
		self.quit = False
		self.packetCounter = 0
		
		self.dev = dev
		self.usbwriter = usbwriter
		self.writeLock = writeLock
		self.context = pyudev.Context()
		
		self.mountpoint = Conf.get("mountpoint")
		self.usbNetworkDir = Conf.get("usbNetworkDir")
		self.networkFilePrefix = Conf.get("networkFilePrefix")
		self.sync = Conf.get("sync")
		
		self.writePath = self.mountpoint + "/" + self.usbNetworkDir + "/"
		self.attrs = Conf.get("udevAttrs")
		self.devname = None
Example #17
0
	def __init__(self):
		# device
		Ether2Any.__init__(self, tap=True)
		self.qrlog = self.setupLogging("QrNet")
		self.mqueue = Queue.Queue()
		self.squeue = Queue.Queue()
		self.setTimeout(1)
		
		network = Conf.get("network", {'mtu': 400})
		self.packetDrop = Conf.get("packetDrop", 20)
		
		self.dev.ifconfig(**network)
		self.dev.up()
		
		# thread starting...
		gtk.gdk.threads_init()
		
		self.cam = CamThread(self.dev, self.squeue, self.setupLogging("CamThread"))
		self.cam.start()
		self.display = DisplayThread(self.dev, self.mqueue, self.squeue, self.setupLogging("DisplayThread"))
		self.display.start()
Example #18
0
    def __init__(self, debug=False):
        Ether2Any.__init__(self, tap=False)

        self.debug = debug
        network = Conf.get("network", {'mtu': 1400})
        self.coder = Conf.get("coder", None)
        self.twitterConf = Conf.get("twitter", None)
        self.endpoint = self.twitterConf['endpoint']
        if not self.endpoint:
            print "No endpoint in configuration, please add one."
            sys.exit(1)
        self.dev.ifconfig(**network)
        self.dev.up()

        self._setupTwitter()
        self.downstream = DownstreamThread(dev=self.dev,
                                           coder=self.coder,
                                           auth=self.auth,
                                           endpoint=self.endpoint,
                                           debug=self.debug)
        self.downstream.start()
Example #19
0
    def __init__(self):
        Ether2Any.__init__(self, tap=False)

        network = Conf.get("network", {'mtu': 1400})
        self.dev.ifconfig(**network)
        self.dev.up()

        self.networkQueue = Queue.Queue()
        self.writeLock = threading.Lock()
        self.writeLock.acquire()

        self.usb = USBWriter(self.dev, self.networkQueue, self.writeLock)
        self.usb.start()

        self.udev = UdevHandler(self.dev, self.usb, self.writeLock)
        self.udev.start()
Example #20
0
	def __init__(self, dev, squeue, camlog):
		threading.Thread.__init__(self)
		
		self.dev = dev
		self.squeue = squeue
		self.camlog = camlog
		
		self.frame = 0
		self.reportAfter = 20 # frames
		self.quit = False
		self.success = 0
		self.lastPacket = ""
		
		self.reader = highgui.cvCreateCameraCapture(Conf.get("camnum", 0))
		self.scanner = zbar.ImageScanner()
		self.scanner.parse_config('enable')
Example #21
0
	def __init__(self):
		Ether2Any.__init__(self, tap=False)
		
		network = Conf.get("network", {'mtu': 1400})
		self.dev.ifconfig(**network)
		self.dev.up()
		
		self.networkQueue = Queue.Queue()
		self.writeLock = threading.Lock()
		self.writeLock.acquire()
		
		self.usb = USBWriter(self.dev, self.networkQueue, self.writeLock)
		self.usb.start()
		
		self.udev = UdevHandler(self.dev, self.usb, self.writeLock)
		self.udev.start()
Example #22
0
class Deploy:

	def __init__(self):
		self.config = Conf()
		self.console = Console()

	def path(self, option):
		path = self.config.get(option)
		return os.path.abspath(path);

	def chown(self, path):
		user = self.config.get('deploy_user')
		self.console.run(['chown', '-R', user, path])

	def linkdir(self, src, dst):
		self.console.run(['ln', '-sfn', src, dst])

	def version(self, deploy_path):
		hash = self.console.run(['git', 'rev-parse', 'HEAD'], cwd=deploy_path);
		return hash[0:8]

	def hostname(self):
		hostname = self.console.run(['hostname', '-f'], output=False);
		return hostname

	def sync(self, src, dst):
		if os.path.exists(src) == False:
			os.makedirs(src, 0755)

		self.console.run([
			'rsync',
			'--links',
			'--checksum',
			'--whole-file',
			'--recursive',
			src.rstrip('/') + '/',
			dst
		])

	def checkout(self):
		deploy_path = self.path('release_path') + '/' + time.strftime('%Y%m%d%H%M%S')

		if os.path.exists(deploy_path) == False:
			os.makedirs(deploy_path, 0755)

		gitclone = ' '.join([
			'git',
			'clone',
			'--quiet',
			'--recursive',
			'--depth', '1',
			'--branch', self.config.get('repo_branch'),
			self.config.get('repo_url'),
			deploy_path
		])

		sshadd = ' '.join([
			'ssh-add',
			self.config.get('deploy_key')
		])

		self.console.success('Fetching files')
		self.console.execute('ssh-agent sh -c \'' + sshadd + '; ' + gitclone + '\'')

		return deploy_path

	def composer(self, deploy_path):
		if os.path.exists(deploy_path + '/composer.json') == False:
			return None

		self.console.success('Installing composer dependencies')
		self.console.run([
			'composer',
			'--quiet',
			'--no-interaction',
			'install',
			'--prefer-dist',
			'--no-dev',
			'--optimize-autoloader'
		], cwd=deploy_path);

	def scripts(self, scripts_to_run, deploy_path):
		if self.config.has(scripts_to_run) == False:
			return

		scripts = self.config.get(scripts_to_run)

		for line in scripts:
			command = line.replace('$deploy_path', deploy_path)
			command = command.replace('$repo_branch', self.config.get('repo_branch'))
			command = command.replace('$repo_url', self.config.get('repo_url'))
			command = command.replace('$hostname', self.hostname())
			self.console.run(shlex.split(command), cwd=deploy_path)

	def clean(self):
		release_path = self.path('release_path')
		deployments = self.console.run(['ls', '-1tA', release_path])
		deploys_to_keep = int(self.config.get('deploys_to_keep'))

		for folder in deployments.splitlines()[deploys_to_keep:]:
			self.console.run(['rm', '-rf', folder], cwd=release_path);

	def rollback(self, version):
		deploy_path = self.path('release_path') + '/' + version

		if os.path.exists(deploy_path) == False:
			self.console.error('Version does not exist')
			return None

		self.console.success('Rolling back')
		self.linkdir(deploy_path, self.config.get('symlink'))

	def deploy(self):
		# checkout files
		deploy_path = self.checkout()

		# fetch resources
		self.composer(deploy_path)

		# static resources
		if self.config.has('static_path'):
			self.console.success('Copying static resources')
			self.sync(self.path('static_path'), deploy_path)

		if self.config.has('pre_scripts'):
			self.console.success('Running pre-scripts')
			self.scripts('pre_scripts', deploy_path)

		self.console.success('Updating file owner')
		self.chown(deploy_path)

		self.console.success('Updating symlink')
		self.linkdir(deploy_path, self.config.get('symlink'))

		if self.config.has('post_scripts'):
			self.console.success('Running post-scripts')
			self.scripts('post_scripts', deploy_path)

		self.console.success('Cleaning up old releases')
		self.clean()
Example #23
0
class MyFrame(wx.Frame):
		
		def __init__(self):

			self.conf = Conf()
			self.home = self.conf.home
			self.op_folder = self.conf.op_folder

			Language(self.conf)
			
			title = _('Moitessier HAT Setup')

			wx.Frame.__init__(self, None, title=title, size=(710,460))
			
			self.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
			
			self.icon = wx.Icon(op_folder+'/static/icons/moitessier_hat.ico', wx.BITMAP_TYPE_ICO)
			self.SetIcon(self.icon)
			self.help_bmp = wx.Bitmap(self.op_folder + "/static/icons/help-browser.png", wx.BITMAP_TYPE_ANY)

			self.p = wx.lib.scrolledpanel.ScrolledPanel(self, -1, style=wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER)
			self.p.SetAutoLayout(1)
			self.p.SetupScrolling()
			self.nb = wx.Notebook(self.p)
			self.p_info = wx.Panel(self.nb)
			self.p_settings = wx.Panel(self.nb)
			self.p_update = wx.Panel(self.nb)
			self.p_configure = wx.Panel(self.nb)
			self.nb.AddPage(self.p_info, _('HAT info'))
			self.nb.AddPage(self.p_update, _('Install drivers'))
			self.nb.AddPage(self.p_configure, _('OpenPlotter configuration'))
			self.nb.AddPage(self.p_settings, _('Play with settings'))
			sizer = wx.BoxSizer()
			sizer.Add(self.nb, 1, wx.EXPAND)
			self.p.SetSizer(sizer)

##################################################################### info

			info_box = wx.StaticBox(self.p_info, -1, _(' Info '))

			self.button_get_info =wx.Button(self.p_info, label= _('Settings'))
			self.Bind(wx.EVT_BUTTON, self.on_get_info, self.button_get_info)

			self.button_statistics =wx.Button(self.p_info, label= _('Statistics'))
			self.Bind(wx.EVT_BUTTON, self.on_statistics, self.button_statistics)

			self.button_reset_statistics =wx.Button(self.p_info, label= _('Reset statistics'))
			self.Bind(wx.EVT_BUTTON, self.on_reset_statistics, self.button_reset_statistics)

			sensors_box = wx.StaticBox(self.p_info, -1, _(' Test sensors '))

			self.button_MPU9250 =wx.Button(self.p_info, label= _('MPU-9250'))
			self.Bind(wx.EVT_BUTTON, self.on_MPU9250, self.button_MPU9250)

			self.button_MS560702BA03 =wx.Button(self.p_info, label= _('MS5607-02BA03'))
			self.Bind(wx.EVT_BUTTON, self.on_MS560702BA03, self.button_MS560702BA03)

			self.button_Si7020A20 =wx.Button(self.p_info, label= _('Si7020-A20'))
			self.Bind(wx.EVT_BUTTON, self.on_Si7020A20, self.button_Si7020A20)

			self.logger = rt.RichTextCtrl(self.p_info, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_DONTWRAP|wx.LC_SORT_ASCENDING)
			self.logger.SetMargins((10,10))

			help_button = wx.BitmapButton(self.p_info, bitmap=self.help_bmp, size=(self.help_bmp.GetWidth()+40, self.help_bmp.GetHeight()+10))
			help_button.Bind(wx.EVT_BUTTON, self.on_help)

			shop =wx.Button(self.p_info, label=_('Shop'))
			self.Bind(wx.EVT_BUTTON, self.onShop, shop)

			checkB =wx.Button(self.p_info, label=_('Check'))
			self.Bind(wx.EVT_BUTTON, self.onCheck, checkB)

			button_ok =wx.Button(self.p_info, label=_('Close'))
			self.Bind(wx.EVT_BUTTON, self.on_ok, button_ok)

			h_boxSizer1 = wx.StaticBoxSizer(info_box, wx.HORIZONTAL)
			h_boxSizer1.AddSpacer(5)
			h_boxSizer1.Add(self.button_get_info, 0, wx.ALL | wx.EXPAND, 5)
			h_boxSizer1.Add(self.button_statistics, 0, wx.ALL | wx.EXPAND, 5)
			h_boxSizer1.Add(self.button_reset_statistics, 0, wx.ALL | wx.EXPAND, 5)

			h_boxSizer3 = wx.StaticBoxSizer(sensors_box, wx.HORIZONTAL)
			h_boxSizer3.AddSpacer(5)
			h_boxSizer3.Add(self.button_MPU9250, 0, wx.ALL | wx.EXPAND, 5)
			h_boxSizer3.Add(self.button_MS560702BA03, 0, wx.ALL | wx.EXPAND, 5)
			h_boxSizer3.Add(self.button_Si7020A20, 0, wx.ALL | wx.EXPAND, 5)

			buttons = wx.BoxSizer(wx.HORIZONTAL)
			buttons.Add(help_button, 0, wx.ALL | wx.EXPAND, 0)
			buttons.Add(shop, 0, wx.LEFT | wx.EXPAND, 10)
			buttons.AddStretchSpacer(1)
			buttons.Add(checkB, 0, wx.ALL | wx.EXPAND, 0)
			buttons.Add(button_ok, 0, wx.LEFT | wx.EXPAND, 10)

			vbox3 = wx.BoxSizer(wx.VERTICAL)
			vbox3.Add(h_boxSizer1, 0, wx.ALL | wx.EXPAND, 5)
			vbox3.Add(h_boxSizer3, 0, wx.ALL | wx.EXPAND, 5)
			vbox3.Add(self.logger, 1, wx.ALL | wx.EXPAND, 5)
			vbox3.Add(buttons, 0, wx.ALL | wx.EXPAND, 5)

			self.p_info.SetSizer(vbox3)

##################################################################### settings

			gnss_box = wx.StaticBox(self.p_settings, -1, ' GNSS ')

			self.button_enable_gnss =wx.Button(self.p_settings, label= _('Enable'))
			self.Bind(wx.EVT_BUTTON, self.on_enable_gnss, self.button_enable_gnss)

			self.button_disable_gnss =wx.Button(self.p_settings, label= _('Disable'))
			self.Bind(wx.EVT_BUTTON, self.on_disable_gnss, self.button_disable_gnss)

			general_box = wx.StaticBox(self.p_settings, -1, _(' General '))

			self.button_reset =wx.Button(self.p_settings, label= _('Reset HAT'))
			self.Bind(wx.EVT_BUTTON, self.on_reset, self.button_reset)

			self.button_defaults =wx.Button(self.p_settings, label= _('Load defaults'))
			self.Bind(wx.EVT_BUTTON, self.on_defaults, self.button_defaults)

			ais_box = wx.StaticBox(self.p_settings, -1, ' AIS ')

			self.simulator = wx.CheckBox(self.p_settings, label=_('enable simulator'))

			interval_label = wx.StaticText(self.p_settings, -1, _('interval (ms)'))
			self.interval = wx.SpinCtrl(self.p_settings, min=1, max=9999, initial=1000)

			mmsi1_label = wx.StaticText(self.p_settings, -1, _('MMSI boat 1'))
			self.mmsi1 = wx.SpinCtrl(self.p_settings, min=111111, max=999999999, initial=5551122)

			mmsi2_label = wx.StaticText(self.p_settings, -1, _('MMSI boat 2'))
			self.mmsi2 = wx.SpinCtrl(self.p_settings, min=111111, max=999999999, initial=6884120)

			freq1_label = wx.StaticText(self.p_settings, -1, _('channel A [Hz]'))
			freq2_label = wx.StaticText(self.p_settings, -1, _('channel B [Hz]'))
			metamask_label = wx.StaticText(self.p_settings, -1, 'meta data')
			afcRange_label = wx.StaticText(self.p_settings, -1, 'AFC range [Hz]')

			self.rec1_freq1 = wx.SpinCtrl(self.p_settings, min=159000000, max=162025000, initial=161975000)
			self.rec1_freq2 = wx.SpinCtrl(self.p_settings, min=159000000, max=162025000, initial=162025000)
			self.rec1_metamask = wx.Choice(self.p_settings, choices=(_('none'),'RSSI'), style=wx.CB_READONLY)
			self.rec1_metamask.SetSelection(0)
			self.rec1_afcRange = wx.SpinCtrl(self.p_settings, min=500, max=2000, initial=1500)

			self.logger2 = rt.RichTextCtrl(self.p_settings, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_DONTWRAP|wx.LC_SORT_ASCENDING)
			self.logger2.SetMargins((10,10))

			help_button = wx.BitmapButton(self.p_settings, bitmap=self.help_bmp, size=(self.help_bmp.GetWidth()+40, self.help_bmp.GetHeight()+10))
			help_button.Bind(wx.EVT_BUTTON, self.on_help)

			self.button_apply =wx.Button(self.p_settings, label=_('Apply changes'))
			self.Bind(wx.EVT_BUTTON, self.on_apply, self.button_apply)

			button_ok2 =wx.Button(self.p_settings, label=_('Close'))
			self.Bind(wx.EVT_BUTTON, self.on_ok, button_ok2)

			h_boxSizer2 = wx.StaticBoxSizer(gnss_box, wx.HORIZONTAL)
			h_boxSizer2.AddSpacer(5)
			h_boxSizer2.Add(self.button_enable_gnss, 1, wx.ALL | wx.EXPAND, 5)
			h_boxSizer2.Add(self.button_disable_gnss, 1, wx.ALL | wx.EXPAND, 5)

			h_boxSizer4 = wx.StaticBoxSizer(general_box, wx.HORIZONTAL)
			h_boxSizer4.AddSpacer(5)
			h_boxSizer4.Add(self.button_reset, 1, wx.ALL | wx.EXPAND, 5)
			h_boxSizer4.Add(self.button_defaults, 1, wx.ALL | wx.EXPAND, 5)

			h_boxSizer5 = wx.BoxSizer(wx.HORIZONTAL)
			h_boxSizer5.Add(h_boxSizer2, 1, wx.RIGHT | wx.EXPAND, 10)
			h_boxSizer5.Add(h_boxSizer4, 1, wx.ALL | wx.EXPAND, 0)

			h_boxSizer6 = wx.BoxSizer(wx.HORIZONTAL)
			h_boxSizer6.Add((0,0), 1, wx.LEFT | wx.EXPAND, 5)
			h_boxSizer6.Add(interval_label, 1, wx.LEFT | wx.EXPAND, 5)
			h_boxSizer6.Add(mmsi1_label, 1, wx.LEFT | wx.EXPAND, 5)
			h_boxSizer6.Add(mmsi2_label, 1, wx.LEFT | wx.EXPAND, 5)

			h_boxSizer7 = wx.BoxSizer(wx.HORIZONTAL)
			h_boxSizer7.Add(self.simulator, 1, wx.ALL | wx.EXPAND, 5)
			h_boxSizer7.Add(self.interval, 1, wx.ALL | wx.EXPAND, 5)
			h_boxSizer7.Add(self.mmsi1, 1, wx.ALL | wx.EXPAND, 5)
			h_boxSizer7.Add(self.mmsi2, 1, wx.ALL | wx.EXPAND, 5)

			rec1_labels = wx.BoxSizer(wx.HORIZONTAL)
			rec1_labels.Add(freq1_label, 1, wx.LEFT | wx.EXPAND, 5)
			rec1_labels.Add(freq2_label, 1, wx.LEFT | wx.EXPAND, 5)
			rec1_labels.Add(metamask_label, 1, wx.LEFT | wx.EXPAND, 5)
			rec1_labels.Add(afcRange_label, 1, wx.LEFT | wx.EXPAND, 5)

			receiver1 = wx.BoxSizer(wx.HORIZONTAL)
			receiver1.Add(self.rec1_freq1, 1, wx.ALL | wx.EXPAND, 5)
			receiver1.Add(self.rec1_freq2, 1, wx.ALL | wx.EXPAND, 5)
			receiver1.Add(self.rec1_metamask, 1, wx.ALL | wx.EXPAND, 5)
			receiver1.Add(self.rec1_afcRange, 1, wx.ALL | wx.EXPAND, 5)

			v_boxSizer8 = wx.StaticBoxSizer(ais_box, wx.VERTICAL)
			v_boxSizer8.Add(h_boxSizer6, 0, wx.ALL | wx.EXPAND, 0)
			v_boxSizer8.Add(h_boxSizer7, 0, wx.ALL | wx.EXPAND, 0)
			v_boxSizer8.AddSpacer(15)
			v_boxSizer8.Add(rec1_labels, 0, wx.ALL | wx.EXPAND, 0)
			v_boxSizer8.Add(receiver1, 0, wx.ALL | wx.EXPAND, 0)
	

			buttons2 = wx.BoxSizer(wx.HORIZONTAL)
			buttons2.Add(help_button, 0, wx.ALL | wx.EXPAND, 0)
			buttons2.AddStretchSpacer(1)
			buttons2.Add(self.button_apply, 0, wx.RIGHT | wx.EXPAND, 10)
			buttons2.Add(button_ok2, 0, wx.ALL | wx.EXPAND, 0)

			vbox4 = wx.BoxSizer(wx.VERTICAL)
			vbox4.Add(h_boxSizer5, 0, wx.ALL | wx.EXPAND, 5)
			vbox4.Add(v_boxSizer8, 0, wx.ALL | wx.EXPAND, 5)
			vbox4.Add(self.logger2, 1, wx.ALL | wx.EXPAND, 5)
			vbox4.Add(buttons2, 0, wx.ALL | wx.EXPAND, 5)

			self.p_settings.SetSizer(vbox4)

##################################################################### install

			kernel_box = wx.StaticBox(self.p_update, -1, _(' Current kernel version '))

			self.kernel_label = wx.StaticText(self.p_update, -1)

			packages_box = wx.StaticBox(self.p_update, -1, _(' Available packages '))

			self.packages_list = []
			self.packages_select = wx.Choice(self.p_update, choices=self.packages_list, style=wx.CB_READONLY)
			self.readAvailable()

			self.button_install =wx.Button(self.p_update, label=_('Install'))
			self.Bind(wx.EVT_BUTTON, self.on_install, self.button_install)

			downloadB =wx.Button(self.p_update, label=_('Download'))
			self.Bind(wx.EVT_BUTTON, self.onDownload, downloadB)

			drivers =wx.Button(self.p_update, label=_('All drivers'))
			self.Bind(wx.EVT_BUTTON, self.onDrivers, drivers)

			self.logger3 = rt.RichTextCtrl(self.p_update, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_DONTWRAP|wx.LC_SORT_ASCENDING)
			self.logger3.SetMargins((10,10))

			help_button = wx.BitmapButton(self.p_update, bitmap=self.help_bmp, size=(self.help_bmp.GetWidth()+40, self.help_bmp.GetHeight()+10))
			help_button.Bind(wx.EVT_BUTTON, self.on_help)

			button_ok3 =wx.Button(self.p_update, label=_('Close'))
			self.Bind(wx.EVT_BUTTON, self.on_ok, button_ok3)

			v_kernel_box = wx.StaticBoxSizer(kernel_box, wx.VERTICAL)
			v_kernel_box.AddSpacer(5)
			v_kernel_box.Add(self.kernel_label, 0, wx.ALL | wx.EXPAND, 5)

			h_packages_box = wx.StaticBoxSizer(packages_box, wx.HORIZONTAL)
			h_packages_box.Add(self.packages_select, 1, wx.ALL | wx.EXPAND, 5)
			h_packages_box.Add(self.button_install, 0, wx.ALL | wx.EXPAND, 5)
			h_packages_box.Add(downloadB, 0, wx.ALL | wx.EXPAND, 5)
			h_packages_box.Add(drivers, 0, wx.ALL | wx.EXPAND, 5)

			buttons3 = wx.BoxSizer(wx.HORIZONTAL)
			buttons3.Add(help_button, 0, wx.ALL | wx.EXPAND, 0)
			buttons3.AddStretchSpacer(1)
			buttons3.Add(button_ok3, 0, wx.ALL | wx.EXPAND, 0)

			update_final = wx.BoxSizer(wx.VERTICAL)
			update_final.Add(v_kernel_box, 0, wx.ALL | wx.EXPAND, 5)
			update_final.Add(h_packages_box, 0, wx.ALL | wx.EXPAND, 5)
			update_final.Add(self.logger3, 1, wx.ALL | wx.EXPAND, 5)
			update_final.Add(buttons3, 0, wx.ALL | wx.EXPAND, 5)

			self.p_update.SetSizer(update_final)

##################################################################### configure

			checkConfB =wx.Button(self.p_configure, label= _('Check'))
			self.Bind(wx.EVT_BUTTON, self.onCheckConfB, checkConfB)

			self.logger4 = rt.RichTextCtrl(self.p_configure, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_DONTWRAP|wx.LC_SORT_ASCENDING)
			self.logger4.SetMargins((10,10))

			help_button = wx.BitmapButton(self.p_configure, bitmap=self.help_bmp, size=(self.help_bmp.GetWidth()+40, self.help_bmp.GetHeight()+10))
			help_button.Bind(wx.EVT_BUTTON, self.on_help)

			button_ok4 =wx.Button(self.p_configure, label=_('Close'))
			self.Bind(wx.EVT_BUTTON, self.on_ok, button_ok4)

			buttons4 = wx.BoxSizer(wx.HORIZONTAL)
			buttons4.Add(help_button, 0, wx.ALL | wx.EXPAND, 0)
			buttons4.AddStretchSpacer(1)
			buttons4.Add(checkConfB, 0, wx.ALL | wx.EXPAND, 0)
			buttons4.Add(button_ok4, 0, wx.LEFT | wx.EXPAND, 10)

			vbox5 = wx.BoxSizer(wx.VERTICAL)
			vbox5.Add(self.logger4, 1, wx.ALL | wx.EXPAND, 5)
			vbox5.Add(buttons4, 0, wx.ALL | wx.EXPAND, 5)

			self.p_configure.SetSizer(vbox5)

#####################################################################

			self.Centre()
			self.read()

		def onCheckConfB(self,e=0):
			self.conf = Conf()
			self.SK_settings = SK_settings(self.conf)
			self.opencpnSettings = opencpnSettings()
			self.logger4.Clear()

			serialInst = self.conf.get('UDEV', 'Serialinst')
			try: serialInst = eval(serialInst)
			except: serialInst = {}
			serialalias = ''
			assignment = ''
			device = ''
			for alias in serialInst:
				if serialInst[alias]['device'] == '/dev/moitessier.tty' and serialInst[alias]['data'] == 'NMEA 0183': 
					serialalias = alias
					assignment = serialInst[alias]['assignment']
					device = self.SK_settings.check_device(alias)

			pypilot = self.conf.get('PYPILOT', 'mode')
			heading = self.conf.get('PYPILOT', 'translation_magnetic_h')
			attitude = self.conf.get('PYPILOT', 'translation_attitude')

			i2c = self.conf.get('I2C', 'sensors')
			try: i2c = eval(i2c)
			except: i2c = {}
			pressure = ''
			temperature = ''
			for sensor in i2c:
				if sensor[0] == 'MS5607-02BA03' and sensor[1] == '0x77':
					pressure = sensor[2][0][0]
					temperature = sensor[2][1][0]

			XDRBaro = False
			SKplugin = False
			setting_file = self.home+'/.signalk/plugin-config-data/sk-to-nmea0183.json'
			if os.path.isfile(setting_file):
				with open(setting_file) as data_file:
					data = ujson.load(data_file)
				if 'enabled' in data: SKplugin = data['enabled']
				if 'configuration' in data:
					if 'XDRBaro' in data['configuration']: XDRBaro = data['configuration']['XDRBaro']

			opencpnConnection = self.opencpnSettings.getConnectionState()

			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.BeginBold()
			self.logger4.WriteText('AIS - GNSS')
			self.logger4.EndBold()
			self.logger4.Newline()
			self.logger4.WriteText(_('Serial alias: '))
			self.logger4.EndTextColour()
			if serialalias:
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(serialalias)
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('none'))
			self.logger4.EndTextColour()
			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.WriteText(_('Assignment: '))
			self.logger4.EndTextColour()
			if not assignment:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('none'))
			elif assignment != 'GPSD':
				if assignment == '0': x = _('manual')
				else: x = assignment
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(x)
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(assignment)
			self.logger4.EndTextColour()
			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.WriteText(_('Signal K connection status: '))
			self.logger4.EndTextColour()
			if not assignment:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('none'))
			elif assignment == '0' or assignment == 'GPSD' or assignment == 'Signal K > OpenCPN':
				if device == 'enabled':
					self.logger4.BeginTextColour((0, 255, 0))
					self.logger4.WriteText(_('enabled'))
				elif device == 'disabled':
					self.logger4.BeginTextColour((255, 0, 0))
					self.logger4.WriteText(_('disabled'))
				else:
					self.logger4.BeginTextColour((255, 0, 0))
					self.logger4.WriteText(_('connection does not exist'))
			elif 'pypilot' in assignment:
				if self.SK_settings.pypilot_enabled == True:
					self.logger4.BeginTextColour((0, 255, 0))
					self.logger4.WriteText(_('enabled'))
				else:
					self.logger4.BeginTextColour((255, 0, 0))
					self.logger4.WriteText(_('disabled'))
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('none'))
			self.logger4.EndTextColour()

			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.Newline()
			self.logger4.BeginBold()
			self.logger4.WriteText(_('Compass - Heel - Trim'))
			self.logger4.EndBold()
			self.logger4.Newline()
			self.logger4.WriteText(_('Pypilot status: '))
			self.logger4.EndTextColour()
			if pypilot == 'basic autopilot' or pypilot == 'imu':
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(_('enabled'))
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('disabled'))
			self.logger4.EndTextColour()
			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.WriteText(_('Heading: '))
			self.logger4.EndTextColour()
			if pypilot != 'disabled' and heading == '1':
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(_('enabled'))
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('disabled'))
			self.logger4.EndTextColour()
			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.WriteText(_('Pitch, Roll: '))
			self.logger4.EndTextColour()
			if pypilot != 'disabled' and attitude == '1':
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(_('enabled'))
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('disabled'))
			self.logger4.EndTextColour()

			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.BeginBold()
			self.logger4.WriteText(_('Pressure - Temperature'))
			self.logger4.EndBold()
			self.logger4.Newline()
			self.logger4.WriteText(_('I2C - Signal K key for pressure: '))
			self.logger4.EndTextColour()
			if pressure:
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(pressure)
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('none'))
			self.logger4.EndTextColour()
			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.WriteText(_('I2C - Signal K key for temperature: '))
			self.logger4.EndTextColour()
			if temperature:
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(temperature)
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('none'))
			self.logger4.EndTextColour()
			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.WriteText(_('Signal K to NMEA 0183 plugin: '))
			self.logger4.EndTextColour()
			if SKplugin:
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(_('enabled'))
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('disabled'))
			self.logger4.EndTextColour()
			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.WriteText(_('XDR (Barometer) conversion: '))
			self.logger4.EndTextColour()
			if SKplugin and XDRBaro:
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(_('enabled'))
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('disabled'))
			self.logger4.EndTextColour()

			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.BeginBold()
			self.logger4.WriteText(_('OpenCPN'))
			self.logger4.EndBold()
			self.logger4.Newline()
			self.logger4.WriteText(_('Signal K connection: '))
			self.logger4.EndTextColour()
			if opencpnConnection:
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(_('TCP localhost 10110 input'))
			else:
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('missing TCP localhost 10110 input'))
			self.logger4.EndTextColour()
			self.logger4.Newline()
			self.logger4.BeginTextColour((55, 55, 55))
			self.logger4.WriteText(_('Status: '))
			self.logger4.EndTextColour()
			if not opencpnConnection or opencpnConnection == 'disabled':
				self.logger4.BeginTextColour((255, 0, 0))
				self.logger4.WriteText(_('disabled'))
			if opencpnConnection == 'enabled':
				self.logger4.BeginTextColour((0, 255, 0))
				self.logger4.WriteText(_('enabled'))


		def onDownload(self,e):
			self.logger3.Clear()
			self.logger3.BeginTextColour((55, 55, 55))
			kernel = subprocess.check_output(['uname','-r'])
			kernel = kernel.split('-')
			kernel = kernel[0]
			file = 'moitessier_'+kernel+'_armhf.deb'
			self.logger3.WriteText(_('Searching file '))
			self.logger3.BeginBold()
			self.logger3.WriteText(file)
			self.logger3.EndBold()
			self.logger3.WriteText(' ...')
			self.logger3.Newline()
			if os.path.isfile(self.op_folder+'/tools/moitessier_hat/packages/'+file):
				self.logger3.WriteText(_('This file already exists!'))
			else:
				try:
					out = subprocess.check_output(['wget','https://get.rooco.tech/moitessier/release/'+kernel+'/latest/'+file, '-P', self.op_folder+'/tools/moitessier_hat/packages'])
					self.logger3.WriteText(_('File downloaded!'))
				except:
					self.logger3.WriteText(_('File not found!'))
			self.logger3.EndTextColour()
			self.readAvailable()

		def readAvailable(self):
			self.packages_select.Clear()
			self.packages_list = []
			kernel = subprocess.check_output(['uname','-r'])
			kernel = kernel.split('.')
			kernelA = int(kernel[0])
			kernelB = int(kernel[1])
			kernelC = kernel[2].split('-')
			kernelC = int(kernelC[0])
			tmp = os.listdir(self.op_folder+'/tools/moitessier_hat/packages')
			for i in tmp:
				package = i.split('_')
				package = package[1]
				package = package.split('.')
				packageA = int(package[0])
				packageB = int(package[1])
				packageC = int(package[2])
				if packageA >= kernelA:
					if packageB >= kernelB:
						if packageC >= kernelC: self.packages_list.append(i)
			self.packages_select.AppendItems(self.packages_list)
			if len(self.packages_list)>0: self.packages_select.SetSelection(0)

		def onCheck(self,e=0):
			self.logger.Clear()
			self.logger.BeginBold()
			try:
				out = subprocess.check_output(['more','product'],cwd='/proc/device-tree/hat')
			except:
				self.logger.BeginTextColour((255, 0, 0))
				self.logger.WriteText(_('Moitessier HAT is not attached!\n'))
				self.logger.EndTextColour()
				self.disable_info_settings_buttons()
			else:
				if not 'Moitessier' in out: 
					self.logger.BeginTextColour((255, 0, 0))
					self.logger.WriteText(_('Moitessier HAT is not attached!\n'))
					self.logger.EndTextColour()
					self.disable_info_settings_buttons()
				else: 
					self.logger.BeginTextColour((0, 255, 0))
					self.logger.WriteText(_('Moitessier HAT is attached.\n'))
					self.logger.EndTextColour()

			if not os.path.isfile(self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl'):
				self.logger.BeginTextColour((255, 0, 0))
				self.logger.WriteText(_('Moitessier HAT package is not installed!\n'))
				self.logger.EndTextColour()
				self.disable_info_settings_buttons()
			else:
				self.logger.BeginTextColour((0, 255, 0))
				self.logger.WriteText(_('Moitessier HAT package is installed.\n'))
				self.logger.EndTextColour()
				self.logger.EndBold()
				self.logger.BeginTextColour((55, 55, 55))
				package = subprocess.check_output(['dpkg','-s','moitessier'])
				self.logger.WriteText(package)
				self.logger.EndTextColour()

				kernel = subprocess.check_output(['uname','-r'])
				kernel = kernel.split('-')
				kernel = kernel[0]
				package = package.split('\n')
				for i in package:
					if 'Version:' in i:
						version = self.extract_value(i)
						version = version.split('-')
						version = version[2]
				if kernel != version:
					self.logger.BeginBold()
					self.logger.BeginTextColour((255, 0, 0))
					self.logger.WriteText(_('The installed package does not match the kernel version. Go to "install" tab to update the package.'))
					self.logger.EndTextColour()
					self.logger.EndBold()

		def extract_value(self, data):
			option, value = data.split(':')
			value = value.strip()
			return value

		def read(self):
			self.onCheck()
			try:
				settings = subprocess.check_output([self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl','/dev/moitessier.ctrl','1'])
				settings = settings.replace('\t','')
				settings = settings.split('\n')
				for i in settings:
					if 'enabled:' in i:
						if self.extract_value(i) == '1': self.simulator.SetValue(True)
						else: self.simulator.SetValue(False)
					if 'interval:' in i:
						self.interval.SetValue(int(self.extract_value(i)))
					if 'mmsi:' in i:
						data = self.extract_value(i)
						data = data.split(' ')
						self.mmsi1.SetValue(int(data[0])) 
						self.mmsi2.SetValue(int(data[1]))
					if 'channel frequency 1 [Hz]:' in i:
						self.rec1_freq1.SetValue(int(self.extract_value(i)))
					if 'channel frequency 2 [Hz]:' in i:
						self.rec1_freq2.SetValue(int(self.extract_value(i)))
					if 'meta data mask:' in i:
						if self.extract_value(i) == '0x00': self.rec1_metamask.SetSelection(0)
						else: self.rec1_metamask.SetSelection(1)
					if 'afc range [Hz]:' in i and not 'default' in i:
						self.rec1_afcRange.SetValue(int(self.extract_value(i)))
			except:
				self.logger2.BeginTextColour((255, 0, 0))
				self.logger2.WriteText(_('Failure reading HAT settings!'))
				self.logger2.EndTextColour()
				self.disable_info_settings_buttons()
			else:
				self.logger2.BeginTextColour((55, 55, 55))
				self.logger2.WriteText(_('All changes will be temporal.\nDefault settings will be loaded after rebooting.\n'))
				self.logger2.EndTextColour()

			self.current_kernel = subprocess.check_output(['uname','-r','-v'])
			self.kernel_label.SetLabel(self.current_kernel)
			self.logger3.BeginTextColour((55, 55, 55))
			self.logger3.WriteText(_('Select the package that fits to the current kernel version.'))
			self.logger3.Newline()
			self.logger3.WriteText(_('If there is no matching package, connect to internet and try to download it.'))
			self.logger3.Newline()
			self.logger3.WriteText(_('Before installing, be sure the HAT is not being used by any service (Signal K, Kplex, GPSD, OpenCPN ...).'))
			self.logger3.Newline()
			self.logger3.WriteText(_('If installation fails, you may have to try to reboot and install the package again.'))
			self.logger3.EndTextColour()
			self.onCheckConfB()

		def on_install(self,e):
			if self.packages_select.GetStringSelection() == '':
				self.logger3.SetValue(_('Select a package to install.'))
			else:
				subprocess.Popen(['lxterminal', '-e', 'bash', self.op_folder+'/tools/moitessier_hat/install.sh', self.op_folder+'/tools/moitessier_hat/packages/'+self.packages_select.GetStringSelection()])
				self.logger3.SetValue(_('Updating Moitessier Hat modules and firmware...'))

		def disable_info_settings_buttons(self):
			self.button_get_info.Disable()
			self.button_statistics.Disable()
			self.button_reset_statistics.Disable()
			self.button_MPU9250.Disable()
			self.button_MS560702BA03.Disable()
			self.button_Si7020A20.Disable()
			self.button_enable_gnss.Disable()
			self.button_disable_gnss.Disable()
			self.button_reset.Disable()
			self.button_defaults.Disable()
			self.simulator.Disable()
			self.interval.Disable()
			self.mmsi1.Disable()
			self.mmsi2.Disable()
			self.rec1_freq1.Disable()
			self.rec1_freq2.Disable()
			self.rec1_metamask.Disable()
			self.rec1_afcRange.Disable()
			self.button_apply.Disable()

		def on_defaults(self,e):
			try:
				tree = ET.parse(self.home+'/moitessier/app/moitessier_ctrl/default_config.xml')
				root = tree.getroot()
				for item in root.iter("simulator"):
					for subitem in item.iter("enabled"):
						if subitem.text == '1': self.simulator.SetValue(True)
						else: self.simulator.SetValue(False)
					for subitem in item.iter("interval"):
						self.interval.SetValue(int(subitem.text))
					for subitem in item.iter("mmsi"):
						self.mmsi1.SetValue(int(subitem[0].text)) 
						self.mmsi2.SetValue(int(subitem[1].text))
				for item in root.iterfind('receiver[@name="receiver1"]'):
					for subitem in item.iter("channelFreq"):
						self.rec1_freq1.SetValue(int(subitem[0].text)) 
						self.rec1_freq2.SetValue(int(subitem[1].text))
					for subitem in item.iter("metamask"):
						if subitem.text == '0': self.rec1_metamask.SetSelection(0)
						else: self.rec1_metamask.SetSelection(1)
					for subitem in item.iter("afcRange"):
						self.rec1_afcRange.SetValue(int(subitem.text)) 
			except:
				self.logger2.Clear()
				self.logger2.BeginTextColour((255, 0, 0))
				self.logger2.WriteText(_('Failure reading default_config.xml file!'))
				self.logger2.EndTextColour()
			else:
				self.logger2.Clear()
				self.logger2.BeginTextColour((55, 55, 55))
				self.logger2.WriteText(_('Defaults loaded. Apply changes.'))
				self.logger2.EndTextColour()

		def on_apply(self,e=0):
			try: 
				tree = ET.parse(self.home+'/moitessier/app/moitessier_ctrl/config.xml')
				root = tree.getroot()
				for item in root.iter("simulator"):
					for subitem in item.iter("enabled"):
						if self.simulator.GetValue(): subitem.text = '1'
						else: subitem.text = '0'
					for subitem in item.iter("interval"):
						subitem.text = str(self.interval.GetValue())
					for subitem in item.iter("mmsi"):
						subitem[0].text = str(self.mmsi1.GetValue())
						subitem[1].text = str(self.mmsi2.GetValue())
				for item in root.iterfind('receiver[@name="receiver1"]'):
					for subitem in item.iter("channelFreq"):
						subitem[0].text = str(self.rec1_freq1.GetValue())
						subitem[1].text = str(self.rec1_freq2.GetValue())
					for subitem in item.iter("metamask"):
						if self.rec1_metamask.GetSelection() == 0: subitem.text = '0'
						else: subitem.text = '16'
					for subitem in item.iter("afcRange"):
						subitem.text = str(self.rec1_afcRange.GetValue())
				for item in root.iterfind('receiver[@name="receiver2"]'):
					for subitem in item.iter("channelFreq"):
						subitem[0].text = str(self.rec1_freq1.GetValue())
						subitem[1].text = str(self.rec1_freq2.GetValue())
					for subitem in item.iter("metamask"):
						if self.rec1_metamask.GetSelection() == 0: subitem.text = '0'
						else: subitem.text = '16'
					for subitem in item.iter("afcRange"):
						subitem.text = str(self.rec1_afcRange.GetValue())
				tree.write(self.home+'/moitessier/app/moitessier_ctrl/config.xml',encoding='utf-8', xml_declaration=True)
				subprocess.call([self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl','/dev/moitessier.ctrl','5',self.home+'/moitessier/app/moitessier_ctrl/config.xml'])
				self.logger2.Clear()
				self.logger2.BeginTextColour((55, 55, 55))
				self.logger2.WriteText(_('Changes applied.'))
				self.logger2.EndTextColour()
			except: 
				self.logger2.Clear()
				self.logger2.BeginTextColour((255, 0, 0))
				self.logger2.WriteText(_('Apply changes failed!'))
				self.logger2.EndTextColour()

		def on_get_info(self, e):
			self.logger.Clear()
			self.logger.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl','/dev/moitessier.ctrl','1'])
			self.logger.WriteText(output)
			self.logger.EndTextColour()

		def on_statistics(self, e):
			self.logger.Clear()
			self.logger.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl','/dev/moitessier.ctrl','0'])
			self.logger.WriteText(output)
			self.logger.EndTextColour()

		def on_reset_statistics(self, e):
			self.logger.Clear()
			self.logger.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl','/dev/moitessier.ctrl','3'])
			self.logger.WriteText(output)
			self.logger.EndTextColour()

		def on_enable_gnss(self, e):
			self.logger2.Clear()
			self.logger2.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl','/dev/moitessier.ctrl','4','1'])
			self.logger2.WriteText(output)
			self.logger2.EndTextColour()

		def on_disable_gnss(self, e):
			self.logger2.Clear()
			self.logger2.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl','/dev/moitessier.ctrl','4','0'])
			self.logger2.WriteText(output)
			self.logger2.EndTextColour()

		def on_MPU9250(self, e):
			self.logger.Clear()
			self.logger.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/sensors/MPU-9250', '/dev/i2c-1'])
			self.logger.WriteText(_('MPU-9250 temperature: ')+output)
			self.logger.WriteText(_('To get accurate readings, make sure the sensor is not being read by another application.'))
			self.logger.EndTextColour()

		def on_MS560702BA03(self, e):
			self.logger.Clear()
			self.logger.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/sensors/MS5607-02BA03', '/dev/i2c-1'])
			self.logger.WriteText(_('MS5607-02BA03 pressure: ')+output)
			self.logger.WriteText(_('To get accurate readings, make sure the sensor is not being read by another application.'))
			self.logger.EndTextColour()

		def on_Si7020A20(self, e):
			self.logger.Clear()
			self.logger.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/sensors/Si7020-A20', '/dev/i2c-1'])
			if 'Firmware' in output: output = _('This sensor is not mounted on this HAT\n')
			self.logger.WriteText(_('Si7020-A20 humidity: ')+output)
			self.logger.WriteText(_('To get accurate readings, make sure the sensor is not being read by another application.'))
			self.logger.EndTextColour()
			
		def on_reset(self, e):
			self.logger2.Clear()
			self.logger2.BeginTextColour((55, 55, 55))
			output = subprocess.check_output([self.home+'/moitessier/app/moitessier_ctrl/moitessier_ctrl','/dev/moitessier.ctrl','2'])
			self.logger2.WriteText(output)
			self.logger2.EndTextColour()

		def on_help(self, e):
			url = self.op_folder+"/docs/html/tools/moitessier_hat.html"
			webbrowser.open(url, new=2)

		def onShop(self, e):
			url = "https://shop.sailoog.com/openplotter/4-moitessier-hat.html"
			webbrowser.open(url, new=2)

		def onDrivers(self, e):
			url = "https://www.rooco.eu/2018/06/13/firmware-and-drivers-for-raspberry-pi-moitessier-hat/"
			webbrowser.open(url, new=2)

		def on_ok(self, e):
			self.Close()
Example #24
0
class MyFrame(wx.Frame):
    def __init__(self):
        self.conf = Conf()
        self.home = self.conf.home
        self.op_folder = self.conf.get('GENERAL', 'op_folder')
        self.currentpath = self.op_folder
        self.help_bmp = wx.Bitmap(
            self.op_folder + "/static/icons/help-browser.png",
            wx.BITMAP_TYPE_ANY)
        Language(self.conf)
        self.SK_settings = SK_settings(self.conf)

        self.available_operators = [
            'eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'btwn', 'cont', 'true',
            'false', 'null', 'nnull', 'empty', 'nempty'
        ]
        self.available_conditions = [
            '=', '!=', '<', '<=', '>', '>=',
            _('is between'),
            _('contains'),
            _('is true'), ('is false'),
            _('is null'),
            _('is not null'),
            _('is empty'),
            _('is not empty')
        ]

        self.available_source = [
            _('label'),
            _('type'),
            _('pgn'),
            _('src'),
            _('sentence'),
            _('talker')
        ]
        self.available_source_nr = [
            'label', 'type', 'pgn', 'src', 'sentence', 'talker'
        ]

        wx.Frame.__init__(self,
                          None,
                          title=_('SignalK input filter (uses node-red)'),
                          size=(710, 460))

        self.SetFont(
            wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL))

        self.icon = wx.Icon(self.op_folder + '/static/icons/openplotter.ico',
                            wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)

        self.list_triggers = wx.ListCtrl(self,
                                         -1,
                                         style=wx.LC_REPORT | wx.SUNKEN_BORDER)
        self.list_triggers.InsertColumn(0, _('Signal K key'), width=240)
        self.list_triggers.InsertColumn(1, _('Source Type'), width=120)
        self.list_triggers.InsertColumn(2, _('Condition'), width=70)
        self.list_triggers.InsertColumn(3, _('Value'), width=90)
        self.list_triggers.InsertColumn(4, _('Value2'), width=60)

        self.list_triggers.Bind(wx.EVT_LIST_ITEM_SELECTED,
                                self.on_select_triggers)
        self.list_triggers.Bind(wx.EVT_LIST_ITEM_DESELECTED,
                                self.on_deselected_triggers)
        self.list_triggers.Bind(wx.EVT_LIST_ITEM_ACTIVATED,
                                self.on_edit_triggers)

        add_trigger = wx.Button(self, label=_('add'))
        add_trigger.Bind(wx.EVT_BUTTON, self.on_add_trigger)

        delete_trigger = wx.Button(self, label=_('delete'))
        delete_trigger.Bind(wx.EVT_BUTTON, self.on_delete_trigger)

        diagnostic = wx.Button(self, label=_('SK Diagnostic'))
        diagnostic.Bind(wx.EVT_BUTTON, self.on_diagnostic_SK)

        reset_skf = wx.Button(self, label=_('Restart'))
        reset_skf.Bind(wx.EVT_BUTTON, self.reset_sensors)

        help_button = wx.BitmapButton(self,
                                      bitmap=self.help_bmp,
                                      size=(self.help_bmp.GetWidth() + 40,
                                            self.help_bmp.GetHeight() + 10))
        help_button.Bind(wx.EVT_BUTTON, self.on_help_filter)

        apply_changes = wx.Button(self, label=_('Apply changes'))
        apply_changes.Bind(wx.EVT_BUTTON, self.on_apply_changes_triggers)
        cancel_changes = wx.Button(self, label=_('Cancel changes'))
        cancel_changes.Bind(wx.EVT_BUTTON, self.on_cancel_changes_triggers)

        hlistbox_but = wx.BoxSizer(wx.VERTICAL)
        hlistbox_but.Add(add_trigger, 0, wx.ALL, 5)
        hlistbox_but.Add(delete_trigger, 0, wx.ALL, 5)

        hlistbox = wx.BoxSizer(wx.HORIZONTAL)
        hlistbox.Add(self.list_triggers, 1, wx.ALL | wx.EXPAND, 5)
        hlistbox.Add(hlistbox_but, 0, wx.RIGHT | wx.LEFT, 0)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(help_button, 0, wx.ALL, 0)
        hbox.Add(diagnostic, 0, wx.RIGHT | wx.LEFT, 5)
        hbox.Add(reset_skf, 0, wx.RIGHT | wx.LEFT, 5)
        hbox.AddStretchSpacer(1)
        hbox.Add(apply_changes, 0, wx.RIGHT | wx.LEFT, 5)
        hbox.Add(cancel_changes, 0, wx.RIGHT | wx.LEFT, 5)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(hlistbox, 1, wx.ALL | wx.EXPAND, 0)
        vbox.Add(hbox, 0, wx.ALL | wx.EXPAND, 5)

        self.SetSizer(vbox)

        self.read_triggers()

    def read_triggers(self):
        self.actions_flow_id = 'openplot.filter'
        self.selected_trigger = -1
        self.selected_condition = -1
        self.selected_action = -1
        self.nodes = Nodes(self, self.actions_flow_id)
        result = self.nodes.get_flow()
        self.actions_flow_tree = result[0]
        self.triggers_flow_nodes = result[1]
        self.conditions_flow_nodes = result[2]
        self.actions_flow_nodes = result[3]
        self.no_actions_nodes = result[4]
        self.remove_credentials = []
        self.on_print_triggers()

    def on_print_triggers(self):
        self.list_triggers.DeleteAllItems()
        self.selected_trigger = -1
        for trigger in self.actions_flow_tree:
            enabled = False
            name = "t|" + trigger["trigger_node_out_id"] + "|" + trigger["type"]
            field2 = ''
            field3 = ''
            field4 = ''
            path = ''
            path_property = ''
            for node in self.triggers_flow_nodes:
                if 'name' in node and name == node['name']:
                    if trigger["type"] == '0':
                        if node['type'] == 'signalk-subscribe' or 'signalk-input-handler':
                            path = node['path']
                            field2 = node['context']
                            nsrc = node['source']
                if node['id'] == trigger["trigger_node_out_id"]:
                    if 'func' in node:
                        if node['func'] == 'return msg;': enabled = True
                    else:
                        enabled = True
                self.nodeid = node['id']
            self.list_triggers.Append([path.decode('utf8'), '', '', '', ''])
            self.last = self.list_triggers.GetItemCount() - 1
            self.selected_trigger = self.list_triggers.GetItemCount() - 1
            self.on_print_conditions()

    def on_print_conditions(self):
        if self.selected_trigger == -1: return
        conditions = self.actions_flow_tree[
            self.selected_trigger]["conditions"]
        triggertype = self.actions_flow_tree[self.selected_trigger]["type"]
        for condition in conditions:
            name = "c|" + condition["condition_node_out_id"] + "|" + condition[
                "operator"]
            field2 = ''
            field3 = ''
            value2 = ''
            for node in self.conditions_flow_nodes:
                if 'name' in node and name == node['name']:
                    if node['type'] == 'switch':
                        if 'property' in node:
                            property = node['property']
                        else:
                            property = ''
                        if 'v' in node['rules'][0]:
                            if triggertype == '5':
                                try:
                                    seconds = float(
                                        node['rules'][0]['v']) / 1000
                                    local_time = datetime.fromtimestamp(
                                        seconds)
                                    field2 = local_time.strftime(
                                        "%Y-%m-%d %H:%M:%S")
                                except:
                                    pass
                            else:
                                value = node['rules'][0]['v']
                        if 't' in node['rules'][0] and node['rules'][0][
                                't'] == 'btwn':
                            if 'v2' in node['rules'][0]:
                                if triggertype == '5':
                                    try:
                                        seconds = float(
                                            node['rules'][0]['v2']) / 1000
                                        local_time = datetime.fromtimestamp(
                                            seconds)
                                        field3 = local_time.strftime(
                                            "%Y-%m-%d %H:%M:%S")
                                    except:
                                        pass
                                else:
                                    value2 = node['rules'][0]['v2']
            self.list_triggers.SetStringItem(self.last, 1,
                                             property.decode('utf8'))
            self.list_triggers.SetStringItem(
                self.last, 2, self.available_conditions[int(
                    condition["operator"])].decode('utf8'))
            self.list_triggers.SetStringItem(self.last, 3,
                                             value.decode('utf8'))
            self.list_triggers.SetStringItem(self.last, 4,
                                             value2.decode('utf8'))
            self.last = self.list_triggers.GetItemCount() - 1

    def on_select_triggers(self, e):
        self.selected_trigger = self.list_triggers.GetFirstSelected()

    def on_deselected_triggers(self, e):
        self.on_print_triggers()

    def on_edit_triggers(self, e):
        if self.selected_trigger == -1: return
        node = self.actions_flow_tree[
            self.selected_trigger]['trigger_node_out_id']
        self.nodetrigger = node
        triggertype = self.actions_flow_tree[self.selected_trigger]['type']
        name = 't|' + node + '|' + triggertype
        edit = []
        for i in self.triggers_flow_nodes:
            if 'name' in i:
                if i['name'] == name: edit.append(i)
            else:
                subid0 = i['id'].split('.')
                subid = subid0[0]
                for ii in self.triggers_flow_nodes:
                    subid0 = ii['id'].split('.')
                    subid2 = subid0[0]
                    if subid2 == subid and name == ii['name']: edit.append(i)

        #find connected condition
        nodec = self.actions_flow_tree[self.selected_trigger]['conditions'][
            self.selected_condition]['condition_node_out_id']
        typec = self.actions_flow_tree[self.selected_trigger]['conditions'][
            self.selected_condition]['operator']
        name = 'c|' + nodec + '|' + typec
        edit2 = ''
        for i in self.conditions_flow_nodes:
            if 'name' in i:
                if i['name'] == name:
                    edit2 = i['rules'][0]
                    src_property = (i['property'].split('.'))[1]
                    self.edit_cond = i

        self.edit_add_trigger(edit, edit2, src_property)

    def on_add_trigger(self, e):
        self.edit_add_trigger(0, 0, 0)

    def edit_add_trigger(self, edit, edit2, src_property):
        trigger = 0
        dlg = TriggerFilterSK(self, edit, edit2, trigger, src_property)
        res = dlg.ShowModal()
        if res == wx.OK:
            if not edit:
                for i in dlg.TriggerNodes:
                    self.triggers_flow_nodes.append(i)
                    if 'name' in i: items = i['name'].split('|')
                    self.actions_flow_tree.append({
                        "trigger_node_out_id":
                        items[1],
                        "type":
                        items[2],
                        "conditions": []
                    })
                j = 0
                for i in self.actions_flow_tree:
                    if i["trigger_node_out_id"] == items[1]:
                        self.act_action_flow_tree = j
                    j += 1
                trigger_id = items[1]
                self.conditions_flow_nodes.append(dlg.ConditionNode)
                items = dlg.ConditionNode['name'].split('|')
                self.actions_flow_tree[
                    self.act_action_flow_tree]['conditions'].append({
                        "condition_node_out_id":
                        items[1],
                        "operator":
                        items[2],
                        "actions": []
                    })
                self.condition_id = items[1]
                for i in self.triggers_flow_nodes:
                    if i['id'] == trigger_id:
                        i['wires'][0].append(dlg.condition_connector_id)
                self.add_action()
            else:
                tmplist = []
                nodeout = self.actions_flow_tree[
                    self.selected_trigger]['trigger_node_out_id']
                for i in self.triggers_flow_nodes:
                    exist = False
                    for ii in edit:
                        if i['id'] == ii['id']:
                            exist = True
                            if ii['id'] == nodeout: wires = ii['wires']
                    if not exist: tmplist.append(i)
                self.triggers_flow_nodes = tmplist
                for i in dlg.TriggerNodes:
                    if 'name' in i: items = i['name'].split('|')
                    self.triggers_flow_nodes.append(i)
                for i in self.triggers_flow_nodes:
                    if i['id'] == items[1]: i['wires'] = wires
                self.actions_flow_tree[
                    self.selected_trigger]['trigger_node_out_id'] = items[1]
                self.actions_flow_tree[
                    self.selected_trigger]['type'] = items[2]
                selected_trigger = self.selected_trigger
                self.on_print_triggers()
                self.selected_trigger = selected_trigger
                self.list_triggers.Select(self.selected_trigger)
                #condition
                self.edit_cond['rules'] = dlg.ConditionNode['rules']
                self.edit_cond['property'] = dlg.ConditionNode['property']
                namesplit = self.edit_cond['name'].split('|')
                operator = self.available_operators.index(
                    self.edit_cond['rules'][0]['t'])
                self.edit_cond['name'] = namesplit[0] + '|' + namesplit[
                    1] + '|' + str(operator)

                for i in self.actions_flow_tree[
                        self.selected_trigger]['conditions']:
                    if 'condition_node_out_id' in i:
                        if i['condition_node_out_id'] == namesplit[1]:
                            i['operator'] = str(operator)

            self.on_print_triggers()
            last = self.list_triggers.GetItemCount() - 1

        dlg.Destroy()

    def add_action(self):
        self.sk_node_template = '''
		    {			
		        "id": "",
				"type": "signalk-input-handler-next",
		        "z": "",
		        "name": "",
		        "x": 380,
		        "y": 120,
		        "wires": []
		    }'''

        ActionNodes = []
        sk_node = ujson.loads(self.sk_node_template)
        sk_node['id'] = self.nodes.get_node_id()
        sk_node['z'] = self.actions_flow_id
        sk_node['name'] = 'a|' + sk_node['id'] + '|0'
        ActionNodes.append(sk_node)
        action_connector_id = sk_node['id']

        for i in ActionNodes:
            self.actions_flow_nodes.append(i)
            if 'dname' in i: items = i['dname'].split('|')
            elif 'name' in i: items = i['name'].split('|')
        self.actions_flow_tree[
            self.act_action_flow_tree]['conditions'][0]['actions'].append({
                "action_node_out_id":
                items[1],
                "type":
                items[2]
            })
        for i in self.conditions_flow_nodes:
            if i['id'] == self.condition_id:
                i['wires'][0].append(action_connector_id)

    def on_delete_trigger(self, e):
        if self.selected_trigger == -1:
            self.ShowStatusBarRED(_('Select an item to delete'))
            return
        node = self.actions_flow_tree[
            self.selected_trigger]['trigger_node_out_id']
        triggertype = self.actions_flow_tree[self.selected_trigger]['type']
        name = 't|' + node + '|' + triggertype
        conditions = self.actions_flow_tree[
            self.selected_trigger]['conditions']
        for condition in conditions:
            nodec = condition['condition_node_out_id']
            operatortype = condition['operator']
            namec = 'c|' + nodec + '|' + operatortype
            actions = condition['actions']
            for action in actions:
                nameaction = 'a|' + action[
                    'action_node_out_id'] + '|' + action['type']
                self.delete_action_nodes(nameaction, action['type'], nodec)
            self.delete_condition_nodes(namec, node)

        self.delete_trigger_nodes(name)
        del self.actions_flow_tree[self.selected_trigger]

        self.on_print_triggers()

    def delete_trigger_nodes(self, name):
        tmplist = []
        for i in self.triggers_flow_nodes:
            name2 = ''
            if 'name' in i: name2 = i['name']
            elif not 'name' in i:
                subid0 = i['id'].split('.')
                subid = subid0[0]
                for ii in self.triggers_flow_nodes:
                    subidii = ii['id'].split('.')
                    if 'name' in ii and subid == subidii[0]: name2 = ii['name']
            if name != name2: tmplist.append(i)

        self.triggers_flow_nodes = tmplist

    def delete_condition_nodes(self, name, triggernode):
        tmplist = []
        for i in self.conditions_flow_nodes:
            name2 = ''
            if 'name' in i: name2 = i['name']
            if name != name2: tmplist.append(i)
            else:
                for ii in self.triggers_flow_nodes:
                    if ii['id'] == triggernode:
                        if i['id'] in ii['wires'][0]:
                            ii['wires'][0].remove(i['id'])
        self.conditions_flow_nodes = tmplist

    def delete_action_nodes(self, name, actiontype, conditionnode):
        tmplist = []
        for i in self.actions_flow_nodes:
            name2 = ''
            if 'dname' in i: name2 = i['dname']
            elif 'name' in i: name2 = i['name']
            elif not 'name' in i:
                subid0 = i['id'].split('.')
                subid = subid0[0]
                for ii in self.actions_flow_nodes:
                    subidii = ii['id'].split('.')
                    if 'name' in ii and subid == subidii[0]: name2 = ii['name']
            if name != name2: tmplist.append(i)
            else:
                for ii in self.conditions_flow_nodes:
                    if ii['id'] == conditionnode:
                        if i['id'] in ii['wires'][0]:
                            ii['wires'][0].remove(i['id'])
                if actiontype == '4' and 'type' in i:
                    if i['type'] == 'e-mail':
                        self.remove_credentials.append(i['id'])
        self.actions_flow_nodes = tmplist

    def on_apply_changes_triggers(self, e):
        all_flows = []
        result = self.nodes.get_flow()
        no_actions_nodes = result[4]
        others_flow_nodes = result[5]

        for i in no_actions_nodes:
            all_flows.append(i)
        for i in others_flow_nodes:
            all_flows.append(i)
        for i in self.triggers_flow_nodes:
            all_flows.append(i)
        for i in self.conditions_flow_nodes:
            all_flows.append(i)
            if i["type"] == "switch":
                result = []
                if 'vt' in i['rules'][0] and i['rules'][0]['vt'] == 'flow':
                    result = self.nodes.get_subscription(i['rules'][0]['v'])
                    name = result[0]['name']
                    exists = False
                    for ii in all_flows:
                        if 'name' in ii and ii['name'] == name: exists = True
                    if not exists:
                        for iii in result:
                            all_flows.append(iii)
                if 'v2t' in i['rules'][0] and i['rules'][0]['v2t'] == 'flow':
                    result = self.nodes.get_subscription(i['rules'][0]['v2'])
                    name = result[0]['name']
                    exists = False
                    for ii in all_flows:
                        if 'name' in ii and ii['name'] == name: exists = True
                    if not exists:
                        for iii in result:
                            all_flows.append(iii)

        for i in self.actions_flow_nodes:
            all_flows.append(i)
            if i["type"] == "change":
                result = []
                c = len(i['rules'])
                if c == 1 and 'tot' in i['rules'][0] and i['rules'][0][
                        'tot'] == 'flow':
                    result = self.nodes.get_subscription(i['rules'][0]['to'])
                if c > 1 and 'tot' in i['rules'][1] and i['rules'][1][
                        'tot'] == 'flow':
                    result = self.nodes.get_subscription(i['rules'][1]['to'])
                if result:
                    name = result[0]['name']
                    exists = False
                    for ii in all_flows:
                        if 'name' in ii and ii['name'] == name: exists = True
                    if not exists:
                        for iii in result:
                            all_flows.append(iii)
            if i["type"] == "template":
                result = []
                if 'template' in i:
                    matches = re.findall("{{(.*?)}}", i['template'])
                    for ii in matches:
                        value_list = ii.split('.')
                        value_list.pop(0)
                        skkey = '.'.join(value_list)
                        result = self.nodes.get_subscription(skkey)
                        name = result[0]['name']
                        exists = False
                        for iii in all_flows:
                            if 'name' in iii and iii['name'] == name:
                                exists = True
                        if not exists:
                            for iiii in result:
                                all_flows.append(iiii)

        shortcut = []
        idabs = []
        idabs_parent = []
        line = 0
        absline = 0
        treeline = 0

        #create list of shortcuts
        for i in all_flows:
            if 'type' in i and 'wires' in i and 'id' in i and i[
                    'z'] == self.actions_flow_id:
                if i['wires'] in [[], [[]], [[], []], [[], [], []]]:
                    #line,tree,parent,x,y,idnum,wiresnum,id,wires
                    # 0     1    2    3 4   5       6     7   8
                    shortcut.append(
                        [line, -1, -1, -1, -1, absline, -1, i['id'], ''])
                    line += 1
                else:
                    treeline = 0
                    for ii in i['wires'][0]:
                        shortcut.append([
                            line, treeline, -1, -1, -1, absline, -1, i['id'],
                            ii
                        ])
                        line += 1
                        treeline += 1
                idabs.append(i['id'])
                idabs_parent.append(absline)
                absline += 1
            #print absline,line,i

        #print 'idabs'
        #for i in idabs: print idabs.index(i),i

        #print 'idabs_parent'
        #for i in idabs_parent: print idabs_parent.index(i),i

        #find idnum for id
        for i in shortcut:
            if i[8] <> '':
                i[6] = idabs.index(i[8])
                idabs_parent[i[6]] = -1

        #print 'idabs_parent'
        #for i in idabs_parent: print idabs_parent.index(i),i

        parentlist = []
        parentnum = 0
        #create parentlist
        for i in idabs_parent:
            if i > -1:
                parentlist.append(i)
                for j in shortcut:
                    if j[5] == i:
                        j[2] = parentnum
                        j[3] = 0
                        j[4] = 0
                parentnum += 1

        #print 'shortcut'
        #for i in shortcut: print i

        #identify x position of following nodes
        for j in range(10):
            for i in shortcut:
                if i[3] == j:
                    for ii in shortcut:
                        if ii[5] == i[6]:
                            if ii[3] == -1:
                                ii[3] = j + 1
                                ii[2] = i[2]

        for j in range(len(parentlist)):
            y = 1
            #find all forks and set y
            for i in shortcut:
                if i[2] == j and i[1] >= 1:
                    i[4] = y
                    y += 1

        #print 'shortcut'
        #for i in shortcut: print i

        for j in range(10):
            for i in shortcut:
                #x -1
                if i[3] == j:
                    for ii in shortcut:
                        #x -1
                        if ii[5] == i[6]:
                            if ii[4] == -1:
                                ii[4] = i[4]

        fork = []
        for j in range(len(parentlist)):
            for i in shortcut:
                #x -1
                if i[2] == j and i[1] >= 1:
                    # line,linenum,mainfork(y),subfork(y),x
                    fork.append(
                        [i[2], i[0], shortcut[i[0] - 1][4], i[4], i[3]])
                    i[4] = shortcut[i[0] - 1][4]

        fork = sorted(fork, key=lambda x: (x[0], x[2], -x[4]))

        #print 'fork'
        #for i in fork: print i

        #set lines with fork in right direction
        #build a converting table
        convert = []
        for j in range(len(parentlist)):
            convert.append([0])
            for i in fork:
                if i[0] == j:
                    convert[j].append(0)

        #set values to converting table
        for j in range(len(parentlist)):
            y = 1
            for i in fork:
                if i[0] == j:
                    convert[j][i[3]] = y
                    y += 1

        #print 'convert'
        #for i in convert: print i

        #convert every line
        for i in shortcut:
            i[4] = convert[i[2]][i[4]]

        #print 'shortcut'
        #for i in shortcut: print i

        xstart = 140
        ystart = 60
        xstep = 220
        ystep = 55
        ymax = 0
        for j in range(len(parentlist)):
            if ymax >= ystart:
                ystart = ymax + ystep

            for i in all_flows:
                if 'type' in i and 'wires' in i and 'id' in i and i[
                        'z'] == self.actions_flow_id:
                    for ii in reversed(shortcut):
                        if i['id'] == ii[7] and ii[2] == j:
                            i['x'] = xstart + xstep * ii[3]
                            i['y'] = ystart + ystep * ii[4]
                            if i['y'] > ymax:
                                ymax = i['y']

        self.nodes.write_flow(all_flows)
        self.restart_SK()
        seconds = 15
        for i in range(seconds, 0, -1):
            self.ShowStatusBarGREEN(
                _('Signal K server restarted') + ' | ' +
                _('Starting Node-Red... ') + str(i))
            time.sleep(1)
        self.ShowStatusBarGREEN(
            _('Signal K server restarted') + ' | ' + _('Node-Red restarted'))

    def on_cancel_changes_triggers(self, e):
        self.read_triggers()

    def on_help_filter(self, e):
        url = self.currentpath + "/docs/html/tools/filter_signalk_inputs.html"
        webbrowser.open(url, new=2)

    def start_SK(self):
        subprocess.call(['sudo', 'systemctl', 'start', 'signalk.socket'])
        subprocess.call(['sudo', 'systemctl', 'start', 'signalk.service'])

    def stop_SK(self):
        subprocess.call(['sudo', 'systemctl', 'stop', 'signalk.service'])
        subprocess.call(['sudo', 'systemctl', 'stop', 'signalk.socket'])

    def ShowStatusBarRED(self, w_msg):
        self.ShowStatusBar(w_msg, wx.RED)

    def ShowStatusBarGREEN(self, w_msg):
        self.ShowStatusBar(w_msg, wx.GREEN)

    def ShowStatusBar(self, w_msg, colour):
        #self.GetStatusBar().SetForegroundColour(colour)
        #self.SetStatusText.value = w_msg
        pass

    def restart_SK(self):
        seconds = 12
        # stopping sk server
        self.stop_SK()
        # restarting sk server
        self.start_SK()
        for i in range(seconds, 0, -1):
            self.ShowStatusBarRED(_('Restarting Signal K server... ') + str(i))
            time.sleep(1)
        self.ShowStatusBarGREEN(_('Signal K server restarted'))

    def on_diagnostic_SK(self, e):
        subprocess.call(['pkill', '-f', 'diagnostic-SK-input.py'])
        subprocess.Popen(
            ['python', self.op_folder + '/diagnostic-SK-input.py'])

    def reset_sensors(self, event):
        pass
Example #25
0
class MyForm(wx.Frame):
    def __init__(self):
        self.serial = 0

        self.conf = Conf()
        Language(self.conf)
        wx.Frame.__init__(self,
                          None,
                          wx.ID_ANY,
                          _('tty auto setup'),
                          size=(720, 350))

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)
        log = wx.TextCtrl(panel,
                          wx.ID_ANY,
                          style=wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL)

        self.autostart = wx.CheckBox(panel,
                                     label=_('setup autostart on every boot'))
        self.autostart.Bind(wx.EVT_CHECKBOX, self.on_autostart)

        setup = wx.Button(panel, wx.ID_ANY, 'setup')
        setup.Bind(wx.EVT_BUTTON, on_setup)
        close = wx.Button(panel, wx.ID_CLOSE)
        close.Bind(wx.EVT_BUTTON, self.on_close)

        # Add widgets to a sizer
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(self.autostart, 0, wx.ALL | wx.EXPAND, 5)
        hbox.Add((0, 0), 1, wx.ALL | wx.EXPAND, 5)
        hbox.Add(setup, 0, wx.ALL | wx.EXPAND, 5)
        hbox.Add(close, 0, wx.ALL | wx.EXPAND, 5)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(log, 1, wx.ALL | wx.EXPAND, 5)
        vbox.Add(hbox, 0, wx.ALL | wx.CENTER | wx.EXPAND, 5)
        panel.SetSizer(vbox)

        self.tool_list = []
        data = self.conf.get('TOOLS', 'py')
        try:
            temp_list = eval(data)
        except:
            temp_list = []
        for ii in temp_list:
            self.tool_list.append(ii)
        self.tool = []
        self.tool_exist = False
        for i in self.tool_list:
            if i[2] == 'autosetup_tty.py':
                self.autostart.SetValue(i[3] == '1')
                self.tool.append(i)
                self.tool_exist = True

        # redirect text here
        redir = RedirectText(log)
        sys.stdout = redir

        print _(
            'Auto setup detects hardware. Please make sure that all devices are turned on.'
        )
        print

    def on_autostart(self, event):
        if self.tool_exist:
            if self.autostart.GetValue():
                self.tool[0][3] = '1'
            else:
                self.tool[0][3] = '0'

            self.conf.set('TOOLS', 'py', str(self.tool_list))

    def on_close(self, event):
        self.Close()
Example #26
0
            if 0 == conf_analog.has_option(FIRMATA + str(i), 'adjust_points'):
                adjust_point_active[index] = 0
            else:
                line = conf_analog.get(FIRMATA + str(i), 'adjust_points')
                if line:
                    adjust_point[index] = eval(line)
                    adjust_point_active[index] = 1
                else:
                    adjust_point[index] = []
            index += 1


conf = Conf()
home = conf.home
currentpath = conf.get('GENERAL', 'op_folder')

if len(sys.argv) > 1:
    index = 1
    if sys.argv[1] == 'settings':
        print home + '/.openplotter/tools/openplotter_analog.conf'
        subprocess.Popen(
            ['leafpad', home + '/.openplotter/tools/openplotter_analog.conf'])
    exit
else:
    RawValue = []
    adjust_point = []
    adjust_point_active = []
    channel = []
    channel_index = []
    SK_name = []
Example #27
0
def on_setup(event):
    time.sleep(0.1)
    context = pyudev.Context()
    tty_list = []
    index = 0

    conf = Conf()
    home = conf.home

    subprocess.call(["pkill", '-f', "signalk-server-node"])
    subprocess.call(["pkill", '-9', "kplex"])
    subprocess.call(['pkill', '-f', '1w_d.py'])
    subprocess.call(['pkill', '-f', 'read_sensors_d.py'])
    subprocess.call(['pkill', '-f', 'mqtt_d.py'])
    subprocess.call(['pkill', '-f', 'SK-base_d.py'])
    subprocess.call(['pkill', '-f', 'N2K-server_d.py'])

    conf_list = []
    data = conf.get('UDEV', 'usbinst')
    try:
        temp_list = eval(data)
    except:
        temp_list = []
    for ii in temp_list:
        conf_list.append(ii)

    print
    print 'search for tty devices'
    for device in context.list_devices(subsystem='tty'):
        # print(device)
        imfd = ''
        ivfd = ''
        id_bus = ''
        id_vendor_id = 'internal'
        id_modell_id = ''
        id_serial_short = ''
        devname = ''
        devpath = ''

        if 'ID_MODEL_FROM_DATABASE' in device:
            imfd = device['ID_MODEL_FROM_DATABASE']
        if 'ID_VENDOR_FROM_DATABASE' in device:
            ivfd = device['ID_VENDOR_FROM_DATABASE']
        if 'ID_MODEL_ID' in device: id_modell_id = device['ID_MODEL_ID']
        if 'ID_VENDOR_ID' in device: id_vendor_id = device['ID_VENDOR_ID']
        if 'ID_SERIAL_SHORT' in device:
            id_serial_short = device['ID_SERIAL_SHORT']
        if 'ID_BUS' in device: id_bus = device['ID_BUS']
        if 'DEVNAME' in device: devname = device['DEVNAME']
        if 'DEVPATH' in device: devpath = device['DEVPATH']
        if 'platform' in devpath or id_bus == 'usb':
            devpath = devpath[:-(len(devpath) - devpath.find('/tty'))]
            devpath = devpath[devpath.rfind('/') + 1:]
            if devname != '/dev/ttyAMA0':
                print 'found:', devname, id_vendor_id, id_modell_id, id_serial_short, devpath, imfd, ivfd
                tty_list.append([
                    '',
                    str(id_vendor_id),
                    str(id_modell_id),
                    str(id_serial_short),
                    str(devpath), 'dev',
                    str(devname[5:11]),
                    str(devname),
                    str(imfd),
                    str(ivfd), 0
                ])
            # for item in device:
            # print(item,device[item])
            # print('	  '+str(item)+':'+str(device[item]))
            index += 1

    print
    print 'sort tty devices'

    list_new = []
    for i in sorted(tty_list, key=lambda item: (item[2])):
        list_new.append(i)
    tty_list = list_new

    list_new = []
    for i in sorted(tty_list, key=lambda item: (item[1])):
        list_new.append(i)
    tty_list = list_new

    list_new = []
    for i in sorted(tty_list, key=lambda item: (item[0])):
        list_new.append(i)
    tty_list = list_new

    print
    print 'check if we have to switch from dev to port'

    t0 = 'x'
    t1 = 'x'
    t2 = 'x'
    safe = 0
    index = 0
    for i in tty_list:
        print 'test ', i
        if t0 == i[0] and t1 == i[1] and t2 == i[2]:
            tty_list[safe][5] = 'port'
            i[5] = 'port'
        else:
            t0 = i[0]
            t1 = i[1]
            t2 = i[2]
            safe = index
        index += 1

    print
    print 'search for NMEA0183 in tty devices'
    print
    wx.Yield()
    # self.update()

    baudrate_list = ['4800', '38400', '115200', '9600', '19200', '57600']
    baudrate_listN2K = ['115200']
    auto = AutoDetect()

    for i in tty_list:
        for baud in baudrate_list:
            wx.Yield()
            if i[10] == 0:
                if auto.readNMEA0183(i[7], baud):
                    i[10] = str(baud)
                    baud = baudrate_list[-1]

    print
    print 'create an autoname for found NMEA0183 devices'

    for i in tty_list:
        if i[10] != 0:
            index = 0
            ttyname = 'ttyOP_' + auto.readNMEA0183name(i[7], i[10])
            for j in tty_list:
                if ttyname in j[6]:
                    index += 1
            if index != 0:
                i[0] = str(ttyname + str(index))
            else:
                i[0] = str(ttyname)
            print 'created the name:', i[0]

    print
    print 'search for NMEA2000 in tty devices'
    wx.Yield()

    for i in tty_list:
        if i[7] != '/dev/ttyAMA0' and i[0] == '':
            print i
            for baud in baudrate_listN2K:
                print 'n2k', i, baud
                wx.Yield()
                if i[10] == 0:
                    print 'start'
                    wx.Yield()
                    if auto.readNMEA2000(i[7], baud):
                        i[10] = str(baud)
                        i[0] = 'ttyOP_N2K'
                        baud = baudrate_listN2K[-1]
                        i = tty_list[-1]
                        print 'ja'
                        wx.Yield()
                        # break
    print
    print '########################## result ################################'
    wx.Yield()
    print
    print 'add new devices to openplotter.conf'

    data = ''
    for i in tty_list:
        if i[10] != 0:
            exists = False
            print i
            for ii in conf_list:
                if (i[1] == ii[1] and i[2] == ii[2]
                        and i[3] == ii[3]) and i[5] != 'port':
                    exists = True
            if not exists:
                for ii in conf_list:
                    if i[0] == ii[0]:
                        exists = True
                if not exists:
                    conf_list.append(
                        [i[0], i[1], i[2], i[3], i[4], i[5], i[6]])
                    data += str([i[0], i[1], i[2], i[3], i[4], i[5], i[6]
                                 ]) + ','
                    i[6] = 1
                else:
                    print 'The auto created name ' + i[0] + ' already exists'
                    i[10] = 0
    if len(data) > 0:
        print '[UDEV]'
        print 'usbinst = ['
        print data[:-1] + ']'
    else:
        print '- none -'

    conf.set('UDEV', 'usbinst', str(conf_list))

    for i in tty_list:
        if 'ttyOP_N2K' == i[0]:
            if len(conf.get('N2K', 'can_usb')) < 3:
                conf.set('N2K', 'can_usb', '/dev/ttyOP_N2K')
                conf.set('N2K', 'enable', '1')
                print '[N2K]'
                print 'enable = 1'
                print 'can_usb = /dev/ttyOP_N2K'

    print
    print 'add new devices to kplex (not activated and no filter)'

    f1 = open(home + '/.kplex.conf', 'r')
    data = f1.readlines()
    f1.close()

    dataa = ''
    for i in tty_list:
        if i[6] == 1 and i[0] != 'ttyOP_N2K':
            auto_name = 'auto_' + i[0][6:].lower()
            exists = False
            for index, item in enumerate(data):
                if auto_name in item: exists = True
            if not exists:
                dataa += '#[serial]\n'
                dataa += '#name=' + auto_name + '\n'
                dataa += '#direction=in\n'
                dataa += '#optional=yes\n'
                dataa += '#filename=/dev/' + i[0] + '\n'
                dataa += '#baud=' + str(i[10]) + '\n\n'

    if dataa == '':
        print '- none -'
    else:
        print dataa

    newdata = ''
    for index, item in enumerate(data):
        if '###end of OpenPlotter GUI settings' in item:
            newdata += dataa
        newdata += item

    f1 = open(home + '/.kplex.conf', 'w')
    f1.write(newdata)
    f1.close()
Example #28
0
class DDStorm:
    """ Provides the class for finding differential diagnosis. """

    conf = False

    def __init__(self, comp=False, conf=False):
        """
        Initiate the diagnosis finder.

        Parameters:
        comp - Recompiles the data files if set to True
        conf - Supply a Conf object
        """
        if conf:
            self.conf = conf
        else:
            self.conf = Conf()
        self.compiler = Compile(conf)
        if comp:
            self.compiler.compile()
        self.index = Index(conf)

    def dd(self, symptoms):
        """
        Find the differential diagnosis list.

        Parameter:
        symptom - list of strings containing symptoms

        Return value:
        List of strings containing the differential diagnosis
        """

        # Return empty list if symptom list is empty
        if not symptoms:
            return

        # Find DD of first symptom and discard it
        diff1 = self._getDiff(symptoms.pop(0))

        # Loop through the rest of the list
        for s in symptoms:

            # Find DD of the current item in the list
            diff2 = self._getDiff(s)

            # List for temporary holding the DDs
            temp = []

            # Make both lists the same length by appending empty strings to the end
            if len(diff1) > len(diff2):
                diff2 += [""] * (len(diff1) - len(diff2))
            elif len(diff2) > len(diff1):
                diff1 += [""] * (len(diff2) - len(diff1))

            # Loop over both lists
            for (s1, s2) in zip(diff1, diff2):

                # Add s1 to temp if s1 or any of its upstream ancestor is common to both list
                if (s1 not in temp) and (len(s1) > 0):
                    if s1 in diff2:
                        temp.append(s1)
                    else:
                        us = self.index.upstream(s1)
                        for i in us:
                            if i in diff2:
                                temp.append(i)

                # Add s2 to temp if s2 or any of its upstream ancestor is common to both list
                if (s2 not in temp) and (len(s2) > 0):
                    if s2 in diff1:
                        temp.append(s2)
                    else:
                        us = self.index.upstream(s2)
                        for i in us:
                            if i in diff1:
                                temp.append(i)

            # Copy temp to first list
            diff1 = list(temp)

        return diff1

    def _getDiff(self, symptom):
        """ Return differential diagnosis for a single symptom """
        diff = []
        symptom = symptom.lower().replace("_", " ").replace("-", " ")
        if os.path.isfile(self.conf.get("module_path") + symptom + ".module"):
            with open(self.conf.get("module_path") + symptom + ".module", "r") as mf:
                for line in mf:
                    diff.append(line.strip())
        return diff

    def symptoms(self):
        """
        Return a full list of available symptoms

        Return value:
        List of string containing symptoms
        """
        symp = []
        for n in os.listdir(self.conf.get("module_path")):
            symp.append(os.path.splitext(os.path.basename(n))[0].capitalize())
        return symp
Example #29
0
# encoding:utf-8
import pymongo
import time
import datetime
from conf import Conf

client = pymongo.MongoClient(Conf.get('DEFAULT','ip'), int(Conf.get('DEFAULT','port')),username='******',password='******')


# support_transication = client.server_info()['versionArray'][0] >= 4
support_transication = False


class Base():
    '''
    collection的模型
    '''
    db_name = ''
    collection_name = ''
    template = {}

    def __init__(self):
        '''
        初始化数据库
        '''
        self.db = client[self.db_name]
        # self.db.authenticate('root','Superman01')
        # self.db.authenticate('','')
        self.collection = self.db[self.collection_name]
        if not self.db_name or not self.collection_name or not self.template:
            raise Exception('缺少定义 self.db_name 或 self.collection_name 或 self.template')
class MainFrame(wx.Frame):
    def __init__(self):

        self.option = sys.argv[1]

        self.conf = Conf()
        self.home = self.conf.home
        self.currentpath = self.home + self.conf.get(
            'GENERAL', 'op_folder') + '/openplotter'

        Language(self.conf)

        wx.Frame.__init__(self,
                          None,
                          title=_('Fine calibration'),
                          size=(500, 300))

        self.SetFont(
            wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL))

        self.icon = wx.Icon(self.currentpath + '/openplotter.ico',
                            wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)

        self.CreateStatusBar()

        self.text = wx.StaticText(self, label=_('Error'), pos=(10, 10))

        self.gain = self.conf.get('AIS-SDR', 'gain')
        self.ppm = self.conf.get('AIS-SDR', 'ppm')
        self.channel = self.conf.get('AIS-SDR', 'gsm_channel')

        wx.StaticText(self,
                      label=_('gain: ').decode('utf8') + self.gain,
                      pos=(10, 70))
        wx.StaticText(self,
                      label=_('ppm: ').decode('utf8') + self.ppm,
                      pos=(100, 70))

        self.output = wx.TextCtrl(self,
                                  style=wx.TE_MULTILINE | wx.TE_READONLY
                                  | wx.TE_DONTWRAP,
                                  size=(480, 110),
                                  pos=(10, 90))

        self.button_close = wx.Button(self, label=_('Close'), pos=(300, 210))
        self.Bind(wx.EVT_BUTTON, self.close, self.button_close)

        self.button_calculate = wx.Button(self,
                                          label=_('Calculate'),
                                          pos=(400, 210))
        self.Bind(wx.EVT_BUTTON, self.calculate, self.button_calculate)

        if self.option == 'c':
            self.text.SetLabel(
                _('Press Calculate and wait for the system to calculate the ppm value with\nthe selected channel. Put the obtained value in "Correction (ppm)" field\nand enable SDR-AISreception. Estimated time: 1 min.'
                  ))
            wx.StaticText(self,
                          label=_('channel: ').decode('utf8') + self.channel,
                          pos=(200, 70))
        if self.option == 'b':
            self.text.SetLabel(
                _('Press Calculate and wait for the system to check the band. Write down\nthe strongest channel (power). If you do not find any channel try another\nband. Estimated time: 5 min.'
                  ))

        self.Centre()

    def calculate(self, e):
        self.SetStatusText(_('Working...'))
        self.output.SetValue('')
        if self.option == 'c':

            try:
                output = subprocess.check_output([
                    'kal', '-c', self.channel, '-g', self.gain, '-e', self.ppm
                ])
            except:
                output = _('error')
        if self.option == 'b':
            band = self.conf.get('AIS-SDR', 'band')
            try:
                output = subprocess.check_output(
                    ['kal', '-s', band, '-g', self.gain, '-e', self.ppm])
            except:
                output = _('error')
        self.output.SetValue(output)
        self.SetStatusText(_('Finished'))

    def close(self, e):
        self.Destroy()
Example #31
0
    #     self.queue.put(('debug',value))
    #
    # @property
    # def info(self):
    #     return
    #
    # @info.setter
    # def info(self,value):
    #     self.queue.put(('info',value))
    #
    # @property
    # def warning(self):
    #     return
    #
    # @warning.setter
    # def warning(self,value):
    #     self.queue.put(('warning',value))
    #
    # @property
    # def error(self):
    #     return
    #
    # @error.setter
    # def error(self,value):
    #     self.queue.put(('error',value))


logger = Log(
    'log/log', logging.DEBUG
    if Conf.get('DEFAULT', 'mode') == 'debug' else logging.ERROR).logger
Example #32
0
	def __init__(self):
		Ether2Any.__init__(self, tap=True)
		self.irclog = self.setupLogging("IrcVPN")
		self.irclog.setLevel(logging.WARN)
		
		# === Load config values ===
		network = Conf.get("network", {'mtu': 1500})
		self.ircmsglen = Conf.get("ircmsglen", 400)
		self.ircserver = Conf.get("ircserver")
		self.broadcastchan = Conf.get("broadcastchan")
		self.nickPrefix = Conf.get("nickPrefix", "VPN")
		self.postConnectCmd = Conf.get("postConnectCmd", None)
		self.voiceWord = Conf.get("voicebot", None)
		if self.voiceWord:
			self.voiceWord = self.voiceWord.get("voiceword", None)
		self.mode = Conf.get("mode", "HUB")
		self.ignoreNonMacUser = Conf.get("ignoreNonMacUser", True)
		self.acceptNonMatchingMac = Conf.get("acceptNonMatchingMac", True)
		self.strictSwichedNetwork = Conf.get("strictSwichedNetwork", False)
		
		if self.mode not in ("HUB", "SWITCH"):
			raise ValueError("mode needs to be either HUB or SWITCH")
		self.irclog.info("Starting the IRC Public Network")
		self.packets = {}
		self._setupIrc()
		self.nickre = re.compile("^%s[a-fA-F0-9]{12}$" % (self.nickPrefix,))
		self.dev.ifconfig(**network)
		self.dev.up()
Example #33
0
class Index:
    ''' Provides an index of the upstream ancestors of symptoms '''
    def __init__(self, conf=False):
        '''
        Initiate the index object. Accepts a Conf object as an
        optional parameter.
        '''
        if(conf):
            self.conf=conf
        else:
            self.conf=Conf()
        self.data={}
        self.compile()

    def compile(self):
        '''
        Compile the text index files to a application usable format.
        '''
        # Loop over all files under index_path
        for path, subdirs, files in os.walk(self.conf.get("index_path")):
            for name in files:
                # Only files with *.txt suffix
                if(fnmatch(name, "*.txt")):
                    with open(self.conf.get("index_path")+name, "r") as f:
                        # Two dimensional list buffer to hold the index
                        buff=[]
                        buff.append([])
                        buff.append([])
                        # Loop over all lines as separate entries
                        for line in f:
                            # Ignore commnents starting with #
                            line=line.rstrip().split("#")[0]
                            if(len(line)==0):
                                pass
                            else:
                                # Find number of leading whitespaces
                                ws=len(line)-len(line.lstrip())
                                # Format the entry
                                line=line.lstrip().capitalize()
                                
                                # No leading whitespace means a top level entry i.e. no upstream ancestor
                                if(ws==0):
                                    # Empty the buffer and add the entry
                                    del buff[0][:]
                                    buff[0].append(line.lstrip())
                                    # Reset the whitespace index
                                    del buff[1][:]
                                    buff[1].append(0)
                                # If leading whitespace > indexed whitespace, the entry is a subcategory of previous entry
                                elif(ws>buff[1][-1]):
                                    # Append entry to buffer as new item
                                    buff[0].append(line.lstrip())
                                    # Record leading whitespace to buffer
                                    buff[1].append(ws)
                                    # Copy buffer to data list
                                    self.data[buff[0][-1]]=list(reversed(buff[0]))
                                # If leading whitespace == indexed whitespace, the entry is at the same level with the previous entry
                                elif(ws==buff[1][-1]):
                                    # Append entry to last item of buffer
                                    buff[0][-1]=line.lstrip()
                                    buff[1][-1]=ws
                                    # Copy buffer to data list
                                    self.data[buff[0][-1]]=list(reversed(buff[0]))
                                # If leading whitespace < indexed whitespace, the entry is at an upper category than the previous entry
                                elif(ws<buff[1][-1]):
                                    # Loop over the buffer in reverse
                                    for i in reversed(buff[1]):
                                        # Discard all lower category items
                                        if(i>=ws):
                                            buff[0].pop()
                                            buff[1].pop()
                                        #Append the entry to buffer
                                        else:
                                            buff[0].append(line.lstrip())
                                            buff[1].append(ws)
                                            break
                                    # Copy buffer to data list
                                    self.data[buff[0][-1]]=list(reversed(buff[0]))

    def upstream(self, name):
        '''
        Return the upstream list of a symptom

        Parameter:
        name - the name of the symptom as string

        Return value:
        List of strings containing the upstream items
        '''
        if(len(name)>0):
            if name in self.data:
                return self.data[name]
            else:
                return []

    def names(self):
        ''' Return all indexed symptoms name '''
        return list(self.data.keys())
Example #34
0
class ConfTestCase(unittest.TestCase):

    _default_directory = Path.home().joinpath('.svsoft')
    _default_file_name = 'budgeton.cfg'

    @classmethod
    def setUpClass(self):
        self._cnf = Conf()

    @classmethod
    def tearDownClass(self):
        pass

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def delete_all(self):
        try:
            # remove all files in directory .svsoft
            for current_file in os.listdir(self._default_directory):
                os.remove(self._default_directory.joinpath(current_file))
        except FileNotFoundError:
            pass

        try:
            # remove file
            os.rmdir(self._default_directory)
        except FileNotFoundError:
            pass

        pass

    def test_creation_file(self):
        # delete directory if exist
        self.delete_all()

        # test if deleted correctly
        self.assertEqual(self._default_directory.exists(), False)

        self._cnf = Conf()

        # test if created correctly
        self.assertEqual(self._default_directory.exists(), True)  # directory
        self.assertEqual(
            self._default_directory.joinpath(self._default_file_name).exists(),
            True)  #file

    def test_init_values(self):
        self.assertEqual(self._cnf.get('last_opened'), False)

    def test_if_property_not_exist_is_none(self):
        self.assertEqual(self._cnf.get("another_random_property"), None)

    def test_save_method(self):
        self._cnf.set('toto', True)
        self.assertEqual(self._cnf.get('toto'), True)

        f = open(self._default_directory.joinpath(self._default_file_name),
                 'r',
                 encoding='utf-8')

        content = f.read()
        json_obj = json.loads(content)
        self.assertEqual(json_obj['toto'], True)

        f.close()
Example #35
0
class Compile:
    '''
    This class creates a compiler for the DDStorm
    that compiles the text files containing list of
    differential diagnosis to simplified modular
    data files usable by the program.
    '''
    def __init__(self, conf=False):
        '''
        The constructor optionally accepts a configuration.
        If none is provided it creates a default configuration.

        Parameters:
        conf - A dictionary containing configuration options
        '''
        if (conf):
            self._conf = conf
        else:
            self._conf = Conf()
        self.clean = True

    def compile(self):
        ''' Compile the text files to DDStorm modules. '''
        self.source = set()
        self.custom = set()
        self.alias = Alias(self._conf)

        # Loop over library files and add *.txt files to source
        for path, subdirs, files in os.walk(self._conf.get("library_path")):
            for name in files:
                if (fnmatch(name, "*.txt")):
                    self.source.add(os.path.join(path, name))

        # Loop over custom files and add *.txt files to custom
        for path, subdirs, files in os.walk(self._conf.get("custom_path")):
            for name in files:
                if (fnmatch(name, "*.txt")):
                    self.custom.add(os.path.join(path, name))

        # Create module directory if not already present and delete all module files
        if (not os.path.isdir(self._conf.get("module_path"))):
            os.makedirs(self._conf.get("module_path"))
        for f in os.listdir(self._conf.get("module_path")):
            if (fnmatch(f, "*.module")):
                os.unlink(self._conf.get("module_path") + f)

        # Create a regex for calculating priority from filename
        self.priorityRegex = re.compile("(?<=\.)\d+$")

        # First sort files by priority then compile them to module
        for src in self._sortPriority(self.source):
            self._makeModule(src)
        for src in self._sortPriority(self.custom):
            self._makeModule(src)

    def _sortPriority(self, files):
        ''' Sort data files based on their priority settings. '''
        ls = []
        # Loop over the files
        for addr in files:
            # Format the file name
            name = os.path.splitext(os.path.basename(addr))[0].lower().replace(
                "_", " ").replace("-", " ")
            # Search for priority tag on file name
            m = re.search(self.priorityRegex, name)
            # Add to ls as (symptom name, priority number, file name) with default priority of 100
            if (m):
                ls.append((name.replace("." + m.group(),
                                        ""), int(m.group()), addr))
            else:
                ls.append((name, 100, addr))
        # Sort the file list, first by the symptom name, then by the priority number
        ls.sort(reverse=True)
        if (ls):
            return (list(zip(*ls))[2])
        else:
            return ls

    def _makeModule(self, src):
        ''' Create application usable modules from data files. '''
        # Format the file name
        module = os.path.splitext(os.path.basename(src))[0].lower().replace(
            "_", " ").replace("-", " ")
        # Remove the priority tag from file name
        m = re.search(self.priorityRegex, module)
        if (m):
            module = module.replace("." + m.group(), "")
        # Create the module file name
        modFile = self._conf.get("module_path") + module + ".module"
        modFlag = False
        # Loop over both files, the source data file and the target module file
        with open(src, "r") as sf, open(modFile, "a") as tf:
            # Ignore lines starting with ! or #, + and - has special meaning, write other lines to module. Log the errors.
            for line in sf:
                line = line.strip().split("#")[0]
                if (len(line) == 0):
                    pass
                elif (line.startswith("!")):
                    pass
                elif (line.startswith("#")):
                    pass
                elif (line.startswith("+")):
                    modFlag = True
                elif (line.startswith("-")):
                    modFlag = True
                elif (line.replace(" ", "").replace("-", "").replace(
                        "_", "").replace("'", "").isalnum()):
                    print(self.alias.get(line).capitalize(), file=tf)
                else:
                    self.clean = False
                    logging.warning("Syntax error in file '" + src + "': " +
                                    line)
        # Deal with special lines
        if (modFlag):
            modFlag = False
            with open(src, "r") as f:
                for line in f:
                    line = line.strip().split("#")[0]
                    if (line[1:].replace(" ", "").replace("-", "").replace(
                            "_", "").replace("'", "").isalnum()):
                        # If line starts with + add it to the module file
                        if (line.startswith("+")):
                            with open(modFile, "r") as fn:
                                text = fn.read()
                            with open(modFile, "w") as fn:
                                print(self.alias.get(line[1:]).capitalize() +
                                      "\n" + text,
                                      file=fn)
                        # If line starts with - remove corresponding item from the module file
                        elif (line.startswith("-")):
                            with open(modFile, "r") as fn:
                                text = fn.read()
                            text = text.replace(
                                self.alias.get(line[1:]).capitalize() + "\n",
                                "")
                            with open(modFile, "w") as fn:
                                print(text, file=fn)

    def is_clean(self):
        '''Report if compilation ended successfully'''
        return self.clean
Example #36
0
    def __init__(self, oldkey, selectvessels):
        wx.Dialog.__init__(self,
                           None,
                           title=_('Select Signal K key'),
                           size=(710, 460))
        self.SetFont(
            wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL))
        panel = wx.Panel(self)

        conf = Conf()
        sk_folder = conf.get('GENERAL', 'sk_folder')
        data = ""
        try:
            with open(
                    sk_folder +
                    '/node_modules/@signalk/signalk-schema/dist/keyswithmetadata.json'
            ) as data_file:
                data = ujson.load(data_file)
        except:
            self.ShowMessage(
                _('Error. File not found: ') + 'keyswithmetadata.json')

        SK_ = SK_settings(conf)
        self.port = SK_.aktport
        self.http = SK_.http

        self.list_vessels = ['self']
        skvesselslabel = wx.StaticText(panel, label=_('Vessel'))
        self.skvessels = wx.ComboBox(panel, choices=self.list_vessels)
        self.refreshBtn = wx.Button(panel, label=_('Refresh'))
        self.refreshBtn.Bind(wx.EVT_BUTTON, self.OnRefreshBtn)
        self.skvessels.SetSelection(0)

        self.list_groups = wx.ListCtrl(panel,
                                       style=wx.LC_REPORT,
                                       size=(150, -1))
        self.list_groups.InsertColumn(0, _('Groups'), width=140)
        self.list_groups.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectGroup)

        self.list_skpaths = wx.ListCtrl(panel, style=wx.LC_REPORT)
        self.list_skpaths.InsertColumn(0, _('Keys'), width=350)
        self.list_skpaths.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectPath)

        self.list_skproperties = wx.ListCtrl(panel,
                                             style=wx.LC_REPORT,
                                             size=(130, -1))
        self.list_skproperties.InsertColumn(0, _('Properties'), width=120)
        self.list_skproperties.Bind(wx.EVT_LIST_ITEM_SELECTED,
                                    self.OnSelectProperty)

        self.key_description = wx.TextCtrl(panel,
                                           -1,
                                           style=wx.TE_MULTILINE
                                           | wx.TE_READONLY,
                                           size=(-1, 60))
        self.key_description.SetBackgroundColour(
            wx.SystemSettings_GetColour(wx.SYS_COLOUR_INACTIVECAPTION))

        wildcard_label = wx.StaticText(
            panel, label=_('Replace * (allowed characters: 0-9, a-z, A-Z)'))
        self.wildcard = wx.TextCtrl(panel)
        addBtn = wx.Button(panel, label=_('Replace'))
        addBtn.Bind(wx.EVT_BUTTON, self.OnAdd)

        selected_key_label = wx.StaticText(panel, label=_('Selected key'))
        self.SKkey = wx.TextCtrl(panel, style=wx.CB_READONLY)

        cancelBtn = wx.Button(panel, wx.ID_CANCEL)
        okBtn = wx.Button(panel, wx.ID_OK)
        okBtn.Bind(wx.EVT_BUTTON, self.OnOk)

        vessels = wx.BoxSizer(wx.HORIZONTAL)
        vessels.Add(skvesselslabel, 0, wx.TOP | wx.BOTTOM, 9)
        vessels.AddSpacer(5)
        vessels.Add(self.skvessels, 1, wx.TOP | wx.BOTTOM, 3)
        vessels.Add(self.refreshBtn, 0, wx.LEFT, 10)

        lists = wx.BoxSizer(wx.HORIZONTAL)
        lists.Add(self.list_groups, 0, wx.EXPAND, 0)
        lists.Add(self.list_skpaths, 1, wx.EXPAND, 0)
        lists.Add(self.list_skproperties, 0, wx.EXPAND, 0)

        wildcard = wx.BoxSizer(wx.HORIZONTAL)
        wildcard.Add(wildcard_label, 0, wx.TOP | wx.BOTTOM, 9)
        wildcard.AddSpacer(5)
        wildcard.Add(self.wildcard, 1, wx.TOP | wx.BOTTOM, 3)
        wildcard.Add(addBtn, 0, wx.LEFT, 10)

        key = wx.BoxSizer(wx.HORIZONTAL)
        key.Add(selected_key_label, 0, wx.TOP | wx.BOTTOM, 6)
        key.Add(self.SKkey, 1, wx.LEFT, 10)

        okcancel = wx.BoxSizer(wx.HORIZONTAL)
        okcancel.AddStretchSpacer(1)
        okcancel.Add(okBtn, 0, wx.ALL, 5)
        okcancel.Add(cancelBtn, 0, wx.ALL, 5)

        main = wx.BoxSizer(wx.VERTICAL)
        main.Add(vessels, 0, wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND, 5)
        main.Add(lists, 1, wx.ALL | wx.EXPAND, 5)
        main.Add(self.key_description, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 5)
        main.Add(wildcard, 0, wx.ALL | wx.EXPAND, 5)
        main.Add(key, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 5)
        main.Add(okcancel, 0, wx.ALL | wx.EXPAND, 0)

        panel.SetSizer(main)
        self.Centre()

        clean_data = {}
        for i in data:
            if '/vessels/*/' in i:
                new = i.replace('/vessels/*/', '')
                new = new.replace('RegExp', '*')
                new = new.replace('[A-Za-z0-9]+', '*')
                new = new.replace('/', '.')
                clean_data[new] = data[i]

        self.grouped_data = [{
            'name': 'ungrouped',
            'description': 'Keys that do not belong to any group',
            'keys': []
        }]
        groups_tmp = []
        for i in clean_data:
            items = i.split('.')
            first_key = items[0]
            if first_key in groups_tmp:
                exist = False
                for ii in self.grouped_data:
                    if ii['name'] == first_key: exist = True
                if not exist:
                    description = '[missing]'
                    if clean_data[first_key].has_key('description'):
                        description = clean_data[first_key]['description']
                    self.grouped_data.append({
                        'name': first_key,
                        'description': description,
                        'keys': []
                    })
            else:
                groups_tmp.append(first_key)

        self.grouped_data = sorted(self.grouped_data, key=lambda k: k['name'])

        for i in clean_data:
            items = i.split('.')
            first_key = items[0]
            rest = items
            rest.pop(0)
            keyname = '.'.join(rest)
            exist = False
            for ii in self.grouped_data:
                if ii['name'] == first_key:
                    exist = True
                    if i != first_key:
                        ii['keys'].append({
                            'name': keyname,
                            'content': clean_data[i]
                        })
            if not exist:
                for ii in self.grouped_data:
                    if ii['name'] == 'ungrouped':
                        ii['keys'].append({
                            'name': first_key,
                            'content': clean_data[i]
                        })
            for i in self.grouped_data:
                i['keys'] = sorted(i['keys'], key=lambda k: k['name'])

        self.list_groups2 = []
        for i in self.grouped_data:
            self.list_groups.Append([i["name"]])
            self.list_groups2.append(i["name"])

        self.selected_group = False
        self.selected_path = False
        self.selected_property = False

        self.list_skpaths2 = []

        if oldkey:
            skproperties = oldkey.split(':')
            skpath = skproperties[0].split('.')
            self.list_groups.Select(self.list_groups2.index(skpath[0]), 1)
            keysindex = -1
            for i in self.grouped_data[self.selected_group]['keys']:
                self.list_skpaths.Append([i["name"]])
                self.list_skpaths2.append(i["name"])
                if skproperties[0][len(skpath[0]) + 1:] == i["name"]:
                    keysindex = self.list_skpaths2.index(i["name"])

            if keysindex == -1:
                newkey = '*' + skproperties[0][len(skpath[0]) +
                                               len(skpath[1]) + 1:]
                for i in self.list_skpaths2:
                    if newkey == i:
                        keysindex = self.list_skpaths2.index(i)
                        self.wildcard.SetValue(skpath[1])

            if keysindex > -1:
                self.list_skpaths.Select(keysindex, 1)
                self.list_skpaths.Focus(keysindex)
                self.selected_path = keysindex
                keysindex = -1
                if len(skproperties) > 1:
                    list_skproperties2 = []
                    for i in self.grouped_data[self.selected_group]['keys'][
                            self.selected_path]['content']['properties']:
                        list_skproperties2.append(i)
                        if skproperties[1] == i:
                            keysindex = list_skproperties2.index(i)
                    if keysindex > -1:
                        self.list_skproperties.Select(keysindex, 1)
            self.SKkey.SetValue(oldkey)

        if not selectvessels:
            self.skvessels.Disable()
            self.refreshBtn.Disable()
        else:
            self.OnRefreshBtn(0)
Example #37
0
            if 0 == conf_analog.has_option(FIRMATA + str(i), 'adjust_points'):
                adjust_point_active[index] = 0
            else:
                line = conf_analog.get(FIRMATA + str(i), 'adjust_points')
                if line:
                    adjust_point[index] = eval(line)
                    adjust_point_active[index] = 1
                else:
                    adjust_point[index] = []
            index += 1


conf = Conf()
home = conf.home
currentpath = home + conf.get('GENERAL', 'op_folder') + '/openplotter'

if len(sys.argv) > 1:
    index = 1
    if sys.argv[1] == 'settings':
        print home + '/.openplotter/openplotter_analog.conf'
        subprocess.Popen(
            ['leafpad', home + '/.openplotter/openplotter_analog.conf'])
    exit
else:
    RawValue = []
    adjust_point = []
    adjust_point_active = []
    channel = []
    channel_index = []
    SK_name = []
Example #38
0
class MyFrame(wx.Frame):
    def __init__(self):

        self.conf = Conf()
        self.home = self.conf.home
        self.op_folder = self.conf.get('GENERAL', 'op_folder')
        self.help_bmp = wx.Bitmap(
            self.op_folder + "/static/icons/help-browser.png",
            wx.BITMAP_TYPE_ANY)
        Language(self.conf)
        self.SK_settings = SK_settings(self.conf)
        self.opencpnSettings = opencpnSettings()

        wx.Frame.__init__(self, None, title=_('SDR receiver'), size=(710, 380))

        self.SetFont(
            wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL))

        self.icon = wx.Icon(self.op_folder + '/static/icons/sdr.ico',
                            wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)

        calibrationbox = wx.StaticBox(self, label=_(' Calibration '))

        self.button_test_gain = wx.Button(self, label=_('Initial PPM'))
        self.Bind(wx.EVT_BUTTON, self.test_gain, self.button_test_gain)

        bands_label = wx.StaticText(self, label=_('Band'))
        bands_list = ['GSM850', 'GSM-R', 'GSM900', 'EGSM', 'DCS', 'PCS']
        self.band = wx.ComboBox(self, choices=bands_list, style=wx.CB_READONLY)
        self.check_bands = wx.Button(self, label=_('Get channel'))
        self.Bind(wx.EVT_BUTTON, self.check_band, self.check_bands)
        channel_label = wx.StaticText(self, label=_('Channel'))
        self.channel = wx.TextCtrl(self)
        self.check_channels = wx.Button(self, label=_('Get PPM'))
        self.Bind(wx.EVT_BUTTON, self.check_channel, self.check_channels)

        correction_label = wx.StaticText(self, label=_('PPM'))
        self.ppm = wx.TextCtrl(self)

        self.button_saveppm = wx.Button(self, label=_('Save PPM'))
        self.Bind(wx.EVT_BUTTON, self.on_saveppm, self.button_saveppm)

        aisbox = wx.StaticBox(self, label=' AIS ')

        self.ais_sdr_enable = wx.CheckBox(self, label=_('Enable'))
        self.ais_sdr_enable.Bind(wx.EVT_CHECKBOX, self.OnOffAIS)

        self.button_checkppm = wx.Button(self, label=_('Check AIS frequency'))
        self.Bind(wx.EVT_BUTTON, self.on_checkppm, self.button_checkppm)

        radiobox = wx.StaticBox(self, label=_(' Radio '))
        self.button_radio_default = wx.Button(self, label=_('Load defaults'))
        self.Bind(wx.EVT_BUTTON, self.on_radio_default,
                  self.button_radio_default)

        self.button_radio_16 = wx.Button(self, label=_('Channel 16'))
        self.Bind(wx.EVT_BUTTON, self.on_radio_16, self.button_radio_16)

        self.button_radio_9 = wx.Button(self, label=_('Channel 9'))
        self.Bind(wx.EVT_BUTTON, self.on_radio_9, self.button_radio_9)

        self.frequency = wx.SpinCtrl(self,
                                     min=24000000,
                                     max=1766000000,
                                     initial=156800000)
        self.button_radio_freq = wx.Button(self, label=_('Frequency'))
        self.Bind(wx.EVT_BUTTON, self.on_radio_freq, self.button_radio_freq)

        help_button = wx.BitmapButton(self,
                                      bitmap=self.help_bmp,
                                      size=(self.help_bmp.GetWidth() + 40,
                                            self.help_bmp.GetHeight() + 10))
        help_button.Bind(wx.EVT_BUTTON, self.on_help_sdr)

        self.CreateStatusBar()
        self.Centre()
        self.Show(True)

        ppm = self.conf.get('AIS-SDR', 'ppm')
        if not ppm: self.ppm.SetValue('0')
        else: self.ppm.SetValue(ppm)
        self.band.SetValue(self.conf.get('AIS-SDR', 'band'))
        self.channel.SetValue(self.conf.get('AIS-SDR', 'gsm_channel'))
        if self.conf.get('AIS-SDR', 'enable') == '1':
            self.ais_sdr_enable.SetValue(True)
            self.disable_sdr_controls()

        h_calibration1 = wx.BoxSizer(wx.HORIZONTAL)
        h_calibration1.AddSpacer(10)
        h_calibration1.Add(self.button_test_gain, 0, wx.RIGHT, 15)
        h_calibration1.Add(bands_label, 0, wx.TOP, 6)
        h_calibration1.Add(self.band, 0, wx.LEFT | wx.RIGHT, 5)
        h_calibration1.Add(self.check_bands, 0, wx.LEFT | wx.RIGHT, 5)
        h_calibration1.AddSpacer(10)
        h_calibration1.Add(channel_label, 0, wx.TOP, 6)
        h_calibration1.Add(self.channel, 0, wx.LEFT | wx.RIGHT, 5)
        h_calibration1.Add(self.check_channels, 0, wx.LEFT | wx.RIGHT, 5)

        h_calibration2 = wx.BoxSizer(wx.HORIZONTAL)
        h_calibration2.Add(correction_label, 0, wx.TOP, 6)
        h_calibration2.Add(self.ppm, 0, wx.LEFT | wx.RIGHT, 5)
        h_calibration2.Add(self.button_saveppm, 0, wx.LEFT | wx.RIGHT, 5)

        v_calibrationbox = wx.StaticBoxSizer(calibrationbox, wx.VERTICAL)
        v_calibrationbox.Add(h_calibration1, 0, wx.UP | wx.BOTTOM, 10)
        v_calibrationbox.Add(h_calibration2, 0, wx.LEFT | wx.BOTTOM, 10)

        h_aisbox = wx.StaticBoxSizer(aisbox, wx.HORIZONTAL)
        h_aisbox.Add(self.ais_sdr_enable, 0, wx.ALL, 10)
        h_aisbox.Add(self.button_checkppm, 0, wx.ALL, 10)

        h_radiobox = wx.StaticBoxSizer(radiobox, wx.HORIZONTAL)
        h_radiobox.Add(self.button_radio_default, 0, wx.ALL, 10)
        h_radiobox.Add(self.button_radio_9, 0, wx.ALL, 10)
        h_radiobox.Add(self.button_radio_16, 0, wx.ALL, 10)
        h_radiobox.AddSpacer(10)
        h_radiobox.Add(self.frequency, 0, wx.UP, 10)
        h_radiobox.AddSpacer(5)
        h_radiobox.Add(self.button_radio_freq, 0, wx.UP, 10)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.AddSpacer(5)
        vbox.Add(v_calibrationbox, 0, wx.ALL | wx.EXPAND, 5)
        vbox.Add(h_aisbox, 0, wx.ALL | wx.EXPAND, 5)
        vbox.Add(h_radiobox, 0, wx.ALL | wx.EXPAND, 5)
        vbox.AddStretchSpacer(1)
        vbox.Add(help_button, 0, wx.LEFT | wx.BOTTOM, 10)

        self.SetSizer(vbox)

    def kill_sdr(self):
        subprocess.call(['pkill', '-15', 'rtl_ais'])
        subprocess.call(['pkill', '-f', 'SDR_AIS_fine_cal.py'])
        subprocess.call(['pkill', '-15', 'rtl_test'])
        subprocess.call(['pkill', '-15', 'kal'])
        subprocess.call(['pkill', '-15', 'gqrx'])

    def enable_sdr_controls(self):
        self.ppm.Enable()
        self.button_test_gain.Enable()
        self.button_saveppm.Enable()
        self.button_checkppm.Enable()
        self.band.Enable()
        self.channel.Enable()
        self.check_bands.Enable()
        self.check_channels.Enable()
        self.button_radio_default.Enable()
        self.button_radio_9.Enable()
        self.button_radio_16.Enable()
        self.button_radio_freq.Enable()
        self.frequency.Enable()

    def disable_sdr_controls(self):
        self.ppm.Disable()
        self.button_test_gain.Disable()
        self.button_saveppm.Disable()
        self.button_checkppm.Disable()
        self.band.Disable()
        self.channel.Disable()
        self.check_bands.Disable()
        self.check_channels.Disable()
        self.button_radio_default.Disable()
        self.button_radio_9.Disable()
        self.button_radio_16.Disable()
        self.button_radio_freq.Disable()
        self.frequency.Disable()

    def OnOffAIS(self, e):
        self.kill_sdr()
        isChecked = self.ais_sdr_enable.GetValue()
        if isChecked:
            self.disable_sdr_controls()
            ppm = self.ppm.GetValue()
            try:
                int(ppm)
            except:
                self.ShowStatusBarRED(_('Failed. Wrong PPM'))
                return
            subprocess.Popen(['rtl_ais', '-R', '-p', ppm])
            self.conf.set('AIS-SDR', 'enable', '1')
            self.on_saveppm(0)
            msg = _('SDR-AIS reception enabled')
            opencpn = self.opencpnSettings.getConnectionState()
            if not opencpn:
                msg = _(
                    'Failed. The default OpenCPN connection is missing: input TCP localhost:10110'
                )
            elif opencpn == 'disabled':
                msg = _(
                    'Failed. The default OpenCPN connection is disabled: input TCP localhost:10110'
                )
        else:
            self.enable_sdr_controls()
            self.conf.set('AIS-SDR', 'enable', '0')
            msg = _('SDR-AIS reception disabled')

        if self.SK_settings.setSKsettings():
            seconds = 12
            subprocess.call(['sudo', 'systemctl', 'stop', 'signalk.service'])
            subprocess.call(['sudo', 'systemctl', 'stop', 'signalk.socket'])
            subprocess.call(['sudo', 'systemctl', 'start', 'signalk.socket'])
            subprocess.call(['sudo', 'systemctl', 'start', 'signalk.service'])
            for i in range(seconds, 0, -1):
                self.ShowStatusBarRED(
                    _('Restarting Signal K server... ') + str(i))
                time.sleep(1)
        self.ShowStatusBarBLACK(msg)

    def test_gain(self, event):
        self.kill_sdr()
        subprocess.Popen(['lxterminal', '-e', 'rtl_test', '-p'])
        msg = _(
            'Wait for "cumulative PPM" value to stabilize and copy it into "PPM" field'
        )
        self.ShowStatusBarBLACK(msg)

    def check_band(self, event):
        self.kill_sdr()
        band = self.band.GetValue()
        self.on_saveppm(0)
        self.conf.set('AIS-SDR', 'band', band)
        subprocess.Popen([
            'python', self.op_folder + '/tools/SDR_AIS/SDR_AIS_fine_cal.py',
            'b'
        ])
        msg = _(
            'Select the GSM band used in your country to get the strongest channel'
        )
        self.ShowStatusBarBLACK(msg)

    def check_channel(self, event):
        self.kill_sdr()
        channel = self.channel.GetValue()
        try:
            int(channel)
        except:
            self.ShowStatusBarRED(_('Failed. Wrong channel'))
            return
        self.on_saveppm(0)
        self.conf.set('AIS-SDR', 'gsm_channel', channel)
        if channel:
            subprocess.Popen([
                'python',
                self.op_folder + '/tools/SDR_AIS/SDR_AIS_fine_cal.py', 'c'
            ])
        msg = _('Use the strongest channel to calculate the final PPM')
        self.ShowStatusBarBLACK(msg)

    def on_radio_default(self, event):
        self.kill_sdr()
        subprocess.call([
            'cp', '-f', self.op_folder + '/tools/SDR_AIS/default.conf',
            self.home + '/.config/gqrx/'
        ])
        self.open_gqrx()

    def on_radio_16(self, event):
        self.kill_sdr()
        self.setconf('156800000')
        self.open_gqrx()

    def on_radio_9(self, event):
        self.kill_sdr()
        self.setconf('156450000')
        self.open_gqrx()

    def on_radio_freq(self, event):
        self.kill_sdr()
        self.setconf(self.frequency.GetValue())
        self.open_gqrx()

    def on_checkppm(self, event):
        self.kill_sdr()
        self.on_saveppm(0)
        self.setconf('162025000')
        self.open_gqrx()

    def setconf(self, frequency):
        self.gqrx_conf = ConfigParser.SafeConfigParser()
        self.gqrx_conf.read(self.home + '/.config/gqrx/default.conf')
        try:
            self.gqrx_conf.set('General', 'crashed', 'false')
        except ConfigParser.NoSectionError:
            self.gqrx_conf.add_section('General')
            self.gqrx_conf.set('General', 'crashed', 'false')
        try:
            self.gqrx_conf.set('input', 'frequency', str(frequency))
        except ConfigParser.NoSectionError:
            self.gqrx_conf.add_section('input')
            self.gqrx_conf.set('input', 'frequency', str(frequency))
        try:
            self.gqrx_conf.set('receiver', 'demod', '3')
        except ConfigParser.NoSectionError:
            self.gqrx_conf.add_section('receiver')
            self.gqrx_conf.set('receiver', 'demod', '3')
        with open(self.home + '/.config/gqrx/default.conf',
                  'wb') as configfile:
            self.gqrx_conf.write(configfile)

    def on_saveppm(self, event):
        ppm = self.ppm.GetValue()
        try:
            ppm2 = int(ppm) * 1000000
        except:
            self.ShowStatusBarRED(_('Failed. Wrong PPM'))
            return
        self.gqrx_conf = ConfigParser.SafeConfigParser()
        self.gqrx_conf.read(self.home + '/.config/gqrx/default.conf')
        try:
            self.gqrx_conf.set('input', 'corr_freq', str(ppm2))
        except ConfigParser.NoSectionError:
            self.gqrx_conf.add_section('input')
            self.gqrx_conf.set('input', 'corr_freq', str(ppm2))
        with open(self.home + '/.config/gqrx/default.conf',
                  'wb') as configfile:
            self.gqrx_conf.write(configfile)
        self.conf.set('AIS-SDR', 'ppm', ppm)
        self.ShowStatusBarGREEN(_('Saved PPM'))

    def open_gqrx(self):
        subprocess.Popen('gqrx')

    def on_help_sdr(self, e):
        url = self.op_folder + "/docs/html/tools/sdr_receiver.html"
        webbrowser.open(url, new=2)

    def ShowStatusBar(self, w_msg, colour):
        self.GetStatusBar().SetForegroundColour(colour)
        self.SetStatusText(w_msg)

    def ShowStatusBarRED(self, w_msg):
        self.ShowStatusBar(w_msg, wx.RED)

    def ShowStatusBarGREEN(self, w_msg):
        self.ShowStatusBar(w_msg, wx.GREEN)

    def ShowStatusBarBLACK(self, w_msg):
        self.ShowStatusBar(w_msg, wx.BLACK)
Example #39
0
class MainFrame(wx.Frame):
    def __init__(self):

        self.option = sys.argv[1]

        self.conf = Conf()
        self.home = self.conf.home
        self.currentpath = self.conf.get('GENERAL', 'op_folder')

        Language(self.conf)

        wx.Frame.__init__(self,
                          None,
                          title=_('Fine calibration'),
                          size=(600, 320))

        self.SetFont(
            wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL))

        self.icon = wx.Icon(self.currentpath + '/static/icons/openplotter.ico',
                            wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)

        self.text = wx.StaticText(self, label=_('Error'), pos=(10, 10))

        self.ppm = self.conf.get('AIS-SDR', 'ppm')
        self.band = self.conf.get('AIS-SDR', 'band')
        self.channel = self.conf.get('AIS-SDR', 'gsm_channel')

        wx.StaticText(self,
                      label=_('Initial PPM: ').decode('utf8') + self.ppm,
                      pos=(10, 80))

        self.output = wx.TextCtrl(self,
                                  style=wx.TE_MULTILINE | wx.TE_READONLY
                                  | wx.TE_DONTWRAP,
                                  size=(580, 120),
                                  pos=(10, 100))

        self.button_close = wx.Button(self, label=_('Close'), pos=(400, 230))
        self.Bind(wx.EVT_BUTTON, self.close, self.button_close)

        self.button_calculate = wx.Button(self,
                                          label=_('Start'),
                                          pos=(500, 230))
        self.Bind(wx.EVT_BUTTON, self.calculate, self.button_calculate)

        if self.option == 'c':
            self.text.SetLabel(
                _('Press Start and wait for the system to calculate the PPM value.\nRound the resulting PPM to the nearest integer and copy it into "PPM" field.\nEstimated time: 1 min.'
                  ))
            wx.StaticText(self,
                          label=_('channel: ').decode('utf8') + self.channel,
                          pos=(200, 80))
        if self.option == 'b':
            self.text.SetLabel(
                _('Press Start and wait for the system to check the band.\nWrite down the strongest channel (power).\nIf you do not find any channel try another band.\nEstimated time: 5 min.'
                  ))
            wx.StaticText(self,
                          label=_('band: ').decode('utf8') + self.band,
                          pos=(200, 80))

        self.CreateStatusBar()

        self.Centre()

    def calculate(self, e):
        self.SetStatusText(_('Working...'))
        self.output.SetValue('')
        if self.option == 'c':
            try:
                output = subprocess.check_output(
                    ['kal', '-c', self.channel, '-e', self.ppm])
            except Exception, e:
                output = _("Error: ") + str(e)
        if self.option == 'b':
            try:
                output = subprocess.check_output(
                    ['kal', '-s', self.band, '-e', self.ppm])
            except Exception, e:
                output = _("Error: ") + str(e)
Example #40
0
class Compile:
    '''
    This class creates a compiler for the DDStorm
    that compiles the text files containing list of
    differential diagnosis to simplified modular
    data files usable by the program.
    '''
    
    def __init__(self, conf=False):
        '''
        The constructor optionally accepts a configuration.
        If none is provided it creates a default configuration.

        Parameters:
        conf - A dictionary containing configuration options
        '''
        if(conf):
            self._conf=conf
        else:
            self._conf=Conf()
        self.clean=True

    def compile(self):
        ''' Compile the text files to DDStorm modules. '''
        self.source=set()
        self.custom=set()
        self.alias=Alias(self._conf)
        
        # Loop over library files and add *.txt files to source
        for path, subdirs, files in os.walk(self._conf.get("library_path")):
            for name in files:
                if(fnmatch(name, "*.txt")):
                    self.source.add(os.path.join(path, name))

        # Loop over custom files and add *.txt files to custom
        for path, subdirs, files in os.walk(self._conf.get("custom_path")):
            for name in files:
                if(fnmatch(name, "*.txt")):
                    self.custom.add(os.path.join(path, name))

        # Create module directory if not already present and delete all module files
        if(not os.path.isdir(self._conf.get("module_path"))):
            os.makedirs(self._conf.get("module_path"))
        for f in os.listdir(self._conf.get("module_path")):
            if(fnmatch(f, "*.module")):
                os.unlink(self._conf.get("module_path")+f)

        # Create a regex for calculating priority from filename
        self.priorityRegex=re.compile("(?<=\.)\d+$")

        # First sort files by priority then compile them to module
        for src in self._sortPriority(self.source):
            self._makeModule(src)
        for src in self._sortPriority(self.custom):
            self._makeModule(src)

    def _sortPriority(self, files):
        ''' Sort data files based on their priority settings. '''
        ls=[]
        # Loop over the files
        for addr in files:
            # Format the file name
            name=os.path.splitext(os.path.basename(addr))[0].lower().replace("_"," ").replace("-", " ")
            # Search for priority tag on file name
            m=re.search(self.priorityRegex, name)
            # Add to ls as (symptom name, priority number, file name) with default priority of 100
            if(m):
                ls.append((name.replace("."+m.group(), ""), int(m.group()), addr))
            else:
                ls.append((name, 100, addr))
        # Sort the file list, first by the symptom name, then by the priority number
        ls.sort(reverse=True)
        if(ls):
            return(list(zip(*ls))[2])
        else:
            return ls
        
    def _makeModule(self, src):
        ''' Create application usable modules from data files. '''
        # Format the file name
        module=os.path.splitext(os.path.basename(src))[0].lower().replace("_"," ").replace("-", " ")
        # Remove the priority tag from file name
        m=re.search(self.priorityRegex, module)
        if(m):
            module=module.replace("."+m.group(), "")
        # Create the module file name
        modFile=self._conf.get("module_path")+module+".module"
        modFlag=False
        # Loop over both files, the source data file and the target module file
        with open(src, "r") as sf, open(modFile, "a") as tf:
            # Ignore lines starting with ! or #, + and - has special meaning, write other lines to module. Log the errors.
            for line in sf:
                line=line.strip().split("#")[0]
                if(len(line)==0):
                    pass
                elif(line.startswith("!")):
                    pass
                elif(line.startswith("#")):
                    pass
                elif(line.startswith("+")):
                    modFlag=True
                elif(line.startswith("-")):
                    modFlag=True
                elif(line.replace(" ","").replace("-","").replace("_","").replace("'","").isalnum()):
                    print(self.alias.get(line).capitalize(), file=tf)
                else:
                    self.clean=False
                    logging.warning("Syntax error in file '"+src+"': "+line)
        # Deal with special lines
        if(modFlag):
            modFlag=False
            with open(src, "r") as f:
                for line in f:
                    line=line.strip().split("#")[0]
                    if(line[1:].replace(" ","").replace("-","").replace("_","").replace("'","").isalnum()):
                        # If line starts with + add it to the module file
                        if(line.startswith("+")):
                            with open(modFile, "r") as fn:
                                text=fn.read()
                            with open(modFile, "w") as fn:
                                print(self.alias.get(line[1:]).capitalize()+"\n"+text, file=fn)
                        # If line starts with - remove corresponding item from the module file
                        elif(line.startswith("-")):
                            with open(modFile, "r") as fn:
                                text=fn.read()
                            text=text.replace(self.alias.get(line[1:]).capitalize()+"\n", "")
                            with open(modFile, "w") as fn:
                                print(text, file=fn)

    def is_clean(self):
            '''Report if compilation ended successfully'''
            return self.clean
Example #41
0
class MyFrame(wx.Frame):
    def __init__(self):

        self.conf = Conf()
        self.home = self.conf.home
        self.currentpath = self.home + self.conf.get(
            'GENERAL', 'op_folder') + '/openplotter'

        Language(self.conf)

        wx.Frame.__init__(self, None, title=_('SDR receiver'), size=(690, 370))

        self.SetFont(
            wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL))

        self.icon = wx.Icon(self.currentpath + '/openplotter.ico',
                            wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)

        wx.StaticBox(self, label='', size=(400, 170), pos=(10, 10))

        self.ais_sdr_enable = wx.CheckBox(self,
                                          label=_('Enable AIS reception'),
                                          pos=(20, 25))
        self.ais_sdr_enable.Bind(wx.EVT_CHECKBOX, self.OnOffAIS)

        self.gain = wx.TextCtrl(self, -1, size=(55, 32), pos=(150, 60))
        self.gain_label = wx.StaticText(self, label=_('Gain'), pos=(20, 65))
        self.ppm = wx.TextCtrl(self, -1, size=(55, 32), pos=(150, 95))
        self.correction_label = wx.StaticText(self,
                                              label=_('Correction (ppm)'),
                                              pos=(20, 100))

        self.ais_frequencies1 = wx.CheckBox(self,
                                            label=_('Channel A 161.975Mhz'),
                                            pos=(220, 60))
        self.ais_frequencies1.Bind(wx.EVT_CHECKBOX, self.ais_frequencies)
        self.ais_frequencies2 = wx.CheckBox(self,
                                            label=_('Channel B 162.025Mhz'),
                                            pos=(220, 95))
        self.ais_frequencies2.Bind(wx.EVT_CHECKBOX, self.ais_frequencies)

        #self.show_kplex6 =wx.Button(self, label=_('Inspector'), pos=(20, 140))
        #self.Bind(wx.EVT_BUTTON, self.show_kplex, self.show_kplex6)
        self.button_test_ppm = wx.Button(self,
                                         label=_('Take a look'),
                                         pos=(150, 140))
        self.Bind(wx.EVT_BUTTON, self.test_ppm, self.button_test_ppm)
        self.button_test_gain = wx.Button(self,
                                          label=_('Calibration'),
                                          pos=(275, 140))
        self.Bind(wx.EVT_BUTTON, self.test_gain, self.button_test_gain)

        wx.StaticBox(self,
                     label=_(' Fine calibration using GSM '),
                     size=(260, 170),
                     pos=(420, 10))
        self.bands_label = wx.StaticText(self, label=_('Band'), pos=(430, 50))
        self.bands_list = ['GSM850', 'GSM-R', 'GSM900', 'EGSM', 'DCS', 'PCS']
        self.band = wx.ComboBox(self,
                                choices=self.bands_list,
                                style=wx.CB_READONLY,
                                size=(100, 32),
                                pos=(430, 70))
        self.band.SetValue('GSM900')
        self.check_bands = wx.Button(self,
                                     label=_('Check band'),
                                     pos=(540, 70))
        self.Bind(wx.EVT_BUTTON, self.check_band, self.check_bands)
        self.channel_label = wx.StaticText(self,
                                           label=_('Channel'),
                                           pos=(430, 125))
        self.channel = wx.TextCtrl(self, -1, size=(55, 32), pos=(430, 143))
        self.check_channels = wx.Button(self,
                                        label=_('Fine calibration'),
                                        pos=(495, 140))
        self.Bind(wx.EVT_BUTTON, self.check_channel, self.check_channels)

        wx.StaticBox(self, label=_(' Radio '), size=(260, 120), pos=(420, 185))

        self.button_vhf_Rx = wx.Button(self, label='Gqrx', pos=(430, 210))
        self.Bind(wx.EVT_BUTTON, self.vhf_Rx, self.button_vhf_Rx)

        self.CreateStatusBar()

        self.Centre()

        self.Show(True)

        output = subprocess.check_output('lsusb')
        supported_dev = [
            '0bda:2832', '0bda:2838', '0ccd:00a9', '0ccd:00b3', '0ccd:00d3',
            '0ccd:00d4', '0ccd:00e0', '185b:0620', '185b:0650', '1f4d:b803',
            '1f4d:c803', '1b80:d3a4', '1d19:1101', '1d19:1102', '1d19:1103',
            '0458:707f', '1b80:d393', '1b80:d394', '1b80:d395', '1b80:d39d'
        ]
        found = False
        for i in supported_dev:
            if i in output: found = True
        if found:
            self.gain.SetValue(self.conf.get('AIS-SDR', 'gain'))
            self.ppm.SetValue(self.conf.get('AIS-SDR', 'ppm'))
            self.band.SetValue(self.conf.get('AIS-SDR', 'band'))
            self.channel.SetValue(self.conf.get('AIS-SDR', 'gsm_channel'))
            if self.conf.get('AIS-SDR', 'enable') == '1':
                self.ais_sdr_enable.SetValue(True)
                self.disable_sdr_controls()
            if self.conf.get('AIS-SDR', 'channel') == 'a':
                self.ais_frequencies1.SetValue(True)
            if self.conf.get('AIS-SDR', 'channel') == 'b':
                self.ais_frequencies2.SetValue(True)
        else:
            self.ais_sdr_enable.Disable()
            self.disable_sdr_controls()
            self.button_test_gain.Disable()
            self.button_test_ppm.Disable()
            self.bands_label.Disable()
            self.channel_label.Disable()
            self.band.Disable()
            self.channel.Disable()
            self.check_channels.Disable()
            self.check_bands.Disable()
            self.button_vhf_Rx.Disable()

    def kill_sdr(self):
        subprocess.call(['pkill', '-9', 'aisdecoder'])
        subprocess.call(['pkill', '-9', 'rtl_fm'])
        subprocess.call(['pkill', '-f', 'SDR_AIS_waterfall.py'])
        subprocess.call(['pkill', '-f', 'SDR_AIS_fine_cal.py'])
        subprocess.call(['pkill', '-9', 'rtl_test'])
        subprocess.call(['pkill', '-9', 'kal'])
        subprocess.call(['pkill', '-9', 'gqrx'])

    def enable_sdr_controls(self):
        self.gain.Enable()
        self.ppm.Enable()
        self.ais_frequencies1.Enable()
        self.ais_frequencies2.Enable()
        self.gain_label.Enable()
        self.correction_label.Enable()
        self.ais_sdr_enable.SetValue(False)
        self.conf.set('AIS-SDR', 'enable', '0')

    def disable_sdr_controls(self):
        self.gain.Disable()
        self.ppm.Disable()
        self.ais_frequencies1.Disable()
        self.ais_frequencies2.Disable()
        self.gain_label.Disable()
        self.correction_label.Disable()

    def ais_frequencies(self, e):
        sender = e.GetEventObject()
        self.ais_frequencies1.SetValue(False)
        self.ais_frequencies2.SetValue(False)
        sender.SetValue(True)

    def OnOffAIS(self, e):
        self.kill_sdr()
        isChecked = self.ais_sdr_enable.GetValue()
        if isChecked:
            self.disable_sdr_controls()
            gain = self.gain.GetValue()
            ppm = self.ppm.GetValue()
            frecuency = '161975000'
            channel = 'a'
            if self.ais_frequencies2.GetValue():
                frecuency = '162025000'
                channel = 'b'
            rtl_fm = subprocess.Popen([
                'rtl_fm', '-f', frecuency, '-g', gain, '-p', ppm, '-s', '48k'
            ],
                                      stdout=subprocess.PIPE)
            aisdecoder = subprocess.Popen([
                'aisdecoder', '-h', 'localhost', '-p', '10110', '-a', 'file',
                '-c', 'mono', '-d', '-f', '/dev/stdin'
            ],
                                          stdin=rtl_fm.stdout)
            self.conf.set('AIS-SDR', 'enable', '1')
            self.conf.set('AIS-SDR', 'gain', gain)
            self.conf.set('AIS-SDR', 'ppm', ppm)
            self.conf.set('AIS-SDR', 'channel', channel)
            msg = _('SDR-AIS reception enabled')
        else:
            self.enable_sdr_controls()
            self.conf.set('AIS-SDR', 'enable', '0')
            msg = _('SDR-AIS reception disabled')
        self.SetStatusText(msg)

    def test_ppm(self, event):
        self.kill_sdr()
        self.enable_sdr_controls()
        gain = '25'
        if self.gain.GetValue():
            gain = self.gain.GetValue()
            gain = gain.replace(',', '.')
        ppm = '0'
        if self.ppm.GetValue():
            ppm = self.ppm.GetValue()
            ppm = ppm.replace(',', '.')
        channel = 'a'
        if self.ais_frequencies2.GetValue(): channel = 'b'
        w_open = subprocess.Popen([
            'python', self.currentpath + '/tools/SDR_AIS_waterfall.py', gain,
            ppm, channel
        ])
        msg = _(
            'AIS reception disabled. After closing the new window enable AIS reception again.'
        )
        self.SetStatusText(msg)

    def test_gain(self, event):
        self.kill_sdr()
        self.enable_sdr_controls()
        subprocess.Popen(['lxterminal', '-e', 'rtl_test', '-p'])
        msg = _(
            'SDR-AIS reception disabled.\nCheck the new window. Copy the maximum supported gain value. Wait for ppm value to stabilize and copy it too.'
        )
        self.ShowMessage(msg)

    def check_band(self, event):
        self.kill_sdr()
        self.enable_sdr_controls()
        gain = self.gain.GetValue()
        ppm = self.ppm.GetValue()
        band = self.band.GetValue()
        self.conf.set('AIS-SDR', 'gain', gain)
        self.conf.set('AIS-SDR', 'ppm', ppm)
        self.conf.set('AIS-SDR', 'band', band)
        subprocess.Popen(
            ['python', self.currentpath + '/tools/SDR_AIS_fine_cal.py', 'b'])
        msg = _(
            'AIS reception disabled. After closing the new window enable AIS reception again.'
        )
        self.SetStatusText(msg)

    def check_channel(self, event):
        self.kill_sdr()
        self.enable_sdr_controls()
        gain = self.gain.GetValue()
        ppm = self.ppm.GetValue()
        channel = self.channel.GetValue()
        self.conf.set('AIS-SDR', 'gain', gain)
        self.conf.set('AIS-SDR', 'ppm', ppm)
        self.conf.set('AIS-SDR', 'gsm_channel', channel)
        if channel:
            subprocess.Popen([
                'python', self.currentpath + '/tools/SDR_AIS_fine_cal.py', 'c'
            ])
        msg = _(
            'AIS reception disabled. After closing the new window enable AIS reception again.'
        )
        self.SetStatusText(msg)

    def vhf_Rx(self, event):
        self.kill_sdr()
        self.enable_sdr_controls()
        subprocess.Popen(self.home + '/.config/gqrx/run_gqrx.sh')
        msg = _(
            'AIS reception disabled. After closing the new window enable AIS reception again.'
        )
        self.SetStatusText(msg)

    def ShowMessage(self, w_msg):
        wx.MessageBox(w_msg, 'Info', wx.OK | wx.ICON_INFORMATION)
from  datetime import datetime
from conf import Conf
from playhouse.postgres_ext import Model
from playhouse.db_url import connect

db = connect(Conf.get('db_connection_string'), register_hstore=False)


class BaseModel(Model):
    class Meta:
        database = db

    def to_json(self):
        json = {}
        for key in self._data.keys():
            value = getattr(self, key)
            if isinstance(value, datetime):
                value = value.timestamp()
            if isinstance(value, BaseModel): continue
            json[key] = value
        return json
Example #43
0
class Index:
    ''' Provides an index of the upstream ancestors of symptoms '''
    def __init__(self, conf=False):
        '''
        Initiate the index object. Accepts a Conf object as an
        optional parameter.
        '''
        if (conf):
            self.conf = conf
        else:
            self.conf = Conf()
        self.data = {}
        self.compile()

    def compile(self):
        '''
        Compile the text index files to a application usable format.
        '''
        # Loop over all files under index_path
        for path, subdirs, files in os.walk(self.conf.get("index_path")):
            for name in files:
                # Only files with *.txt suffix
                if (fnmatch(name, "*.txt")):
                    with open(self.conf.get("index_path") + name, "r") as f:
                        # Two dimensional list buffer to hold the index
                        buff = []
                        buff.append([])
                        buff.append([])
                        # Loop over all lines as separate entries
                        for line in f:
                            # Ignore commnents starting with #
                            line = line.rstrip().split("#")[0]
                            if (len(line) == 0):
                                pass
                            else:
                                # Find number of leading whitespaces
                                ws = len(line) - len(line.lstrip())
                                # Format the entry
                                line = line.lstrip().capitalize()

                                # No leading whitespace means a top level entry i.e. no upstream ancestor
                                if (ws == 0):
                                    # Empty the buffer and add the entry
                                    del buff[0][:]
                                    buff[0].append(line.lstrip())
                                    # Reset the whitespace index
                                    del buff[1][:]
                                    buff[1].append(0)
                                # If leading whitespace > indexed whitespace, the entry is a subcategory of previous entry
                                elif (ws > buff[1][-1]):
                                    # Append entry to buffer as new item
                                    buff[0].append(line.lstrip())
                                    # Record leading whitespace to buffer
                                    buff[1].append(ws)
                                    # Copy buffer to data list
                                    self.data[buff[0][-1]] = list(
                                        reversed(buff[0]))
                                # If leading whitespace == indexed whitespace, the entry is at the same level with the previous entry
                                elif (ws == buff[1][-1]):
                                    # Append entry to last item of buffer
                                    buff[0][-1] = line.lstrip()
                                    buff[1][-1] = ws
                                    # Copy buffer to data list
                                    self.data[buff[0][-1]] = list(
                                        reversed(buff[0]))
                                # If leading whitespace < indexed whitespace, the entry is at an upper category than the previous entry
                                elif (ws < buff[1][-1]):
                                    # Loop over the buffer in reverse
                                    for i in reversed(buff[1]):
                                        # Discard all lower category items
                                        if (i >= ws):
                                            buff[0].pop()
                                            buff[1].pop()
                                        #Append the entry to buffer
                                        else:
                                            buff[0].append(line.lstrip())
                                            buff[1].append(ws)
                                            break
                                    # Copy buffer to data list
                                    self.data[buff[0][-1]] = list(
                                        reversed(buff[0]))

    def upstream(self, name):
        '''
        Return the upstream list of a symptom

        Parameter:
        name - the name of the symptom as string

        Return value:
        List of strings containing the upstream items
        '''
        if (len(name) > 0):
            if name in self.data:
                return self.data[name]
            else:
                return []

    def names(self):
        ''' Return all indexed symptoms name '''
        return list(self.data.keys())
Example #44
0
# coding:utf-8

from conf import Conf 

if __name__ == '__main__':
    global_conf = Conf('./conf/diffPy.conf')
    print global_conf.get('diff_args', 'offline_env')
    print 'main'
Example #45
0
class Deploy:
    def __init__(self):
        self.config = Conf()
        self.console = Console()

    def path(self, option):
        path = self.config.get(option)
        return os.path.abspath(path)

    def chown(self, path):
        user = self.config.get('deploy_user')
        self.console.run(['chown', '-R', user, path])

    def linkdir(self, src, dst):
        self.console.run(['unlink', dst])
        self.console.run(['ln', '-s', src, dst])

    def version(self, deploy_path):
        hash = self.console.run(['git', 'rev-parse', 'HEAD'], cwd=deploy_path)
        return hash[0:8]

    def sync(self, src, dst):
        self.console.run([
            'rsync', '--links', '--checksum', '--whole-file', '--recursive',
            '--exclude=".git"', '--exclude=".gitignore"',
            '--exclude=".gitmodules"',
            src.rstrip('/') + '/', dst
        ])

    def checkout(self, branch):
        deploy_path = self.path('release_path') + '/' + time.strftime(
            '%Y%m%d%H%M%S')

        if os.path.exists(deploy_path) == False:
            os.makedirs(deploy_path, 0755)

        self.console.success('Fetching files')
        self.console.run([
            'git', 'clone', '--quiet', '--recursive', '--depth', '1',
            '--branch', branch,
            self.config.get('repo_url'), deploy_path
        ])

        return deploy_path

    def composer(self, deploy_path):
        if os.path.exists(deploy_path + '/composer.json') == False:
            return None

        self.console.success('Installing composer dependencies')
        if (self.config.has('wcpw')
                == True) or (self.config.has('wearedefiant') == True):
            self.console.run([
                'composer', '--quiet', '--no-interaction', 'install',
                '--no-dev', '-o'
            ],
                             cwd=deploy_path)
        else:
            self.console.run([
                'composer', '--quiet', '--no-interaction', 'install',
                '--prefer-dist', '--no-dev', '--optimize-autoloader'
            ],
                             cwd=deploy_path)

    def bower(self, deploy_path):
        if os.path.exists(deploy_path + '/bower.json') == False:
            return None

        self.console.success('Installing bower dependencies')
        self.console.run(['bower', 'install', '--allow-root'], cwd=deploy_path)

    def packages(self, deploy_path):
        if os.path.exists(deploy_path + '/package.json') == False:
            return None

        self.console.success('Installing npm dependencies')
        if (self.config.has('wcpw')
                == True) or (self.config.has('wearedefiant') == True):
            self.console.run(['npm', 'install', '--silent'], cwd=deploy_path)
        else:
            self.console.run(['npm', 'install', '--silent', '--production'],
                             cwd=deploy_path)

    def gulp(self, deploy_path):
        if os.path.exists(deploy_path + '/gulpfile.js') == False:
            return None

        self.console.success('Running gulp')
        self.console.run(['node', 'node_modules/.bin/gulp'], cwd=deploy_path)

    def scripts(self, scripts_to_run, deploy_path):
        if self.config.has(scripts_to_run) == False:
            return

        scripts = self.config.get(scripts_to_run)

        for line in scripts:
            command = line.replace('$deploy_path', deploy_path)
            self.console.run(shlex.split(command), cwd=deploy_path)

    def clean(self):
        release_path = self.path('release_path')
        deployments = self.console.run(['ls', '-1tA', release_path])
        deploys_to_keep = int(self.config.get('deploys_to_keep'))

        for folder in deployments.splitlines()[deploys_to_keep:]:
            self.console.run(['rm', '-rf', folder], cwd=release_path)

    def deploy(self, branch="master"):
        # checkout files
        deploy_path = self.checkout(branch)

        # fetch resources
        self.composer(deploy_path)
        self.packages(deploy_path)
        self.bower(deploy_path)
        self.gulp(deploy_path)

        # static resources
        if self.config.has('static_path'):
            self.console.success('Copying static resources')
            self.sync(self.path('static_path'), deploy_path)

        self.console.success('Running pre-scripts')
        self.scripts('pre_scripts', deploy_path)

        self.console.success('Updating file owner')
        self.chown(deploy_path)

        self.console.success('Updating symlink')
        self.linkdir(deploy_path, self.config.get('symlink'))

        self.console.success('Running post-scripts')
        self.scripts('post_scripts', deploy_path)

        self.console.success('Cleaning up old releases')
        self.clean()