Exemplo n.º 1
0
 def send(self, widget):
     #print widget
     self.PackedData = []
     fields = [self.classification,
               gtk.Buildable.get_name(widget)]  #,item.get_text()]
     #print fields
     Communications.transmit(framer.wrapfieldscrc(fields))
Exemplo n.º 2
0
 def send(self, widget):
     self.PackedData = []
     #print widget
     #print 'widget class = ',widget.__class__.__name__
     if widget.__class__.__name__ == 'Entry':
         fields = [
             self.classification,
             gtk.Buildable.get_name(widget),
             widget.get_text()
         ]
         #print fields #['cfdata', 'StepNumX', '2000']
         #raw_input('fields')
     elif widget.__class__.__name__ == 'ComboBox':
         index = widget.get_active()  #indicate nth item selection
         model = widget.get_model()
         item = model[index][1]
         fields = [
             self.classification,
             gtk.Buildable.get_name(widget), item
         ]
     #print fields
     if Communications.serial_activated:
         #fields = ['cfdata', 'StepNumX', '2000']
         #msg_encodded = pw.wrapfieldscrc(fields)
         #print 'encoded = ',msg_encodded
         ##encoded =  [#[F709D151#]#[###[cfdata###]###[StepNumX###]###[2000###]#]]
         value = framer.wrapfieldscrc(fields)
         #print 'class ManualControlData is sending: ',value
         Communications.transmit(value)
    def __init__(self, requestFileName, config=None):
        self.config = config
        self._requestFileName = requestFileName
        self.batchRequestList = []
        self.__litleLimit_maxAllowedTransactionsPerFile = 500000
        self.requestId = None

        if config is None:
            self.config = Configuration()
            self.config.printXml = None
        confParser = ConfigParser()

        configFilePath = self.config.configFolder + '/' + self.config.getConfigFileName(
        )
        if not os.path.exists(configFilePath):
            f = open(configFilePath, 'a')
            f.close()

        confParser.read(configFilePath)
        propertyList = [
            "username", "password", "merchantId", "proxyHost", "proxyPort",
            "batchHost", "batchPort", "batchTcpTimeout", "batchUseSSL",
            "maxAllowedTransactionsPerFile", "maxTransactionsPerBatch",
            "batchRequestFolder", "batchResponseFolder", "sftpUsername",
            "sftpPassword", "sftpTimeout"
        ]

        for prop in propertyList:
            if confParser.has_option('PythonSDK',
                                     prop) and not hasattr(self.config, prop):
                setattr(self.config, prop, confParser.get('PythonSDK', prop))

        if confParser.has_option('PythonSDK', 'printXml') and hasattr(
                self.config, 'printXml') and self.config.printXml == None:
            setattr(self.config, 'printXml',
                    confParser.get('PythonSDK', 'printXml'))

        self.communication = Communications(self.config)

        self._maxAllowedTransactionsPerFile = int(
            getattr(self.config, 'maxAllowedTransactionsPerFile', '1000'))
        if self._maxAllowedTransactionsPerFile > self.__litleLimit_maxAllowedTransactionsPerFile:
            raise Exception('maxAllowedTransactionsPerFile property value cannot exceed'+ \
                            str(self.__litleLimit_maxAllowedTransactionsPerFile))

        __dirRequest = self.config.batchRequestFolder
        if not os.path.exists(__dirRequest):
            os.makedirs(__dirRequest)

        self.requestFile = open(__dirRequest + '/' + self._requestFileName,
                                'a')
        self.requestFile.close()

        __dirResponse = self.config.batchResponseFolder
        if not os.path.exists(__dirResponse):
            os.makedirs(__dirResponse)

        self.responseFile = open(__dirResponse + '/' + self._requestFileName,
                                 'a')
        self.responseFile.close()
Exemplo n.º 4
0
def send_file(filename):
    #create an object of protocol wrapper
    #if not Communications.active_serial == None:
    global framer
    PackedData = []
    file = open(filename, 'r')
    for line in file:
        #print line
        stripped = line.rstrip('\r\n')  #remove carriage returns
        if not (len(stripped) == 0):  #skip empty lines
            fields = ['gcode']  #initialieze fields list with classification
            fields.extend(stripped.split())  #tokenize on white spaces
            PackedData.append(framer.wrapfieldscrc(fields))  #wrap with crc
    for data in PackedData:
        Communications.transmit(data)  #transmit
 def __init__(self, Configuration):
     self.Configuration = Configuration
     self.MerchantId = Configuration.getMerchantId()
     self.User = Configuration.getUser()
     self.Password = Configuration.getPassword()
     self.ReportGroup = Configuration.getReportGroup()
     self.communications = Communications(self.Configuration)
     self.printXml = Configuration.getPrintXml()
Exemplo n.º 6
0
 def send(self):
     '''
     sends packed data over serial channel
     data will be in the format defined by protocol wrapper
     [Classification][Type][Data]
     [CRC32][Classification][Type][Data]
     
     call get_packedData to get the data to send
     '''
     #print self.get_packedData()[0]
     #if not Communications.active_serial == None:
     #         print self.get_packedData()
     #         raw_input('packed data')
     #         for data in self.get_packedData():
     #             C
     for data in self.get_packedData():
         Communications.transmit(data)
Exemplo n.º 7
0
 def __init__(self, Configuration):
     self.Configuration = Configuration
     self.MerchantId = Configuration.merchantId
     self.User = Configuration.username
     self.Password = Configuration.password
     self.ReportGroup = Configuration.reportGroup
     self.communications = Communications(self.Configuration)
     self.printXml = Configuration.printXml
 def test_van(self):
     tup = comm.WebComm().login(
         'https://accounts.ngpvan.com/oidc/login?signin=04287350137c8df2e7ad6a9beb1755c0',
         'Slark1101', '*****@*****.**')
     pp = pprint.PrettyPrinter(indent=2)
     print(tup[0])
     print('\n')
     print(tup[1])
Exemplo n.º 9
0
	def __init__(self, eventManager):

                self.EventKeyDown=6

                # initialize base class
                eventManager.addEventHandler("GameStart", self.onGameStart) #Stability
                eventManager.addEventHandler("BeginGameTurn", self.onBeginGameTurn) #Stability
                eventManager.addEventHandler("cityAcquired", self.onCityAcquired) #Stability
                eventManager.addEventHandler("cityRazed", self.onCityRazed) #Stability
                eventManager.addEventHandler("cityBuilt", self.onCityBuilt) #Stability
                eventManager.addEventHandler("combatResult", self.onCombatResult) #Stability
                eventManager.addEventHandler("changeWar", self.onChangeWar)
                eventManager.addEventHandler("religionFounded",self.onReligionFounded) #Victory
                eventManager.addEventHandler("buildingBuilt",self.onBuildingBuilt) #Victory
                eventManager.addEventHandler("projectBuilt",self.onProjectBuilt) #Victory
                eventManager.addEventHandler("BeginPlayerTurn", self.onBeginPlayerTurn)
                eventManager.addEventHandler("kbdEvent",self.onKbdEvent)
                eventManager.addEventHandler("OnLoad",self.onLoadGame) #edead: StoredData
                eventManager.addEventHandler("techAcquired",self.onTechAcquired) #Stability
                eventManager.addEventHandler("religionSpread",self.onReligionSpread) #Stability
                eventManager.addEventHandler("firstContact",self.onFirstContact)
                eventManager.addEventHandler("OnPreSave",self.onPreSave) #edead: StoredData
		eventManager.addEventHandler("vassalState", self.onVassalState)
		eventManager.addEventHandler("revolution", self.onRevolution)
		eventManager.addEventHandler("cityGrowth", self.onCityGrowth)
		eventManager.addEventHandler("unitPillage", self.onUnitPillage)
		eventManager.addEventHandler("cityCaptureGold", self.onCityCaptureGold)
		eventManager.addEventHandler("playerGoldTrade", self.onPlayerGoldTrade)
		eventManager.addEventHandler("tradeMission", self.onTradeMission)
		eventManager.addEventHandler("playerSlaveTrade", self.onPlayerSlaveTrade)
		eventManager.addEventHandler("playerChangeStateReligion", self.onPlayerChangeStateReligion)
		                
		#Leoreth
		eventManager.addEventHandler("greatPersonBorn", self.onGreatPersonBorn)
		eventManager.addEventHandler("unitCreated", self.onUnitCreated)
		eventManager.addEventHandler("unitBuilt", self.onUnitBuilt)
		eventManager.addEventHandler("plotFeatureRemoved", self.onPlotFeatureRemoved)
		eventManager.addEventHandler("goldenAge", self.onGoldenAge)
		eventManager.addEventHandler("releasedPlayer", self.onReleasedPlayer)
		eventManager.addEventHandler("cityAcquiredAndKept", self.onCityAcquiredAndKept)
		eventManager.addEventHandler("blockade", self.onBlockade)
		eventManager.addEventHandler("peaceBrokered", self.onPeaceBrokered)
               
                self.eventManager = eventManager

                self.rnf = RiseAndFall.RiseAndFall()
                self.barb = Barbs.Barbs()
                self.rel = Religions.Religions()
                self.res = Resources.Resources()
                self.up = UniquePowers.UniquePowers()
                self.aiw = AIWars.AIWars()
                self.pla = Plague.Plague()
                self.com = Communications.Communications()
                self.corp = Companies.Companies()

		self.dc = DynamicCivs.DynamicCivs()
Exemplo n.º 10
0
    def extra(self, MainWindow):
        self.MainWindow = MainWindow
        self.screenshot_dir = "screenshots"
        if not os.path.isdir(self.screenshot_dir):
            os.mkdir(self.screenshot_dir)
        # for vertical widget
        self.terminal.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.terminal.setFont(font)
        self.signal_terminal.connect(self.add_to_terminal)

        # create for progress bar
        signals = [self.signal_dowload, self.signal_terminal]
        self.signal_dowload.connect(self.update_download_progress)
        self.download_progress = None

        self.coms = Communications(signals)
        self.add_folder_tree()
        self.add_vlc()
        self.button_get_files.clicked.connect(self.download_files)
        self.button_screenshot.clicked.connect(self.take_screenshot)
        self.live_on_off = ["Stop Live Stream", "Start Live Stream"]
        self.button_live_stream.clicked.connect(self.change_live)
        self.button_reset_connection.clicked.connect(self.reset_connection)

        # create settings now
        self.button_apply_settings.clicked.connect(self.send_cam_settings)
        self.button_auto_settings.clicked.connect(
            lambda: self.reset_cam_settings(None))
        # see if there are any settings files for the camera
        if os.path.isfile("settings.txt"):
            with open("settings.txt", "r") as settings:
                s = [int(i) for i in settings.readlines()]
        else:
            s = None
        self.reset_cam_settings(s)
        self.thread_handler = ThreadPoolHandler()
        # create a list of buttons to be disabled when downloading is in progress
        self.button_list = [
            self.button_get_files, self.button_apply_settings,
            self.button_live_stream, self.button_auto_settings
        ]
Exemplo n.º 11
0
def get_com_port_list():

    #create an instance of Liststore with data
    liststore = gtk.ListStore(int, str)
    Com_List = Communications.list_serial_ports()
    liststore.append([0, "Select a valid serial port:"])
    for port_number in range(len(Com_List)):
        #print port_number
        liststore.append([port_number, Com_List[port_number]])
    return liststore
Exemplo n.º 12
0
    def __init__(self, eventManager):

        self.lastRegionID = -1
        self.bStabilityOverlay = False
        self.EventKeyDown = 6
        self.EventKeyUp = 7
        self.eventManager = eventManager

        # initialize base class
        eventManager.addEventHandler("GameStart", self.onGameStart)
        eventManager.addEventHandler("OnLoad", self.onLoadGame)
        eventManager.addEventHandler("OnPreSave", self.onPreSave)
        eventManager.addEventHandler("BeginGameTurn", self.onBeginGameTurn)
        eventManager.addEventHandler("EndGameTurn", self.onEndGameTurn)
        eventManager.addEventHandler("BeginPlayerTurn", self.onBeginPlayerTurn)
        eventManager.addEventHandler("EndPlayerTurn", self.onEndPlayerTurn)
        eventManager.addEventHandler("firstContact", self.onFirstContact)
        eventManager.addEventHandler("cityAcquired", self.onCityAcquired)
        eventManager.addEventHandler("goldenAge", self.onGoldenAge)  # srpt
        eventManager.addEventHandler("corporationSpread",
                                     self.onCorporationSpread)  # srpt
        eventManager.addEventHandler("cityAcquiredAndKept",
                                     self.onCityAcquiredAndKept)
        eventManager.addEventHandler("cityRazed", self.onCityRazed)
        eventManager.addEventHandler("cityBuilt", self.onCityBuilt)
        eventManager.addEventHandler("combatResult", self.onCombatResult)
        eventManager.addEventHandler("buildingBuilt", self.onBuildingBuilt)
        eventManager.addEventHandler("projectBuilt", self.onProjectBuilt)
        eventManager.addEventHandler("techAcquired", self.onTechAcquired)
        eventManager.addEventHandler("religionSpread", self.onReligionSpread)
        eventManager.addEventHandler("unitSpreadReligionAttempt",
                                     self.onUnitSpreadReligionAttempt)
        eventManager.addEventHandler("playerChangeStateReligion",
                                     self.onPlayerChangeStateReligion)
        eventManager.addEventHandler("vassalState", self.onVassalState)
        eventManager.addEventHandler("changeWar", self.onChangeWar)
        eventManager.addEventHandler("unitBuilt", self.onUnitBuilt)
        eventManager.addEventHandler("revolution", self.onRevolution)
        eventManager.addEventHandler("setPlayerAlive", self.onSetPlayerAlive)
        eventManager.addEventHandler("greatPersonBorn", self.onGreatPersonBorn)
        eventManager.addEventHandler("kbdEvent", self.onKbdEvent)

        self.rnf = RiseAndFall.RiseAndFall()
        self.cnm = CityNameManager.CityNameManager()
        self.res = Resources.Resources()
        self.rel = Religions.Religions()
        self.barb = Barbs.Barbs()
        self.aiw = AIWars.AIWars()
        self.vic = Victory.Victory()
        #self.pla = Plague.Plague()
        self.com = Communications.Communications()
        self.dc = DynamicCivs.DynamicCivs()
        self.corp = Companies.Companies()
        self.rfccwaiw = RFCCWAIWars.RFCCWAIWars()
    def __init__(self,requestFileName, config = None):
        self.config = config
        self._requestFileName = requestFileName
        self.batchRequestList = []
        self.__litleLimit_maxAllowedTransactionsPerFile = 500000
        self.requestId = None

        if config is None:
            self.config = Configuration()
            self.config.printXml = None
        confParser = ConfigParser()

        configFilePath = self.config.configFolder + '/' + self.config.getConfigFileName()
        if not os.path.exists(configFilePath):
            f = open(configFilePath, 'a')
            f.close()

        confParser.read(configFilePath)
        propertyList = ["username", "password", "merchantId", "proxyHost",
			 		    "proxyPort", "batchHost", "batchPort",
			 		    "batchTcpTimeout", "batchUseSSL",
			 		    "maxAllowedTransactionsPerFile", "maxTransactionsPerBatch",
			 		    "batchRequestFolder", "batchResponseFolder", "sftpUsername", "sftpPassword", "sftpTimeout"]

        for prop in propertyList:
            if confParser.has_option('PythonSDK', prop) and not hasattr(self.config, prop):
                setattr(self.config, prop, confParser.get('PythonSDK', prop))
        
        if confParser.has_option('PythonSDK', 'printXml') and hasattr(self.config, 'printXml') and self.config.printXml == None :
            setattr(self.config, 'printXml', confParser.get('PythonSDK','printXml'))

        self.communication = Communications(self.config)

        self._maxAllowedTransactionsPerFile = int(getattr(self.config, 'maxAllowedTransactionsPerFile', '1000'))
        if self._maxAllowedTransactionsPerFile > self.__litleLimit_maxAllowedTransactionsPerFile:
            raise Exception('maxAllowedTransactionsPerFile property value cannot exceed'+ \
                            str(self.__litleLimit_maxAllowedTransactionsPerFile))

        __dirRequest = self.config.batchRequestFolder
        if not os.path.exists(__dirRequest):
            os.makedirs(__dirRequest)


        self.requestFile = open(__dirRequest + '/' + self._requestFileName,'a')
        self.requestFile.close()

        __dirResponse = self.config.batchResponseFolder
        if not os.path.exists(__dirResponse):
            os.makedirs(__dirResponse)

        self.responseFile = open(__dirResponse + '/' + self._requestFileName,'a')
        self.responseFile.close()
Exemplo n.º 14
0
    def _send(self, command='ADEAD', payload='', queue_priority=0):
        '''
        payload should be a binary string in the format of the length of payload
        queue_priority == 0 is the fastest and the higher the number the slower 
        #note:set all gcode commands priority = 1, this will place gcode in slow queue
        #allowing user sent commands to be processed quickly even if routing is in progress
        '''
        payload_len = self.command_list[command]['command_length']
        received_payload_len = len(payload) / self.bits_per_byte
        cmd_num = self.get_bin(self.command_list[command]['command_number'],
                               self.command_num_bits)

        cmd_len = self.get_bin(payload_len, self.command_len_bits)

        #verify length of payload matches the specified length

        if not payload_len == received_payload_len:
            print 'specified payload {} does not match recevied payload size {}'.format(
                payload_len, received_payload_len)
        full_command_bin = cmd_num + cmd_len + payload  #build full binary string
        hex_fill = '{0:0>' + str(len(full_command_bin) / 4) + '}'
        #print '%x'% int(full_command_bin,2)
        full_command_hex = hex_fill.format(
            '%x' % int(full_command_bin, 2))  #build hex string zero fill

        #full_command_ascii = binascii.b2a_uu(full_command_bin)
        #self._send_handle.send(full_command_hex.decode('hex'))
        #print 'command ',command, cmd_num, cmd_len

        #print 'full_command binary:',command, cmd_num, cmd_len,payload
        #print 'full_command_decode',full_command_hex.decode('hex')
        #print 'full_command hex: ',full_command_hex
        #print 'full_command ascii:',full_command_ascii
        #         producer1 = Communications.count_stuff(1,5,Communications.myQueue)
        #         producer1.start()
        Communications.transmit(full_command_hex.decode('hex'), queue_priority)
Exemplo n.º 15
0
"""
Test the reading of sensor data
"""

import Communications as com
import pygame
import time
from random import random
from math import *

# setup pygame window
com.init()

pygame.init()
screen = pygame.display.set_mode((512, 600))

origin_x = 256
origin_y = 580

d = 4
pos = 0

com.set_drive_motors(20,20)
com.reset_robot(78,12,0)

for i in xrange(500):

    # pos = -100 + int(random() * 200)
    pos += d
    if pos >= 120 or pos <= -120:
        d *= -1
Exemplo n.º 16
0
class litleBatchFileRequest:

    def __init__(self,requestFileName, config = None):
        self.config = config
        self._requestFileName = requestFileName
        self.batchRequestList = []
        self.__litleLimit_maxAllowedTransactionsPerFile = 500000
        self.requestId = None

        if config is None:
            self.config = Configuration()
            self.config.printXml = None
        confParser = ConfigParser()

        configFilePath = self.config.configFolder + '/' + self.config.getConfigFileName()
        if not os.path.exists(configFilePath):
            f = open(configFilePath, 'a')
            f.close()

        confParser.read(configFilePath)
        propertyList = ["username", "password", "merchantId", "proxyHost",
			 		    "proxyPort", "batchHost", "batchPort",
			 		    "batchTcpTimeout", "batchUseSSL",
			 		    "maxAllowedTransactionsPerFile", "maxTransactionsPerBatch",
			 		    "batchRequestFolder", "batchResponseFolder", "sftpUsername", "sftpPassword", "sftpTimeout"]

        for prop in propertyList:
            if confParser.has_option('PythonSDK', prop) and not hasattr(self.config, prop):
                setattr(self.config, prop, confParser.get('PythonSDK', prop))
        
        if confParser.has_option('PythonSDK', 'printXml') and hasattr(self.config, 'printXml') and self.config.printXml == None :
            setattr(self.config, 'printXml', confParser.get('PythonSDK','printXml'))

        self.communication = Communications(self.config)

        self._maxAllowedTransactionsPerFile = int(getattr(self.config, 'maxAllowedTransactionsPerFile', '1000'))
        if self._maxAllowedTransactionsPerFile > self.__litleLimit_maxAllowedTransactionsPerFile:
            raise Exception('maxAllowedTransactionsPerFile property value cannot exceed'+ \
                            str(self.__litleLimit_maxAllowedTransactionsPerFile))

        __dirRequest = self.config.batchRequestFolder
        if not os.path.exists(__dirRequest):
            os.makedirs(__dirRequest)


        self.requestFile = open(__dirRequest + '/' + self._requestFileName,'a')
        self.requestFile.close()

        __dirResponse = self.config.batchResponseFolder
        if not os.path.exists(__dirResponse):
            os.makedirs(__dirResponse)

        self.responseFile = open(__dirResponse + '/' + self._requestFileName,'a')
        self.responseFile.close()

    def createBatch(self, merchantId = None):
        request = litleBatchRequest(self, merchantId)
        self.batchRequestList.append(request)
        return request

    def getNumberOfTransactionInFile(self):
        totalNumOfTxns = 0
        for batch in self.batchRequestList:
            totalNumOfTxns += batch.numOfTxn
        return totalNumOfTxns

    def sendRequestTCP(self):
        self.prepareForDelivery()
        self.communication.sendRequestFileToIBC(self.requestFile.name, self.responseFile.name, self.config)
        response = litleBatchFileResponse(self.responseFile.name)
        return response

    def sendRequestSFTP(self, useExistingFile = False):
        if not useExistingFile:
            self.prepareForDelivery()
        self.communication.sendRequestFileToSFTP(self.requestFile.name, self.config)
        self.communication.receiveResponseFileFromSFTP(self.requestFile.name, self.responseFile.name, self.config)
        response = litleBatchFileResponse(self.responseFile.name)
        return response

    def sendRequestOnlyToSFTP(self, useExistingFile = False):
        if not useExistingFile:
            self.prepareForDelivery()
        self.communication.sendRequestFileToSFTP(self.requestFile.name, self.config)

    def retrieveOnlyFromSFTP(self):
        self.communication.receiveResponseFileFromSFTP(self.requestFile.name, self.responseFile.name, self.config)
        response = litleBatchFileResponse(self.responseFile.name)
        return response

    def prepareForDelivery(self):
        writeFolderPath = self.config.batchRequestFolder
        self.tempBatchRequestFile = open(writeFolderPath + '/tmp/tempBatchFile','wb')
        for batch in self.batchRequestList:
            batchHeader = self.tnxToXml(batch._batchRequest)
            self.tempBatchRequestFile.write(batchHeader.replace('/>' , '>'))
            with open(batch._filePath,'rb') as batchFile:
                shutil.copyfileobj(batchFile, self.tempBatchRequestFile,4096)
            self.tempBatchRequestFile.write('</batchRequest>\n')
            os.remove(batch._filePath)
        self.tempBatchRequestFile.close()
        self.generateRequestFile()
        shutil.rmtree(writeFolderPath + '/tmp')

    def generateRequestFile(self):
        authentication = litleXmlFields.authentication()
        authentication.password = self.config.password
        authentication.user = self.config.username

        litleRequest = litleXmlFields.litleRequest()
        if self.requestId is not None and len(self.requestId) != 0:
            litleRequest.id = self.requestId

        litleRequest.authentication = authentication
        litleRequest.version = '9.3'
        litleRequest.numBatchRequests = len(self.batchRequestList)
        requestFile = open(self.requestFile.name,'wb')
        requestFile.write(self.tnxToXml(litleRequest).replace('</litleRequest>', ''))
        with open(self.tempBatchRequestFile.name,'rb') as tempBatchFile:
            shutil.copyfileobj(tempBatchFile, requestFile, 4096)
        requestFile.write('</litleRequest>\n')
        requestFile.close()
        os.remove(self.tempBatchRequestFile.name)

    def tnxToXml(self, transaction):
        dom = transaction.toDOM()
        temp = dom.toxml('utf-8')
        temp= temp.replace('ns1:','')
        temp =  temp.replace(':ns1','')
        return temp.replace('<?xml version="1.0" encoding="utf-8"?>','')

    def getNumberOfBatches(self):
        return len(self.batchRequestList)

    def isEmpty(self):
        return True if self.getNumberOfTransactionInFile() == 0 else False

    def isFull(self):
        return self.getNumberOfTransactionInFile() == self._maxAllowedTransactionsPerFile
Exemplo n.º 17
0
 def send(self, widget):
     fields = [self.classification, 'RouterPWM',
               widget.get_text()]  #,item.get_text()]
     print fields
     Communications.transmit(framer.wrapfieldscrc(fields))
Exemplo n.º 18
0
class Ui_MainWindow(QObject, UI):
    signal_terminal = QtCore.pyqtSignal(str)
    signal_dowload = QtCore.pyqtSignal(int)

    def extra(self, MainWindow):
        self.MainWindow = MainWindow
        self.screenshot_dir = "screenshots"
        if not os.path.isdir(self.screenshot_dir):
            os.mkdir(self.screenshot_dir)
        # for vertical widget
        self.terminal.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.terminal.setFont(font)
        self.signal_terminal.connect(self.add_to_terminal)

        # create for progress bar
        signals = [self.signal_dowload, self.signal_terminal]
        self.signal_dowload.connect(self.update_download_progress)
        self.download_progress = None

        self.coms = Communications(signals)
        self.add_folder_tree()
        self.add_vlc()
        self.button_get_files.clicked.connect(self.download_files)
        self.button_screenshot.clicked.connect(self.take_screenshot)
        self.live_on_off = ["Stop Live Stream", "Start Live Stream"]
        self.button_live_stream.clicked.connect(self.change_live)
        self.button_reset_connection.clicked.connect(self.reset_connection)

        # create settings now
        self.button_apply_settings.clicked.connect(self.send_cam_settings)
        self.button_auto_settings.clicked.connect(
            lambda: self.reset_cam_settings(None))
        # see if there are any settings files for the camera
        if os.path.isfile("settings.txt"):
            with open("settings.txt", "r") as settings:
                s = [int(i) for i in settings.readlines()]
        else:
            s = None
        self.reset_cam_settings(s)
        self.thread_handler = ThreadPoolHandler()
        # create a list of buttons to be disabled when downloading is in progress
        self.button_list = [
            self.button_get_files, self.button_apply_settings,
            self.button_live_stream, self.button_auto_settings
        ]

    def download_files(self):
        [b.setDisabled(True) for b in self.button_list]
        self.coms.get_files(self.button_list)

    def reset_connection(self):
        try:
            [b.setDisabled(False) for b in self.button_list]
            print("killing coms")
            self.coms.restart()
            print("after killing")
            time.sleep(3)
            if self.download_progress:
                self.download_progress.setParent(None)
                self.download_progress = None
        except:
            traceback.print_exc()

    def reset_cam_settings(self, settings=None):
        if settings is None:
            self.slider_updown.setSliderPosition(100)
            self.slider_leftright.setSliderPosition(0)
            self.slider_zoom.setSliderPosition(0)
            self.slider_exposure.setSliderPosition(50)
        else:
            self.slider_updown.setSliderPosition(settings[3])
            self.slider_leftright.setSliderPosition(settings[2])
            self.slider_zoom.setSliderPosition(settings[1])
            self.slider_exposure.setSliderPosition(settings[0])
        time.sleep(0.5)
        if len(self.coms.connected_cameras) > 0:
            self.send_cam_settings()

    def send_cam_settings(self):
        sliders = (self.slider_exposure.sliderPosition(),
                   self.slider_zoom.sliderPosition(),
                   self.slider_leftright.sliderPosition(),
                   self.slider_updown.sliderPosition())
        # first save changes in text file
        with open("settings.txt", "w+") as s:
            for slider in sliders:
                s.write(f"{slider}\n")
        self.coms.change_cam_settings(*sliders)

    @QtCore.pyqtSlot(int)
    def update_download_progress(self, prog):
        if self.download_progress:
            # check if new progress is lower than before, maybe it's a new session
            if self.download_progress.value() > prog:
                self.download_progress = None
                return
            self.download_progress.setValue(prog)
            if prog == 100:
                self.terminal.append("Finished downloading camera videos")
                self.download_progress.setParent(None)
                self.download_progress = None
        elif prog != 100:
            self.download_progress = QtWidgets.QProgressBar()
            self.verticalLayout_3.addWidget(self.download_progress)
            #self.groupBox.append(self.download_progress)
        #self.terminal.append(f"Progress is {prog}")

    @QtCore.pyqtSlot(str)
    def add_to_terminal(self, text):
        new = QtWidgets.QLabel(text)
        #self.terminal.addWidget(new)
        self.terminal.append(text)
        #self.scrollArea.ensureWidgetVisible(new, yMargin=0, xMargin=0)

    def change_live(self):
        if len(self.coms.connected_cameras) == 0:
            self.terminal.append("No camera(s) connected")
        elif self.button_live_stream.text() == self.live_on_off[0]:
            # self.terminal.addWidget(QtWidgets.QLabel("Turning off live stream"))
            self.coms.play_pause_live_stream(self.live_image)
            self.button_live_stream.setText(self.live_on_off[1])
        elif self.button_live_stream.text() == self.live_on_off[1]:
            # self.terminal.addWidget(QtWidgets.QLabel("Turning on live stream"))
            self.coms.play_pause_live_stream(self.live_image)
            self.button_live_stream.setText(self.live_on_off[0])

    def add_vlc(self):
        self.opened_file = None
        self.instance = vlc.Instance()
        self.mediaplayer = self.instance.media_player_new()
        self.button_play_pause.clicked.connect(self.playpause)
        self.timer = QTimer(self.MainWindow)
        self.timer.setInterval(200)
        self.timer.timeout.connect(self.updateUI)
        self.positionslider = self.horizontalSlider
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

    def Stop(self):
        """Stop player
        """
        self.mediaplayer.stop()
        self.button_play_pause.setText("Play")
        self.opened_file = None

    def updateUI(self):
        """updates the user interface"""
        # setting the slider to the desired position
        self.positionslider.setValue(self.mediaplayer.get_position() * 1000)

        if not self.mediaplayer.is_playing():
            # no need to call this function if nothing is played
            self.timer.stop()
            if not self.isPaused:
                # after the video finished, the play button stills shows
                # "Pause", not the desired behavior of a media player
                # this will fix it
                self.Stop()

    def open_video(self, filename=None):
        """Open a media file in a MediaPlayer
        """
        self.media = self.instance.media_new(filename)
        # put the media in the media player
        self.mediaplayer.set_media(self.media)
        # parse the metadata of the file
        self.media.parse()
        if sys.platform.startswith('linux'):  # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.main_video_frame.winId())
        elif sys.platform == "win32":  # for Windows
            self.mediaplayer.set_hwnd(self.main_video_frame.winId())
        elif sys.platform == "darwin":  # for MacOS
            self.mediaplayer.set_nsobject(int(self.main_video_frame.winId()))
        self.playpause()

    def take_screenshot(self):
        if not self.mediaplayer.play() == -1:
            name = f"{self.screenshot_dir}/{len(os.listdir(self.screenshot_dir))}.jpg"
            self.mediaplayer.video_take_snapshot(
                0,
                name,
                i_width=self.mediaplayer.video_get_width(),
                i_height=self.mediaplayer.video_get_height())
            self.mediaplayer.pause()
        else:
            self.signal_terminal.emit(
                "Video needs to be played before taking screenshot")

    def playpause(self):
        """Toggle play/pause status
        """
        print("HERE", self.mediaplayer.is_playing())
        if self.mediaplayer.is_playing():
            self.mediaplayer.pause()
            self.button_play_pause.setText("Play")
            self.isPaused = True
        else:
            if self.mediaplayer.play() == -1:
                print("no video selected")
                # self.OpenFile()
                return
            self.mediaplayer\
                .play()
            self.button_play_pause.setText("Pause")
            self.timer.start()
            self.isPaused = False

    def setPosition(self, position):
        """Set the position
        """
        self.mediaplayer.set_position(position / 1000.0)

    def cleanup(self):
        self.coms.cleanup()
        self.thread_handler.kill()

    def add_folder_tree(self):
        self.load_project_structure(self.file_viewer)
        self.file_viewer.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.file_viewer.customContextMenuRequested.connect(self.context_menu)
        # FileViewer(self.treeView)

    def load_project_structure(self, tree):
        font = QtGui.QFont()
        font.setPointSize(8)
        tree.setFont(font)
        self.menu_model = QFileSystemModel()
        self.menu_model.setRootPath(os.getcwd())
        # model.setRootPath(QDir)
        tree.setModel(self.menu_model)
        tree.setRootIndex(self.menu_model.index(os.getcwd()))

    def context_menu(self):
        menu = QtWidgets.QMenu()
        open = menu.addAction("Open")
        rename = menu.addAction("Rename")
        dowscale = menu.addAction("Downscale .MP4")
        convert = menu.addAction("Convert to .MP4")
        delete = menu.addAction("Delete")
        open.triggered.connect(self.open_file)
        rename.triggered.connect(self.rename_file)
        dowscale.triggered.connect(self.dowscale_mp4)
        convert.triggered.connect(self.convert2mp4)
        delete.triggered.connect(self.delete_file)
        cursor = QtGui.QCursor()
        menu.exec_(cursor.pos())

    def convert2mp4(self):
        conversion = self.thread_handler.add(Thread(target=self._convert2mp4))

    def _convert2mp4(self):
        file_name = self.get_file_from_menu()
        self.add_to_terminal(f"Converting {file_name}")
        self.check_if_playing(file_name)
        convert2mp4(file_name)
        self.add_to_terminal(f"Finished converting {file_name}")

    def dowscale_mp4(self):
        width, ok = QInputDialog.getText(self.MainWindow, "Get Text",
                                         "Width of video to downscale: ",
                                         QLineEdit.Normal, "")
        if ok and width != "":
            if not (width.isnumeric() and int(width) < 1280):
                self.add_to_terminal("Enter a valid number")
                return
            downscaling = self.thread_handler.add(
                Thread(target=self._downscale_mp4, args=(width, )))

    def _downscale_mp4(self, width):
        file_name = self.get_file_from_menu()
        self.add_to_terminal(f"Downscaling {file_name}")
        if file_name == self.opened_file:
            self.Stop()
            time.sleep(0.5)
        cap = cv2.VideoCapture(file_name)
        fourcc = cv2.VideoWriter_fourcc(*"MP4V")
        ret, img = cap.read()
        width = int(width)
        height = int((9 / 16) * width)
        img = cv2.resize(img, (width, height))
        new_name = file_name.split(".")[0] + "_downscaled" + ".mp4"
        out = cv2.VideoWriter(new_name, fourcc, 24,
                              (img.shape[1], img.shape[0]))
        while True:
            out.write(img)
            ret, img = cap.read()
            if ret:
                img = cv2.resize(img, (width, height))
            else:
                break
        self.add_to_terminal(f"Finished downscaling {file_name}")
        out.release()
        cap.release()

    def rename_file(self):
        file_name = self.get_file_from_menu()
        self.check_if_playing(file_name)
        text, ok = QInputDialog.getText(self.MainWindow, "Get Text",
                                        "Rename to: ", QLineEdit.Normal, "")
        if ok and text != "":
            split = file_name.split('.')
            if len(split) == 0:
                self.signal_terminal.emit("not a file")
            else:
                self.check_if_playing(file_name)
                file_type = split[-1]
                dir = os.path.dirname(file_name)
                new_path = f"{dir}/{text}.{file_type}"
                os.rename(file_name, new_path)

    def open_file(self):
        file_name = self.get_file_from_menu()
        if file_name.split(".")[-1] in ["h264", "mp4"]:
            self.open_video(file_name)
        else:
            os.startfile(file_name)
        self.opened_file = file_name

    def check_if_playing(self, file_name):
        if self.opened_file == file_name:
            self.Stop()
            self.opened_file = None
            time.sleep(0.5)

    def get_file_from_menu(self):
        index = self.file_viewer.currentIndex()
        return self.menu_model.filePath(index)

    def delete_file(self):
        file_name = self.get_file_from_menu()
        self.check_if_playing(file_name)
        os.remove(file_name)
Exemplo n.º 19
0
"""
Test the reading of sensor data
"""

import Communications as com
import time


for i in xrange(2000):
    data = com.request_all()
    print data
    #print data['SONAR_C']
    time.sleep(0.1)