示例#1
0
    def open_routes_file(self, file_name):
        logging.info("Opening routes file: %s" % file_name)

        with open(file_name, newline='') as csvfile:
            reader = csv.DictReader(csvfile)
            # Read all routes info
            for row in reader:
                route = Route(row, self.stops_list)
                self.routes_list.append(route)

        # Create buses for each route
        for route in self.routes_list:
            logging.info("Creating %d buses for route %s" %
                         (route.buses_total, route.name))
            for i in range(route.buses_total):
                bus = Bus(self.bus_count, route, self.stops_list)
                self.bus_count += 1
                bus.start_time = route.time_offset + route.bus_counter * route.frequency
                route.bus_counter += 1
                self.buses_list.append(bus)

        logging.info("Total created buses %d" % len(self.buses_list))

        globalConstants.results['Total_buses'] = len(self.buses_list)
        globalConstants.results['Total_routes'] = len(self.routes_list)
	def test_from_hex(self):
		self.assertRaises(AssertionError, Bus._pick_from_hex, 1, [])
		self.assertRaises(BusException, Bus._pick_from_hex, "", [("x",1)])
		self.assertRaises(BusException, Bus._pick_from_hex, "10", [])

		self.assertEqual(Bus._pick_from_hex("10", [("x", 1)]), {"x":16})
		self.assertEqual(Bus._pick_from_hex("100010", [("x", 1), ("y", 2)]), {"x":16, "y":16})
示例#3
0
 def createCase5(self):
     self.element1=Host(300,200,0,0)
     self.element2=Host(1000,200,0,0)
     self.element3=Router(650,200,0,0)
     self.element4=Host(650,400,0,0)
     self.Bus1=Bus(300,205,1000,205)
     self.Bus2=Bus(660,200,660,400)
示例#4
0
    def __init__(self, devicesService=None):
        self.bus = Bus()
        self.kodiDao = KodiDAO()
        self.convert = Convert()
        #   self.playerMusic = playerMusic()
        self.tools = Tools()
        self.bus.subscribe('vocalOrdre', self.lanceVocalOrdre)
        self.bus.subscribe('loadSeriesDao', self.loadSeriesCallBack)
        self.bus.subscribe('loadSeriesEnCoursDao',
                           self.loadSeriesEnCoursCallBack)
        self.bus.subscribe('loadFilmsDao', self.loadFilmsCallBack)
        self.bus.subscribe('loadMusiquesDao', self.loadMusiquesCallBack)
        self.bus.subscribe('deviceService', self.deviceChange)
        self.bus.subscribe('emplacementService', self.emplacementChange)

        current_dir = os.path.dirname(__file__)
        #  jsonfile = '../../resources/fr/serieMapping.json'
        #  mappingfile = os.path.join(current_dir, jsonfile)
        #  with open(mappingfile) as data_file:
        #      serieMapping = json.load(data_file)

        #  self.listeMotsSerie = self.mappingToWords(serieMapping)

        numeroMapping_path = '../../resources/fr/numeroMapping.json'
        numeroMapping_file = os.path.join(current_dir, numeroMapping_path)
        with open(numeroMapping_file) as data_file:
            numeroMapping = json.load(data_file)

        self.listeMotsNumero = self.mappingToWords(numeroMapping)

        for var in self.VARIABLES:
            v = self.VARIABLES[var]
            if v == "Int":
                self.VARIABLES[var] = numeroMapping
示例#5
0
    def __init__(self):
        self.bus= Bus()
        
        self.isActive = True
        self.bus.subscribe('vocalOrdre', self.lanceVocalOrdre) 

        global queues
        queues = []
        gst_thread = MainPipeline()
        gst_thread.start()
示例#6
0
def test_bus3(dump_vcd, test_verilog):
    model = Bus(3, 16)
    model.vcd_file = dump_vcd
    if test_verilog:
        model = TranslationTool(model)
    run_test_bus(model, [
        [0xdead, 0xbeef, 0xcafe, 0, 0xdead, 0xdead, 0xdead],
        [0xdead, 0xbeef, 0xcafe, 1, 0xbeef, 0xbeef, 0xbeef],
        [0xdead, 0xbeef, 0xcafe, 2, 0xcafe, 0xcafe, 0xcafe],
    ])
示例#7
0
def main():
    global bus, ram, ppi, alu, cu
    bus = Bus()
    ram = RAM(0x0, 64)
    ppi = PPI(0x40)
    bus.AddMemoryPeripheral(ram, 0x0, 0x0+64*1024-1)
    bus.AddIOPeripheral(ppi, 0x40, 0x40+3)
    
    
    alu = ALU()
    cu = CU(alu, bus)
    
    ppi.SetInterruptCallPA(partial(cu.RST, 5.5, ppi))
    ppi.SetInterruptCallPB(partial(cu.RST, 6.5, ppi))
    
    openFile()
    i = 0
    for wd in words:
        ram.Write(0x8000+i, wd)
        i += 1
    
    
    #ram.Write(0x002C, 0x6F)
    #ram.Write(0x002D, 0xC9)
    ram.Write(0x002c, 0xdb)
    ram.Write(0x002d, 0x40)
    ram.Write(0x002e, 0xc9)
    cu.Reset()
    cu.SetPC(0x8000)
    
    thread = Thread(target=execute)
    thread.start()
    
    ppi.a = 0xbb
    while cu.running:
        pass
#        cmd = input("Enter a command: ")
#        if cmd == "quit":
#            cu.running = False
#        elif cmd == "stba":
#            ppi.StrobeA()
#        elif cmd == "stbb":
#            ppi.StrobeB()
#        elif cmd == "show":
#            print("")
#            alu.Show()
#            #print("\n")
#            #ram.Show()
#            print("\n")
#            ppi.Show()

    ram.ShowRange(parser.labels["TABLE"], parser.labels["TABLE"]+0x63)
    alu.Show()
示例#8
0
def addBus(bus):
    print("Set the number of the bus:")
    num = input()
    while bus_numberExist(
            bus, num):  # if the bus' number is already in use, input again
        num = input()

    print("The departure of the bus: ")
    depa = input()
    while not station_nameExist(
            destinations, depa):  # the departure must be a station registered
        # if not, input again
        print("Station doesn't exist! Input again, please.")
        depa = input()

    print("The destination of the bus:")
    dest = input()
    while depa == dest or not station_nameExist(
            destinations,
            dest):  # the destination must be a station registered
        # if not, input again. And it should not be the same
        # station as its departure.
        if depa == dest:
            print(
                "Destination is the same with departure! Input again, please.")
        if not station_nameExist(destinations, dest):
            print("Station doesn't exist! Input again, please.")
        dest = input()
    tmp = Bus(num, depa, dest)
    bus.append(tmp)
    print("Success!!")
示例#9
0
文件: BaseCPU.py 项目: liangwang/m5
 def addTwoLevelCacheHierarchy(self, ic, dc, l2c):
     self.addPrivateSplitL1Caches(ic, dc)
     self.toL2Bus = Bus()
     self.connectMemPorts(self.toL2Bus)
     self.l2cache = l2c
     self.l2cache.cpu_side = self.toL2Bus.port
     self._mem_ports = ['l2cache.mem_side']
示例#10
0
    def __init__(self):
        self.bus = Bus()

        self.bus.subscribe('vocalOrdre', self.lanceVocalOrdre)
        # Liste des musiques venant de Kodi
        self.bus.subscribe('loadMusiquesDao', self.loadMusiques)

        current_dir = os.path.dirname(__file__)
        script = '../tmp'
        directory_tmp = os.path.join(current_dir, script)
        if not os.path.exists(directory_tmp):
            os.makedirs(directory_tmp)
        script = '../tmp/music'
        directory_tmp = os.path.join(current_dir, script)
        if not os.path.exists(directory_tmp):
            os.makedirs(directory_tmp)
示例#11
0
    def __init__(self, inputData):
        self.inputData = inputData

        nBuses = self.inputData.nBuses
        nDrivers = self.inputData.nDrivers
        nServices = self.inputData.nServices

        start = self.inputData.start
        duration = self.inputData.duration
        kms = self.inputData.kms
        passengers = self.inputData.passengers

        capacity = self.inputData.capacity
        cost_km = self.inputData.cost_km
        cost_min = self.inputData.cost_min

        maxWorkingTime = self.inputData.maxWorkingTime

        self.maxBuses = self.inputData.maxBuses
        self.BM = self.inputData.BM
        self.CBM = self.inputData.CBM
        self.CEM = self.inputData.CEM

        self.drivers = []
        self.buses = []
        self.services = []
        self.overlapping = [[0 for x in range(nServices)]
                            for y in range(nServices)]

        for sId in xrange(
                0,
                nServices):  #hopefully really 0..(nServices-1) --> Check that
            service = Service(sId, start[sId], duration[sId], kms[sId],
                              passengers[sId])
            self.services.append(service)

        for dId in xrange(0, nDrivers):
            driver = Driver(dId, maxWorkingTime[dId])
            self.drivers.append(driver)

        for bId in xrange(0, nBuses):
            bus = Bus(bId, capacity[bId], cost_km[bId], cost_min[bId])
            self.buses.append(bus)

        for s1 in xrange(0, nServices):
            for s2 in xrange(0, nServices):
                startS1 = self.services[s1].getStart()
                endS1 = startS1 + self.services[s1].getDuration()

                startS2 = self.services[s2].getStart()
                endS2 = startS2 + self.services[s2].getDuration()

                if not (endS1 < startS2 or startS1 > endS2):
                    self.overlapping[s1][s2] = 1
                    self.overlapping[s2][s1] = 1
                else:
                    self.overlapping[s1][s2] = 0
                    self.overlapping[s2][s1] = 0
示例#12
0
def getAndroclickObject(objectType):
    if objectType == BUS:
        return Bus()
    elif objectType == STOP:
        return Stop()
    elif objectType == RESPONSE:
        return Response()
    else:
        print("Invalid object type")
示例#13
0
    def createBuses(self):

        total_buses = int(
            input("Escribir el numero de buses que tiene la organización: "))
        total_places = int(
            input("Escribir el numero de plazas totales del bus: "))

        for i in range(total_buses):
            self.busesList.append(Bus(i, total_places))
示例#14
0
def main():
    clock = threading.Event()
    memory = Memory()
    bus = Bus(memory)
    cores = [Core(1, bus), Core(2, bus), Core(3, bus), Core(4, bus)]
    bus.set_cores(cores)

    core_threads = []
    for core in cores:
        thread = threading.Thread(target=core.processor.run, args=(clock, ))
        thread.start()
        core_threads.append(thread)
    mem_thread = threading.Thread(target=memory.run, args=(clock, ))
    mem_thread.start()

    os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
    QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    window = Window(clock, cores, memory)
    sys.exit(app.exec_())
示例#15
0
 def get_vehicle(self, type):
   if type == VehicleType.BUS:
     return Bus()
   elif type == VehicleType.CAR:
     return Car()
   elif type == VehicleType.MOTORCYCLE:
     return Motorcycle()
   elif type == VehicleType.VAN:
     return Van()
   else:
     return None
示例#16
0
    def runner(self, sim_time):

        # Check for buses creation
        for route in self.routes_list:
            # Check if we need to create a new bus
            if (route.last_bus_time + route.frequency) <= (sim_time -
                                                           route.time_offset):
                bus = Bus(self.bus_count, route)
                self.bus_count += 1
                route.last_bus_time = sim_time - route.time_offset
                self.buses_list.append(bus)
                logging.info("Bus %d created with route %s", bus.number,
                             bus.route.name)

        # Run the bus runner for each bus
        for bus in self.buses_list:
            bus.runner(self.stops_list, sim_time)
            if bus.is_finished():
                self.finished_buses_list.append(bus)
                self.buses_list.remove(bus)
示例#17
0
def funcBuses(buses):
    print("\t\nWelcome to the section Buses!\nChoose the option:\n1.Display all buses\n"
          "2.Display buses according to the specified filed\n3.Add the bus\n4.Edit a bus by ID\n"
          "5.Delete the bus according to the specified filed\n6.Go back\n0.Exit")
    while (True):
        choose = input('Your choice: ')
        if (choose == "1"):
            print("\n***Display all buses***")
            print(buses)
            if (input("Enter 1 to continue. Enter any other value to exit: ") == '1'):
                funcBuses(buses)
            else:
                sys.exit()

        elif (choose == "2"):
            funcstrBusParameter(buses)

        elif (choose == "3"):
            busID = buses.lastID()
            model = input("Model = ")
            driver = input("Driver = ")
            while (True):
                numberOfSeats = input("Number of seats = ")
                if (isint(numberOfSeats)):
                    numberOfSeats = int(numberOfSeats)
                    break
                else:
                    print("Number of seats can be only a number.")
                    if (input("Enter 1 to try again. Enter any other value to go back: ") == '1'):
                        continue
                    else:
                        funcBuses(buses)
            buses.add(Bus(busID + 1, model, driver, numberOfSeats))
            print("You add the bus.")
            if (input("Enter 1 to continue. Enter any other value to exit: ") == '1'):
                funcBuses(buses)
            else:
                sys.exit()

        elif (choose == "4"):
            funcEditBus(buses)

        elif (choose == "5"):
            funcDeleteBus(buses, plans)

        elif (choose == "6"):
            mainMenu(buses, routes, plans)

        elif (choose == "0"):
            sys.exit()

        else:
            print("You input wrong symbol! You can input only 0,1,2,3,4,5,6. Try again.")
示例#18
0
    def add_to_inventory(self, type, name, rank, kms_travelled, lat, lng):
        #v = Vehicle(type, name, rank, kms_travelled, lat, lng)
        if type == "Car":
            v = Car(name, rank, kms_travelled, lat, lng)
        elif type == "Bike":
            v = Bike(name, rank, kms_travelled, lat, lng)
        elif type == "Bus":
            v = Bus(name, rank, kms_travelled, lat, lng)
        else:
            raise Exception("Invalid vehicle type")

        self.inventory[v.name] = v
示例#19
0
    def __init__(self, inputData):
        self.inputData = inputData

        nServices = inputData.numServices
        nBuses = inputData.numBuses
        nDrivers = inputData.numDrivers
        self.maxBuses = inputData.maxBuses

        self.buses = {}
        for busId in range(0, nBuses):
            # Assuming that each element of inputData.buses is a string,
            # remove initial and trailing "<...>", then split on ","
            busData = inputData.buses[busId].strip('<>').split(',')
            # Convert to numeral values
            for i in range(0, len(busData)):
                try:
                    busData[i] = int(busData[i].strip())
                except ValueError:
                    busData[i] = float(busData[i].strip())
            # Create element
            bus = Bus(busId, busData[0], busData[1], busData[2])
            self.buses[bus.id] = bus

        self.drivers = {}
        for driverId in range(0, nDrivers):
            # Assuming that each element of inputData.drivers is a string,
            # remove initial and trailing "<...>", then split on ","
            driverData = inputData.drivers[driverId].strip('<>').split(',')
            # Convert to numeral values
            for i in range(0, len(driverData)):
                try:
                    driverData[i] = int(driverData[i].strip())
                except ValueError:
                    driverData[i] = float(driverData[i].strip())
            # Create element
            driver = Driver(driverId, driverData[0], driverData[1],
                            driverData[2], driverData[3])
            self.drivers[driver.id] = driver

        self.services = {}
        for serviceId in range(0, nServices):
            # Assuming that each element of inputData.services is a string,
            # remove initial and trailing "<...>", then split on ","
            serviceData = inputData.services[serviceId].strip('<>').split(',')
            # Convert to numeral values
            for i in range(0, len(serviceData)):
                serviceData[i] = int(serviceData[i].strip())
            service = Service(serviceId, serviceData[0], serviceData[1],
                              serviceData[2], serviceData[3], self.services)
            self.services[service.id] = service
示例#20
0
def read_from_file(destinations, bus, person):
    '''
    read all the information from files
    :param destinations:
    :param bus:
    :param person:
    :return:
    '''
    scriptpath = os.path.dirname(__file__)
    filename = os.path.join(scriptpath, 'destination.txt')
    f = open(filename)
    lines = [line.rstrip('\n') for line in f]
    for item in lines:
        des = Station(item)
        destinations.append(des)
    del destinations[0]
    f.close()

    scriptpath = os.path.dirname(__file__)
    filename = os.path.join(scriptpath, 'bus.txt')
    f = open(filename)
    lines = [line.rstrip('\n') for line in f]
    for item in lines:
        item = item.split('\t')
        pos = len(item) - 1
        tmp = Bus(item[0], item[2], item[4], item[pos - 2], item[pos])
        bus.append(tmp)
    del bus[0]
    f.close()

    scriptpath = os.path.dirname(__file__)
    filename = os.path.join(scriptpath, 'person.txt')
    f = open(filename)
    lines = [line.rstrip('\n') for line in f]
    for item in lines:
        item = item.split('\t')
        end = len(item) - 1
        status = False
        if item[end - 2] == 'Onboard':
            status = True
        num = item[end]
        if num == 'None':
            num = None
        else:
            num = str(num)
        tmp = Person(item[0], item[1], item[3], status, num)
        person.append(tmp)
    del person[0]
    f.close()
示例#21
0
def split_bus(powernet, sub, splitting_nodes):
    """Create a new Power_Network with a split substation.

    Inputs:
    powernet (Power_Network) - The original power network.
    sub (Ring_Substation) - The substation that will split.
    splitting_nodes (List of ints) - The substation nodes that will split from
       the substation.

    Output:
    Power_Network. The new power network that results from the substation 
    splitting.
    """
    new_buses = {bus.ID: bus.copy() for bus in powernet.buses}
    newbusID = max([bus.ID for bus in powernet.buses]) + 1
    newbusind = len(powernet.buses)
    new_bus = Bus(newbusind, newbusID, voltage=sub.voltage)
    new_buses[newbusID] = new_bus
    old_bus = new_buses[sub.ID]
    for node in splitting_nodes:
        new_bus.load += sub.nodes[node].load
        old_bus.load -= sub.nodes[node].load

        new_bus.generation += sub.nodes[node].generation
        old_bus.generation -= sub.nodes[node].generation

        new_bus.shunt_adm += sub.nodes[node].shunt_adm
        old_bus.shunt_adm -= sub.nodes[node].shunt_adm

    splitting_branch_IDs = [
        sub.branchID_at_node(sn) for sn in splitting_nodes
        if sub.branchID_at_node(sn) is not None
    ]
    new_branches = {
        branch.ID: branch.copy()
        for branch in powernet.branches.values()
    }
    for branch_ID in splitting_branch_IDs:
        branch = new_branches[branch_ID]
        assert len(branch.buses) == 2
        if branch.buses[0].ID == old_bus.ID:
            branch.buses = (new_bus, branch.buses[1])
        elif branch.buses[1].ID == old_bus.ID:
            branch.buses = (branch.buses[0], new_bus)
        else:
            assert False

    return PowerNetwork(new_buses, new_branches)
示例#22
0
 def getAllBuses(cls):
     try:
         with CursorPool() as cursor:
             buses:list = []
             cursor.execute(cls._SELECT)
             registers:tuple = cursor.fetchall()
             for register in registers:
                 bus:Bus = Bus(
                     bus_plate=register[0],
                     capacity=register[1],
                     terminal_id=register[2]
                 )
                 buses.append(bus)
                 log.debug(bus)
             return buses              
     except Exception as e:
         log.error(f"Error happened while getting all buses: {e}")
示例#23
0
    def populate_buses(self, departures):
        for bus_route_name, bus_info in departures.items():
            for bus in bus_info:
                est_date = bus['expected_departure_date']
                est_time = bus['best_departure_estimate']
                aim_time = bus['aimed_departure_time']

                if est_date is None:
                    est_date = bus['date']
                if est_time is None:
                    est_time = bus['expected_departure_estimate']
                departure_time = self.create_datetime_if_valid(est_date, est_time)
                aim_time = self.create_datetime_if_valid(est_date, aim_time)
                
                self.buses.append(Bus(bus['line'], aim_time, departure_time))
        self.sort_buses()
        del self.buses[5:len(self.buses)]
示例#24
0
def mainMenu(buses, routes, plans):
    chooseFlag = False
    print("\t\nWelcome to the menu!\nChoose the section:\n1.Buses\n2.Routes\n3.Plans\n"
          "4.Save data to the file\n5.Load data from the file\n0.Exit")
    while (chooseFlag == False):
        choose = input('Your choice: ')
        if (choose == "1"):
            chooseFlag = True
            funcBuses(buses)
        elif (choose == "2"):
            chooseFlag = True
            funcRoutes(routes)
        elif (choose == "3"):
            chooseFlag = True
            funcPlans(plans)
        elif (choose == "4"):
            with open('Buses.txt', 'wb') as f:
                pickle.dump(buses, f)
            with open('Routes.txt', 'wb') as f:
                pickle.dump(routes, f)
            with open('Plans.txt', 'wb') as f:
                pickle.dump(plans, f)
            print("Successfully saved!")
        elif (choose == "5"):
            try:
                with open('Buses.txt', 'rb') as file:
                    busFile = pickle.load(file)
                with open('Routes.txt', 'rb') as file:
                    routeFile = pickle.load(file)
                with open('Plans.txt', 'rb') as file:
                    planFile = pickle.load(file)
                for bus in busFile.buses:
                    buses.add(Bus(bus.busID, bus.model, bus.driver, bus.numberOfSeats))
                for route in routeFile.routes:
                    routes.add(Route(route.routeID, route.wherefrom, route.where, route.distance, route.time))
                for plan in planFile.plans:
                    plans.add(Plan(plan.busID, plan.routeID, plan.dateOfLeaving))
                print("Successfully load!")
            except:
                print("One of the files is emply")
        elif (choose == "0"):
            chooseFlag = True
            sys.exit()
        else:
            print("You input wrong symbol! You can input only 0,1,2,3,4,5. Try again.")
示例#25
0
 def _multi_bus(self, bus):
     bus_id = bus.get("VehicleId")
     name = bus.get("name")
     lat = bus.get("Latitude")
     lon = bus.get("Longitude")
     route = bus.get("RouteId")
     last_stop = bus.get("LastStop")
     return Bus(
         bus_id=bus_id,
         short_name=name,
         last_stop=last_stop,
         latitude=lat,
         longitude=lon,
         route_id=route,
         do_projection=self.projection,
         service="LANTA",
         cache={},
     ).to_dict()
示例#26
0
    def __init__(self, inputData):
        self.inputData = inputData

        nServices = self.inputData.nServices
        nBuses = self.inputData.nBuses
        nDrivers = self.inputData.nDrivers

        time_start = self.inputData.time_start
        duration_min = self.inputData.duration_min
        duration_km = self.inputData.duration_km
        nPassengers = self.inputData.nPassengers

        cap_b = self.inputData.cap_b
        euros_min_b = self.inputData.euros_min_b
        euros_km_b = self.inputData.euros_km_b
        max_d = self.inputData.max_d

        maxBuses = self.inputData.maxBuses
        CBM = self.inputData.CBM
        CEM = self.inputData.CEM
        BM = self.inputData.BM

        self.maxBuses = maxBuses
        self.CBM = CBM
        self.CEM = CEM
        self.BM = BM

        self.services = []

        for sId in xrange(0, nServices):  # sId = 0..(nServices-1)
            service = Service(sId, nPassengers[sId], time_start[sId], duration_min[sId], duration_km[sId])
            self.services.append(service)

        self.buses = []
        for bId in xrange(0, nBuses):  # bId = 0..(nBuses-1)
            bus = Bus(bId, cap_b[bId], euros_min_b[bId], euros_km_b[bId])
            self.buses.append(bus)

        self.drivers = []
        for dId in xrange(0, nDrivers):  # dId = 0..(nDrivers-1)
            driver = Driver(dId, max_d[dId])
            self.drivers.append(driver)
示例#27
0
 def _multi_bus(self, bus):
     bus_id = bus.get("id")
     name = bus.get("name")
     lat = bus.get("lat")
     lon = bus.get("lon")
     route = bus.get("route")
     last_stop = bus.get("lastStop")
     return Bus(
         bus_id=bus_id,
         short_name=name,
         last_stop=last_stop,
         latitude=lat,
         longitude=lon,
         route_id=route,
         do_projection=self.projection,
         do_next_stop=self.next_stop,
         service="Lehigh",
         stops=self.clean_stops,
         routes=self.routes_from_java_script,
         cache=self.cache,
     ).to_dict()
示例#28
0
def crearBus():
    buscreado = False
    nombre = input("Introducir nombre del bus: ")
    while True:
        try:
            numero_plazas = int(input("Introducir numeros de plazas: "))
            break
        except ValueError:
            print("El numero de plazas debe de ser un digito")

    try:
        bus = Bus(nombre, numero_plazas)
        buscreado = True
        if buscreado == True:
            if adminbus.insertBus(bus) > 0:
                print("Bus creado correctamente")
            else:
                print("Error, el bus no se ha creado correctamente")
        else:
            print("Error, el bus no se ha creado")

    except Exception as ex:
        print(ex)
	def test_to_hex(self):
		self.assertEqual(Bus._to_hex(16, 1), "10")
		self.assertEqual(Bus._to_hex(16, 2), "0010")
		self.assertRaises(AssertionError, Bus._to_hex, 500, 1)
		self.assertRaises(AssertionError, Bus._to_hex, "a", 1)
	def test_module_init_1(self):
		serial = FakeSerial()
		bus = Bus(serial)
		bus.init_module("a", True, "1000A", 1)
		self.assertEqual(serial.sendbuf[:14], "ab013130303041")
		self.assertEqual(len(serial.sendbuf), 17)
示例#31
0
class Kodi():

    VARIABLES = {
        '@name_serie': {},
        '@name_film': {},
        '@name_music': {},
        '@name_playlist': {},
        '@episode': 'Int',
        '@saison': 'Int',
        '@episod_id': 'Int',
        '@film_id': 'Int'
    }

    ORDRES = {
        "liste_film": {
            "action": ["display", "show"],
            "message_fr": ["liste film"],
            "input": ["récent", "ordre alpha", "note", "date ajout"]
        },
        "liste_serie": {
            "action": ["display", "show"],
            "message_fr": ["liste série"],
            "input": ["récent", "ordre alpha", "note", "date ajout"]
        },
        "liste_music": {
            "action": ["display", "show"],
            "message_fr": ["liste musique"],
            "input": ["récent", "ordre alpha", "note", "date ajout"]
        },
        "lance_episode": {
            "action": ["launch", "put"],
            "message_fr": ["épisode"],
            "input": [
                "suivant de @name_serie",
                "@episode de la saison @saison de @name_serie",
                "de @name_serie saison @saison épisode @episode",
                "de @name_serie numéro @episod_id",
                "numéro @episod_id de @name_serie"
            ]
        },
        "lance_episode_2": {
            "action": ["resume"],
            "message_fr":
            ["la série", "épisode", "la suite", "la suite de la série"],
            "input": ["de @name_serie"]
        },
        "lance_film": {
            "action": ["launch", "put"],
            "message_fr": ["film"],
            "input": ["@name_film"]
        },
        "resume_film": {
            "action": ["resume"],
            "message_fr": ["film"],
            "input": ["@name_film"],
        },
        "lance_music": {
            "action": ["launch", "put"],
            "message_fr": ["musique"],
            "input": ["@name_music", "@name_playlist", "suivante"],
        },
        "lecture": {
            "action": ["put"],
            "message_fr": ["lecture"],
        },
        "pause": {
            "action": ["put"],
            "message_fr": ["pause"],
        },
        "stop": {
            "action": ["stop"],
            "message_fr":
            ["musique", "vidéo", "épisode", "film", "stop", "arrête"],
        },
        "baisser_son": {
            "action": ["put_down"],
            "message_fr": ["le son", "le volume"],
            "repete": ["encore", "plus"],
        },
        "monter_son": {
            "action": ["turn_up"],
            "message_fr": ["le son", "le volume"],
            "repete": ["encore", "plus"],
        },
        "mute": {
            "action": ["cut", "stop"],
            "message_fr": ["le son", "le volume"],
        },
        "scan": {
            "action": ["put", "launch"],
            "message_fr": ["scan"],
        }
    }

    devices = []
    emplacements = []
    satelitesConnected = {}

    listeMotsSerie = []
    listeMotsNumero = []

    def __init__(self, devicesService=None):
        self.bus = Bus()
        self.kodiDao = KodiDAO()
        self.convert = Convert()
        #   self.playerMusic = playerMusic()
        self.tools = Tools()
        self.bus.subscribe('vocalOrdre', self.lanceVocalOrdre)
        self.bus.subscribe('loadSeriesDao', self.loadSeriesCallBack)
        self.bus.subscribe('loadSeriesEnCoursDao',
                           self.loadSeriesEnCoursCallBack)
        self.bus.subscribe('loadFilmsDao', self.loadFilmsCallBack)
        self.bus.subscribe('loadMusiquesDao', self.loadMusiquesCallBack)
        self.bus.subscribe('deviceService', self.deviceChange)
        self.bus.subscribe('emplacementService', self.emplacementChange)

        current_dir = os.path.dirname(__file__)
        #  jsonfile = '../../resources/fr/serieMapping.json'
        #  mappingfile = os.path.join(current_dir, jsonfile)
        #  with open(mappingfile) as data_file:
        #      serieMapping = json.load(data_file)

        #  self.listeMotsSerie = self.mappingToWords(serieMapping)

        numeroMapping_path = '../../resources/fr/numeroMapping.json'
        numeroMapping_file = os.path.join(current_dir, numeroMapping_path)
        with open(numeroMapping_file) as data_file:
            numeroMapping = json.load(data_file)

        self.listeMotsNumero = self.mappingToWords(numeroMapping)

        for var in self.VARIABLES:
            v = self.VARIABLES[var]
            if v == "Int":
                self.VARIABLES[var] = numeroMapping

    #     if var == "@name_serie" :
    #         self.VARIABLES[var] = serieMapping

    def mappingToWords(self, mapping):
        listOfWord = []
        for item in mapping:
            l_m = mapping[item]
            for m in l_m:
                m_clean = self.tools.cleanString(m)
                l_w = m_clean.split(" ")
                for w in l_w:
                    if w not in listOfWord:
                        listOfWord.append(w)
        return listOfWord

    def listToWords(self, list_):
        listOfWord = []
        for item in list_:
            m_clean = self.tools.cleanString(item)
            l_w = m_clean.split(" ")
            for w in l_w:
                if w not in listOfWord:
                    listOfWord.append(w)
        return listOfWord

    def synchronize(self, data):
        self.bus.publish('kodiService', data)

    def lanceVocalOrdre(self, bus, key, obj):
        groupe = obj['groupe']
        if groupe != 'kodi':
            return

        ordre_name = obj['ordre']
        origineIp = obj["origine"]
        #recognised = obj["recognised"]
        input_ = obj["input"]

        #ordre = self.ORDRES[ordre_name]
        #        function = ordre["function"]

        try:
            getattr(self, ordre_name)(input_, origineIp)
        except Exception as e:
            print("Kodi => lanceVocalOrdre : " + e.__str__())

    def findKodiBySecteur(self, origineIp):
        for secteur in self.emplacements:
            for device in secteur.devices:
                if str(device.ip) == origineIp:
                    self.secteurTouche = secteur

        if hasattr(self, 'secteurTouche'):
            for device in self.secteurTouche.devices:
                if device.hasKodi == True:
                    self.kodiDao.currentKodiIp = device.ip
            del self.secteurTouche

    def liste_film(self, input_, ipDestination):
        self.loadFilms()

    def liste_serie(self, input_, ipDestination):
        self.loadSeries()

    def liste_music(self, input_, ipDestination):
        self.loadMusiques()

    def lance_episode_2(self, input_, ipDestination):
        self.lance_episode(input_, ipDestination, True)

    def lance_episode(self, input_, ipDestination, suite=False):
        """
        1/ Liste des séries   : self.kodiDao.listSeriesEnCours
        2/ Input              : input_   
        """

        self.findKodiBySecteur(ipDestination)

        name_var = None
        episode_num = 0
        saison_num = 0

        for i in input_:
            print(i)
            if "suivant" in i:
                suite = True
            if "@name_serie" in i:
                if len(input_[i]) > 1:
                    name_var = input_[i][1]
                if len(input_[i]) == 1:
                    name_var = input_[i][0]
            if "@umeric" in i:
                if "épisode" in i:
                    if len(input_[i]) > 1:
                        episode_num = input_[i][1]
                    if len(input_[i]) == 1:
                        episode_num = input_[i][0]
                if "saison" in i:
                    if len(input_[i]) > 1:
                        saison_num = input_[i][1]
                    if len(input_[i]) == 1:
                        saison_num = input_[i][0]
            if "premier" in i:
                saison_num = 1
                episode_num = 1
            if "dernier" in i:
                saison_num = "last"
                episode_num = "last"

        numeros = []
        if name_var:
            if suite:
                for serieEnCours in self.kodiDao.listSeriesEnCours:
                    if serieEnCours.serieTitle == name_var.key_ordre:
                        numeros.append(serieEnCours.nextEpisodeid)
            else:
                saison = 0
                episode = None
                serie = None
                if name_var.key_ordre in self.kodiDao.listSeries:
                    serie = self.kodiDao.listSeries[name_var.key_ordre]
                if serie:
                    if saison_num == "last":
                        saison = serie[-1]
                    elif saison_num > 0:
                        saison = serie[saison_num]
                    else:
                        saison = serie[1]

                    if saison > 0:
                        if episode_num == "last":
                            episode = saison[-1]
                        elif episode_num > 0:
                            episode = saison[episode_num]
                        else:
                            episode = saison[1]
                    if episode:
                        numeros.append(episode.id)

        if len(numeros) > 0:
            counter = collections.Counter(numeros)
            listePossible = counter.most_common()
            if len(listePossible) > 0:
                episod_id, nombre = listePossible[0]
                if episod_id > -1:
                    self.openSerie(episod_id)

    def lance_film(self, input_, ipDestination):

        print(input_)
        self.findKodiBySecteur(ipDestination)

        name_var = None

        for i in input_:
            print(i)
            if "@name_film" in i:
                if len(input_[i]) > 1:
                    name_var = input_[i][1]
                if len(input_[i]) == 1:
                    name_var = input_[i][0]

        numeros = []
        if name_var:
            for film in self.kodiDao.listFilms:
                if film.title == name_var.key_ordre:
                    numeros.append(film.id)

        if len(numeros) > 0:
            counter = collections.Counter(numeros)
            listePossible = counter.most_common()
            if len(listePossible) > 0:
                movieid, nombre = listePossible[0]
                if movieid > -1:
                    self.openFilm(movieid)

        #movieid = -1
        #movieid = self.convert.convert(arguments[0])


#        numeros = self.convert.convertListChaine(input_, self.kodiDao.listFilms)
#      print 'lance_film : ' + str(movieid)
#       print ('numeros : ' + str(numeros))
#        counter = collections.Counter(numeros)
#        print ('numeros : ' + str(counter.most_common(4)))
#       listePossible = counter.most_common(4)
#       movieid, nombre = listePossible[0]

#def lance_episode(self, input_, ipDestination):
#episod_id = -1
#    print(input_)
#    numeros = self.convert.convertListChaine(input_, self.kodiDao.listSeries, self.kodiDao.listSeriesEnCours)
#            print 'lance_episode : ' + str(episod_id)
#    print ('numeros : ' + str(numeros))
#    counter = collections.Counter(numeros)
#    print ('numeros : ' + str(counter.most_common(4)))
#    listePossible = counter.most_common(4)
#    episod_id, nombre = listePossible[0]
#    if episod_id > -1 :
#        self.openSerie(episod_id)

#def launchMusic(self, input_, ipDestination):
#    self.playerMusic.manageMusic(ipDestination, "lance_music" , "bureau")

    def pause(self, input_, ipDestination):
        #pass
        self.playPause(False)
        #self.playerMusic.manageMusic(ipDestination, "pause")

    def lecture(self, input_, ipDestination):
        #pass
        self.playPause(True)
        #self.playerMusic.manageMusic(ipDestination, "lecture")

    def stop(self, input_, ipDestination):
        #pass
        self.stopFilm()
        #self.playerMusic.manageMusic(ipDestination, "stop")

    def launchMute(self, input_, ipDestination):
        self.xbmc.Application.SetMute({"mute": True})

    def baisser_son(self, input_, ipDestination):
        self.xbmc = self.kodiDao.connectFirstKodi()
        volume = self.xbmc.Application.GetProperties(
            {"properties": ["volume"]})
        n_v = volume["result"]["volume"] - 2
        volume = self.xbmc.Application.SetVolume({"volume": n_v})

    def scan(self, input_, ipDestination):
        self.scanMoviesDatabase()

    def deviceChange(self, bus, key, obj):
        self.devices = obj["devices"]
        self.detectKodi()
        if len(self.kodiDao.listKodis) > 0 and not hasattr(self, 'WSthread'):
            self.WSthread = []
            for kodi in self.kodiDao.listKodis:
                t = WSThread(self, kodi.ip)
                self.WSthread.append(t)
                t.start()
            self.loadMusiques()
            self.loadFilms()
            self.loadSeries()

    def emplacementChange(self, bus, key, obj):
        if hash(frozenset(self.emplacements)) != hash(
                frozenset(obj["emplacements"])):
            self.emplacements = obj["emplacements"]
            emplacement_name = []
            emplacement_mapping = {}
            for e in self.emplacements:
                name_clean = self.tools.cleanString(e.name)
                emplacement_name.append(name_clean)
                if e.name not in emplacement_mapping:
                    emplacement_mapping[e.name] = []
                if name_clean not in emplacement_mapping[e.name]:
                    emplacement_mapping[e.name].append(name_clean)

            self.VARIABLES["@name_playlist"] = emplacement_mapping
            self.bus.publish(
                'loadVocalVariable', {
                    'module': 'kodi',
                    'key': '@name_playlist',
                    'values': emplacement_name
                })

    def detectKodi(self, args=None):
        listKodis = []
        if len(self.devices) > 0:
            for device in self.devices:
                if self.deviceDetectKodi(device.ip):
                    device.setHasKodi(True)
                    listKodis.append(device)
                    print('Kodi detect  : ' + device.ip)
            obj = {'key': "kodiDetected", 'devices': listKodis}
            self.synchronize(obj)

            self.kodiDao.listKodis = listKodis
        return self.kodiDao.listKodis

    def deviceDetectKodi(self, ip):
        params = {}
        params['jsonrpc'] = '2.0'
        params['id'] = 0
        params['method'] = 'JSONRPC.Ping'
        params['params'] = ''
        data = json.dumps(params).encode('utf-8')
        header = {
            'Content-Type': 'application/json',
            'User-Agent': 'python-xbmc'
        }
        url = "http://" + ip + ":" + str(conf.PORT_HTTP_KODI) + "/jsonrpc"
        isKodi = True
        try:
            req = urllib2.Request(url, data, header)
            urllib2.urlopen(req, timeout=0.3)
            # xbmc = xbmcjson.XBMC(url)
            # xbmc.JSONRPC.Ping()
        except:
            isKodi = False
        return isKodi

    def scanMoviesDatabase(self, args=None):
        self.xbmc = self.kodiDao.connectFirstKodi()
        self.xbmc.VideoLibrary.Scan()

    def scanMusiquesDatabase(self, args=None):
        self.xbmc = self.kodiDao.connectFirstKodi()
        self.xbmc.AudioLibrary.Scan()

    def showNotification(self, args):
        self.xbmc = self.kodiDao.connectFirstKodi()
        self.xbmc.GUI.ShowNotification({
            "title":
            "Topi de amor",
            "message":
            "Bonjour je m'appelle Noni y te quiero"
        })

    def loadFilms(self, forcage=False):
        if len(self.kodiDao.listFilms) == 0 or forcage:
            self.kodiDao.loadFilms()
        obj = {'key': "loadFilms", 'films': self.kodiDao.listFilms}
        self.synchronize(obj)
        return self.kodiDao.listFilms

    def loadFilmsCallBack(self, bus, key, films):
        obj = {'key': "loadFilms", 'films': films}
        self.synchronize(obj)
        films_name = []
        for f in films:
            films_name.append(f.title)
        self.bus.publish('loadVocalVariable', {
            'module': 'kodi',
            'key': '@name_film',
            'values': films_name
        })

    def loadMusiques(self, forcage=False):
        self.kodiDao.loadMusiques()
        obj = {'key': "loadMusiques", 'musiques': self.kodiDao.listMusiques}
        self.synchronize(obj)
        return self.kodiDao.listMusiques

    def loadMusiquesCallBack(self, bus, key, musiques):
        obj = {'key': "loadMusiques", 'musiques': self.kodiDao.listMusiques}
        self.synchronize(obj)
        listArtiste = ["pink floyd"]
        self.bus.publish('loadVocalVariable', {
            'module': 'kodi',
            'key': '@name_music',
            'values': listArtiste
        })

    def loadSeries(self, forcage=False):
        if len(self.kodiDao.listSeries) == 0 or forcage:
            self.kodiDao.loadSeries()
        self.synchronize({
            'key': "loadSeries",
            'series': self.kodiDao.listSeries
        })
        self.synchronize({
            'key': "loadSeriesEnCours",
            'series': self.kodiDao.listSeriesEnCours
        })
        return self.kodiDao.listSeries

    def loadSeriesTab(self, forcage=False):
        if len(self.kodiDao.listSeries) == 0 or forcage:
            self.kodiDao.loadSeries()
        listSeriesTab = []
        for serie in self.kodiDao.listSeries:
            listSeriesTab.append(Serie(serie))
        return listSeriesTab

    def loadSeriesCallBack(self, bus, key, series):
        self.kodiDao.listSeries = series
        self.synchronize({'key': "loadSeries", 'series': series})

        #serieMapping = self.VARIABLES["@name_serie"]
        #for s in self.kodiDao.listSeries:
        #    s_clean = self.tools.cleanString(s)
        #    if s not in serieMapping :
        #        serieMapping[s] = []
        #    if s_clean not in serieMapping[s] :
        #        serieMapping[s].append(s_clean)

        ##self.listeMotsSerie = self.mappingToWords(serieMapping)
        #self.VARIABLES["@name_serie"] = serieMapping

        #vocal_serie = []
        #for item in serieMapping :
        #    l = serieMapping[item]
        #    for m in l :
        #        if m not in vocal_serie :
        #            vocal_serie.append(m)

        #self.bus.publish('loadVocalVariable' , {'module': 'kodi', 'key':'@name_serie' , 'values' : vocal_serie})

    def loadSeriesEnCoursCallBack(self, bus, key, seriesEnCours):
        self.kodiDao.listSeriesEnCours = seriesEnCours
        self.synchronize({
            'key': "loadSeriesEnCours",
            'series': self.kodiDao.listSeriesEnCours
        })

    def kodiCommand(self, kodiArgs):

        command = kodiArgs[0].ordre
        if hasattr(kodiArgs[0], 'arguments'):
            args = kodiArgs[0].arguments

        self.xbmc = self.kodiDao.connectFirstKodi()

        player = {}

        activePlayer = self.xbmc.Player.GetActivePlayers()
        print('Active player : ' + str(activePlayer))
        if command == 'PlayPause':
            player = self.playPause(args)

        if command == 'openFilm':
            player = self.openFilm(args)

        if command == 'openSerie':
            player = self.openSerie(args)

        if command == 'Stop':
            player = self.stopFilm()

        if command == 'activeItem':
            try:
                player = self.activeItem()
            except:
                pass
        return player

    def openFilm(self, args):
        self.xbmc = self.kodiDao.connectFirstKodi()
        self.xbmc.Player.Open({"item": {"movieid": int(args)}})

    def openSerie(self, episod_id):
        self.xbmc = self.kodiDao.connectFirstKodi()
        #   print episod_id
        result = self.xbmc.Player.Open({
            "item": {
                "episodeid": int(episod_id)
            },
            "options": {
                "resume": True
            }
        })
        print(result)

    def playPause(self, args):
        self.xbmc = self.kodiDao.connectFirstKodi()
        return self.xbmc.Player.PlayPause([PLAYER_VIDEO])

    def stopFilm(self):
        self.xbmc = self.kodiDao.connectFirstKodi()
        return self.xbmc.Player.Stop([PLAYER_VIDEO])

    def activeItem(self):
        self.kodiDao.connectFirstKodi()
        activeItem = {}
        activeKodi = self.xbmc.Player.GetItem([PLAYER_VIDEO])
        if not activeKodi:
            return
        listActiveItem = activeKodi.get('result', {}).get('item', [])
        #        print str(listActiveItem)
        if len(listActiveItem) > 0:
            type = listActiveItem['type']

        if type != 'unknown':
            title = listActiveItem['label']
            id = listActiveItem['id']
            speedJson = self.xbmc.Player.GetProperties({
                "properties": ["speed"],
                "playerid": PLAYER_VIDEO
            })
            speed = speedJson.get('result', {}).get('speed')
            print('onPlay' if speed > 0 else 'onPause')
            if type == 'movie':
                activeItem = self.kodiDao.loadFilmDetails(id)
            else:
                activeItem = self.kodiDao.loadEpisodeDetails(id)
            print(title)
            obj = {
                'key': "activeItem",
                'items': {
                    'item': activeItem,
                    'speed': speed
                }
            }
            self.synchronize(obj)
        else:
            print("nada en curso")

        return activeItem

    def test(self):
        #        self.xbmc.GUI.ActivateWindow({"window":"mediasource"})

        sources = self.xbmc.Files.GetSources(media="video")
        print(sources)
        directoryFilms = self.xbmc.Files.GetDirectory({
            "directory": '/media/HP Desktop Drive/Film/',
            "sort": {
                "order": "ascending",
                "method": "label"
            }
        })
        filmsTitle = []
        for film in directoryFilms.get('result', {}).get('files', []):
            item = film['label']
            if item not in filmsTitle:
                filmsTitle.append(item)

        print(filmsTitle)

        directorySeries = self.xbmc.Files.GetDirectory({
            "directory": '/media/Seagate Expansion Dr/série/',
            "sort": {
                "order": "ascending",
                "method": "label"
            }
        })
        seriesTitle = []
        for serie in directorySeries.get('result', {}).get('files', []):
            item = serie['label']
            if item not in seriesTitle:
                seriesTitle.append(item)
        print(seriesTitle)
        print(len(seriesTitle))

    def test1(self):
        xbmc = XBMC("http://192.168.1.100:8080/jsonrpc")
        audio = xbmc.AudioLibrary.GetSongs()
        print(audio)
	def test_status_broadcast(self):
		serial = FakeSerial()
		bus = Bus(serial)
		bus.broadcast_status(10, 1)
		self.assertEqual(serial.sendbuf, "_e000A01\n")
	def test_game_start(self):
		serial = FakeSerial()
		bus = Bus(serial)
		bus.start_game("a")
		self.assertEqual(serial.sendbuf, "ac\n")
示例#34
0
 def __init__(self):
     self.bus= Bus()
     self.ft = LoadFilms(self)
     self.fs = LoadSeries(self)
     self.fm = LoadMusiques(self)
示例#35
0
 if busOption == 2:
     status: bool = False
     capacity = None
     while status == False:
         capacity: int = int(
             input("Enter bus's capacity: "))
         if capacity > 0 and capacity <= 36:
             status = True
         else:
             log.error(
                 f"Capacity should to be into 0 to 36"
             )
     TerminalDao.getAllTerminals()
     terminal: int = int(
         input("Input terminal id: "))
     bus: Bus = Bus(capacity=capacity,
                    terminal_id=terminal)
     BusDao.insertBus(bus)
 if busOption == 3:
     BusDao.getAllBuses()
     bus_plate = input(
         "Write bus plate to update: ")
     capacity = None
     status: bool = False
     while status == False:
         capacity: int = int(
             input("Enter bus's capacity: "))
         if capacity > 0 and capacity <= 36:
             status = True
         else:
             log.error(
                 f"Capacity should to be into 0 to 36"
示例#36
0
class KodiDAO():
    listKodis = []
    listFilms = []
    listSeries = []
    listSeriesEnCours = []
    listMusiques = []
    ListWordsToRecognize = []
    ListTitlesToRecognize = []
    
    def __init__(self):
        self.bus= Bus()
        self.ft = LoadFilms(self)
        self.fs = LoadSeries(self)
        self.fm = LoadMusiques(self)
        
    def connectFirstKodi(self):
        if not hasattr(self, 'currentKodiIp') and len(self.listKodis) > 0 :
            self.currentKodiIp = self.listKodis[0].ip
        
        result = None    
        if hasattr(self, 'currentKodiIp') :
            result = self.connectKodi(self.currentKodiIp)    
        return  result
    
    def connectKodi(self, kodiIp):
        return XBMC("http://" + kodiIp + ":" + str(conf.PORT_HTTP_KODI) + "/jsonrpc")  
        
    def loadFilms(self):
        if not self.ft.isAlive():
            self.xbmc = self.connectFirstKodi()
            self.ft = LoadFilms(self)
            self.ft.start()
        return self.listFilms
    
    def loadFilmsCallback(self):
        self.bus.publish('loadFilmsDao', self.listFilms)

    def loadSeries(self):
        if not self.fs.isAlive():
            self.xbmc = self.connectFirstKodi()
            self.fs = LoadSeries(self)
            self.fs.start()
        return self.listSeries
    
    def loadSeriesCallback(self):
        self.bus.publish('loadSeriesDao', self.listSeries)
        self.bus.publish('loadSeriesEnCoursDao', self.listSeriesEnCours)
    
    def loadSeriesEnCours(self):
        if not self.fs.isAlive():
            self.xbmc = self.connectFirstKodi()
            self.fs = LoadSeries(self)
            self.fs.start()
        return self.listSeriesEnCours

    def loadMusiques(self):
        if not self.fm.isAlive():
            self.fm = LoadMusiques(self)
            self.fm.start()
        return self.listMusiques
    
    def loadMusiquesCallback(self):
        self.bus.publish('loadMusiquesDao', self.listMusiques)

    def loadEpisodeDetails(self, episodeid):
        if len(self.listSeries) > 0 :
            return 
         
        episode = None
        properties = ["title", "plot", "votes", "rating", "writer", "firstaired", "playcount", "runtime", 
                      "director", "productioncode", "season", "episode", "originaltitle", "showtitle", "cast", 
                      "streamdetails", "lastplayed", "fanart", "thumbnail", "file", "resume", "tvshowid", 
                      "dateadded", "uniqueid", "art"]

        for item in self.listSeries:
            if episodeid == item.id :
                episode = item
                detailsJson = self.xbmc.VideoLibrary.GetEpisodeDetails(episodeid=episodeid, properties=properties)
                details = detailsJson.get('result', {}).get('episodedetails', {})
                episode['art'] = details.get('art', {})
#                logger.debug(details)   
         
        return episode       
    
    
    def loadFilmDetails(self, movieid):
        if len(self.loadFilms()) > 0 :
            return 
        ### Media properties ###
        movie_properties = ['title', 'genre', 'year', 'rating', 'director', 'trailer', 'tagline', 'plot',  
                            'plotoutline', 'originaltitle', 'lastplayed', 'playcount', 'writer', 'studio', 
                            'mpaa', 'cast', 'country', 'imdbnumber', 'runtime', 'set', 'showlink', 'streamdetails',
                            'top250', 'votes', 'fanart', 'thumbnail', 'file', 'sorttitle' , 'resume', 'setid', 
                            'dateadded', 'tag', 'art' ]
        film = None
        for item in self.listFilms:
            if movieid == item.id :
                film = item
                detailsJson = self.xbmc.VideoLibrary.GetMovieDetails(movieid=movieid, properties=movie_properties)
                details = detailsJson.get('result', {}).get('moviedetails', {})
                film['art'] = details.get('art', {})
        return film
	def test_game_end(self):
		serial = FakeSerial()
		bus = Bus(serial)
		bus.end_game(1)
		self.assertEqual(serial.sendbuf, "_f01\n")
示例#38
0
 def createCase2(self):
     self.element1=Host(300,200,0,0)
     self.element2=Router(900,200,0,0)
     self.Bus1=Bus(300,205,900,205)
示例#39
0
 def createCase1(self):
     self.element1=Host(300,200,0,0)
     self.element2=Host(900,200,0,0)
     self.Bus1=Bus(300,205,900,205)
示例#40
0
class Palette():
    
    
    def __init__(self):
        self.case1=None
        self.case2=None
        self.case3=None
        self.case4=None
        self.case5=None
        self.element1=None
        self.element2=None
        self.element3=None
        self.element4=None
        self.button_exit=None
        self.button_next=None
        self.Bus1=None
        self.Bus2=None
        self.case11=pygame.image.load("Images/Case1.1.jpg")
        self.case12=pygame.image.load("Images/Case1.2.jpg")
        self.case21=pygame.image.load("Images/Case2.1.jpg")
        self.case22=pygame.image.load("Images/Case2.2.jpg")
        self.case31=pygame.image.load("Images/Case3.1.jpg")
        self.case32=pygame.image.load("Images/Case3.2.jpg")
        self.case41=pygame.image.load("Images/Case4.1.jpg")
        self.case42=pygame.image.load("Images/Case4.2.jpg")
        self.case51=pygame.image.load("Images/Case5.1.jpg")
        self.case52=pygame.image.load("Images/Case5.2.jpg")
        self.exit1=pygame.image.load("Images/button_exit1.jpg")
        self.exit2=pygame.image.load("Images/button_exit2.jpg")
        self.next1=pygame.image.load("Images/button_next1.jpg")
        self.next2=pygame.image.load("Images/button_next2.jpg")
        self.createPalette()
        self.display=pygame.display.get_surface()
    
    def updatePalette(self):
        x,y=pygame.mouse.get_pos()
        if(self.case1.rect.collidepoint(x,y)):
            self.case1.image=self.case12
        else:
            self.case1.image=self.case11
            
        if(self.case2.rect.collidepoint(x,y)):
            self.case2.image=self.case22
        else:
            self.case2.image=self.case21
            
        if(self.case3.rect.collidepoint(x,y)):
            self.case3.image=self.case32
        else:
            self.case3.image=self.case31  
        if(self.case4.rect.collidepoint(x,y)):
            self.case4.image=self.case42
        else:
            self.case4.image=self.case41  
        if(self.case5.rect.collidepoint(x,y)):
            self.case5.image=self.case52
        else:
            self.case5.image=self.case51 
        if(self.button_exit.rect.collidepoint(x,y)):
            self.button_exit.image=self.exit2
        else:
            self.button_exit.image=self.exit1
        if(self.button_next.rect.collidepoint(x,y)):
            self.button_next.image=self.next2
        else:
            self.button_next.image=self.next1      
        
        self.display.blit(self.case1.image,self.case1.rect)
        self.display.blit(self.case2.image,self.case2.rect)
        self.display.blit(self.case3.image,self.case3.rect)
        self.display.blit(self.case4.image,self.case4.rect)
        self.display.blit(self.case5.image,self.case5.rect)
        self.display.blit(self.button_exit.image,self.button_exit.rect)
        self.display.blit(self.button_next.image,self.button_next.rect)
        
        rect=pygame.Rect(160, 0, 10,1000)
        pygame.draw.rect(self.display,(220,0,0),rect,0)
        
        myfont = pygame.font.SysFont("LCD", 75)
        label = myfont.render("ARP SIMULATOR", 1,(220,0,0))
        self.display.blit(label, (500, 15))
        
    def createCase1(self):
        self.element1=Host(300,200,0,0)
        self.element2=Host(900,200,0,0)
        self.Bus1=Bus(300,205,900,205)
        #self.arp_request.rect.left,self.arp_request.rect.top=300,200
        
    def createCase2(self):
        self.element1=Host(300,200,0,0)
        self.element2=Router(900,200,0,0)
        self.Bus1=Bus(300,205,900,205)
        
    def createCase3(self):
        self.element1=Router(300,200,0,0)
        self.element2=Router(900,200,0,0)
        self.Bus1=Bus(300,205,900,205)
    
    def createCase4(self):
        self.element1=Router(300,200,0,0)
        self.element2=Host(900,200,0,0)
        self.Bus1=Bus(300,205,900,205)
        
    def createCase5(self):
        self.element1=Host(300,200,0,0)
        self.element2=Host(1000,200,0,0)
        self.element3=Router(650,200,0,0)
        self.element4=Host(650,400,0,0)
        self.Bus1=Bus(300,205,1000,205)
        self.Bus2=Bus(660,200,660,400)
           
    def update(self,screen):  
        self.Bus1.drawpoint(screen)
        self.element1.update(screen,1)
        self.element2.update(screen,1)
    
    def update5(self,screen):
        self.Bus1.drawpoint(screen)
        self.Bus2.drawpoint(screen)
        self.element1.update(screen,1)
        self.element2.update(screen,1)
        self.element3.update(screen,1)
        self.element4.update(screen,1)
        
    def createSprite(self,x,y,adr):
        s1 = pygame.sprite.Sprite()
        s1.image = pygame.image.load(adr).convert_alpha()
        s1.rect = s1.image.get_rect()
        (s1.rect.left, s1.rect.top) = (x,y)
        return s1   
    
    def createPalette(self):
        self.case1=self.createSprite(10,40,"Images/Case1.1.jpg")
        self.case2=self.createSprite(self.case1.rect.left,self.case1.rect.bottom+20,"Images/Case2.1.jpg")
        self.case3=self.createSprite(self.case2.rect.left,self.case2.rect.bottom+20,"Images/Case3.1.jpg")
        self.case4=self.createSprite(self.case3.rect.left,self.case3.rect.bottom+20,"Images/Case4.1.jpg")
        self.case5=self.createSprite(self.case4.rect.left,self.case4.rect.bottom+20,"Images/Case5.1.jpg")
        self.button_exit=self.createSprite(1200, 5,"Images/button_exit1.jpg")
        self.button_next=self.createSprite(1200, 670,"Images/button_next1.jpg")
        
    def ARPDesign(self,screen):
        c1 = pygame.time.Clock()
        Case1Pressed=False
        Case2Pressed=False
        Case3Pressed=False
        Case4Pressed=False
        Case5Pressed=False
        flag=True
        while True and flag:
            for events in pygame.event.get():
                    if events.type == pygame.QUIT:
                        quit()
                    if events.type == pygame.MOUSEBUTTONDOWN:
                        x,y=pygame.mouse.get_pos()
                        if(self.case1.rect.collidepoint(x,y) and not(Case1Pressed)):
                            Case1Pressed=True
                            Case2Pressed=False
                            Case3Pressed=False
                            Case4Pressed=False
                            Case5Pressed=False
                            self.createCase1()
                        if(self.case2.rect.collidepoint(x,y)):
                            Case1Pressed=False
                            Case2Pressed=True
                            Case3Pressed=False
                            Case4Pressed=False
                            Case5Pressed=False
                            self.createCase2()
                        if(self.case3.rect.collidepoint(x,y)):
                            Case1Pressed=False
                            Case2Pressed=False
                            Case3Pressed=True
                            Case4Pressed=False
                            Case5Pressed=False
                            self.createCase3()
                        if(self.case4.rect.collidepoint(x,y)):
                            Case1Pressed=False
                            Case2Pressed=False
                            Case3Pressed=False
                            Case4Pressed=True
                            Case5Pressed=False
                            self.createCase4()
                        if(self.case5.rect.collidepoint(x,y)):
                            Case1Pressed=False
                            Case2Pressed=False
                            Case3Pressed=False
                            Case4Pressed=False
                            Case5Pressed=True
                            self.createCase5()
                        if(self.button_next.rect.collidepoint(x,y)):
                            flag=False
                        if(self.button_exit.rect.collidepoint(x,y)):
                            flag=False
                            return 0
                        
                              
            c1.tick(100)
            screen.fill((255,255,255))
            self.updatePalette()
            if(Case1Pressed or Case2Pressed or Case3Pressed or Case4Pressed):
                self.update(screen)
            if(Case5Pressed):
                self.update5(screen)
            pygame.display.update()
        if(Case1Pressed):
            return 1
        if(Case2Pressed):
            return 2
        if(Case3Pressed):
            return 3
        if(Case4Pressed):
            return 4
        if(Case5Pressed):
            return 5