def __init__(self, unit_id=0): # Handle camera configuration. self.unit_id = unit_id self.camera_port = BASE_PORT + unit_id self.video_url = 'http://localhost:{}/video_feed'.format(self.\ camera_port) self.image_url = 'http://localhost:{}/current_image'.format(self.\ camera_port) self.binary_image_url = 'http://localhost:{}/current_binary_image'.\ format(self.camera_port) # Launch camera image server. self.boot_image_server() # Register motor controls. # TODO self.x = 0 self.y = 0 self.z = 0 self.dx = 1 self.dy = 1 self.dz = 1 # Create the Hardware. self.hardware = Hardware() # Clean up on exit. atexit.register(self.close)
def __init__(self): logger.info("Starting amplifier control service") self.validVolCmd = ['Up', 'Down', 'Mute'] self.toggleinputs = [ 'Himbeer314', 'CD', 'Bladdnspiela', 'Portable', 'Hilfssherriff' ] self.oled = AmpiOled() self.hyp = Hypctrl(self.oled) #Starte handler für SIGTERM (kill -15), also normales beenden #Handler wird aufgerufen, wenn das Programm beendet wird, z.B. durch systemctl signal.signal(signal.SIGTERM, self.signal_term_handler) self.hw = Hardware(self.oled, self.hyp) time.sleep(1.1) #Short break to make sure the display is cleaned self.hw.setSource("Aus") #Set initial source to Aus self.mc_restart_cnt = 0 self.t_stop = threading.Event() self.clearTimer() self.udpServer() self.tcpServer() #tcpServer_t = Thread(target=tcpServer, args=(1, t_stop)) #tcpServer_t.start() logger.info("Amplifier control service running")
def run(self, robot_config_values, room_size, rects, start_pos, start_angle, square_size, cartographer_grid): self.is_running = True self.commands_queue = Queue() # Clear map and set sizes for views self.map_window.start(room_size) self.map_scene.draw_map(room_size, rects, start_pos, start_angle) self.scanner_window.start(room_size) self.discovered_map_window.start(room_size, square_size) # Create some objects for the RobotController to use, as we have all the data here hardware = Hardware(start_pos, start_angle, room_size, rects, robot_config_values, self.map_change_pos, self.map_change_rotation) cartographer = Cartographer(room_size, square_size, self.cartographer_grid_values_callback, cartographer_grid) self.controller = RobotController(room_size, hardware, cartographer, self.commands_queue, self.scanner_draw_points, self.scanner_draw_lines, self.scanner_draw_robot, self.scanner_clear) self.controller.start()
def init(): assert ROOMID global room global raspberry global bookings room = Database(ROOMID) raspberry = Hardware(LEDS, PINS) bookings = room.Bookings
def create_app(): state = SharedState() hardware = Hardware(state) state.hardware_listener = hardware return (WebApp([(r'/()', IndexEndpoint), (r'/static/(.*)', StaticEndpoint), (r'/spots', SpotEndpoint), (r'/config', ConfigEndpoint, { 'state': state })]), hardware)
def start(): print('Starting...') global hardware, main hardware = Hardware(conf['setup']) main = Main(hardware) main.reset() main.load(conf['events']) main.run()
def main(): global app_button_pressed global run_sun_door_check t = Timer(SUN_CHECK_INTERVAL, schedule_sun_up_down) t.start() hw = Hardware(False, False) s = TimeCheck('Brussels') hw.motor_down() # @Startup open door door_state_up = False button_override = False while True: # blynk iot stuff #blynk.run() # move by button press if hw.button_pressed() or app_button_pressed: print('button_pressed') app_button_pressed = False if door_state_up: hw.motor_down() door_state_up = False button_override = not button_override else: hw.motor_up() door_state_up = True button_override = not button_override # sunup triggers...only check every 5 min if run_sun_door_check: logging.debug('sun door check') door_state_sun_is_up = s.run() logging.debug('override = %r' % button_override) if button_override: # Max override is until override state matches state indicated by the sun button_override = not (door_state_sun_is_up == door_state_up) else: # move by sunup/sundown if door_state_sun_is_up and not door_state_up: hw.motor_up() door_state_up = True logging.debug('door up') elif not door_state_sun_is_up and door_state_up: hw.motor_down() door_state_up = False logging.debug('door down') else: logging.debug('door unchanged') run_sun_door_check = False t = Timer(SUN_CHECK_INTERVAL, schedule_sun_up_down) t.start()
def main(): hardware = Hardware() update_interval = 0.1 thread = threading.Thread(target=update, args=(hardware, update_interval), daemon=True) thread.start() user_input_timeout = 1 status_timeout = 10 max_ping = 200 quick_checks = networkstatus.MultipleChecks([ networkstatus.PingDefaultGatewayCheck(max_ping=max_ping, timeout=status_timeout), networkstatus.PingCheck('google.com', max_ping=max_ping, timeout=status_timeout), networkstatus.DnsCheck('google.com', timeout=status_timeout), networkstatus.PingPrinterCheck(max_ping=max_ping, timeout=status_timeout) ]) extended_checks = networkstatus.MultipleChecks([ networkstatus.SpeedCheck( min_down=20*1000*1000, # 20 mpbs (limited by Raspberry Pi 3b wifi capabilities) min_up=5*1000*1000, # 5 mpbs max_ping=max_ping, timeout=status_timeout) ]) checks = networkstatus.NormalAndExtendedChecks(quick_checks, extended_checks, [hardware]) # Start by running the extended test last_normal_test = 0 last_extended_test = 0 normal_test_interval = 60 extended_test_interval = 60 * 60 while True: current_time = time.time() if (current_time >= last_normal_test + normal_test_interval or current_time >= last_extended_test + extended_test_interval): last_normal_test = current_time time_str = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if current_time >= last_extended_test + extended_test_interval: print('# time(utc),{}'.format(checks.column_names())) last_extended_test = current_time result_str = checks.extended_check() else: result_str = checks.normal_check() print('{},{}'.format(time_str, result_str), flush=True) user_input = hardware.get_user_input(user_input_timeout) if user_input == hardware.UserInput.NORMAL_TEST: last_normal_test = 0 elif user_input == hardware.UserInput.EXTENDED_TEST: last_normal_test = 0 last_extended_test = 0
def __init__(self): # Initialize an ADS1299 object self.SETTINGS = Settings() self.SETTINGS.update(ADS1299.DEFAULT_SETTINGS) try: # Lazy import local settings when __init__ is called. # If local settings exist, overwrite this object settings. from .settings import LOCAL_SETTINGS self.SETTINGS.update(LOCAL_SETTINGS) except ImportError: pass # Initialize SPI for ADS1299 self.spi = mraa.Spi(self.SETTINGS.SPI_CHANNEL) self.spi.frequency(self.SETTINGS.SPI_FREQUENCY) self.spi.mode(self.SETTINGS.SPI_MODE) # Initialize hardware control for ADS1299 self.hardware = Hardware() self.hardware.power = self.init_gpio(self.SETTINGS.PIN_POWER, mraa.DIR_OUT_LOW, mraa.MODE_STRONG) self.hardware.reset = self.init_gpio(self.SETTINGS.PIN_RESET, mraa.DIR_OUT_HIGH, mraa.MODE_STRONG) self.hardware.start = self.init_gpio(self.SETTINGS.PIN_START, mraa.DIR_OUT_LOW, mraa.MODE_STRONG) self.hardware.ready = self.init_gpio(self.SETTINGS.PIN_READY, mraa.DIR_IN, mraa.MODE_HIZ) self.hardware.chip_select = self.init_gpio( self.SETTINGS.PIN_CHIP_SELECT, mraa.DIR_OUT_HIGH, mraa.MODE_STRONG) self.hardware.chip_select_2 = self.init_gpio( self.SETTINGS.PIN_CHIP_SELECT_2, mraa.DIR_OUT_HIGH, mraa.MODE_STRONG) self.hardware.power.write(1) # power up # wait for internal reference waking up (150ms) # wait for internal clock waking up (20us) # wait for external cloxk waking up (1.5ms) sleep(160 * 10**(-3)) self.hardware.reset.write(0) # reset ADS1299 sleep(1 * 10**(-3)) # wait for reset register (18 CLK) self.hardware.reset.write(1) # finish reseting ADS1299 # Connect Register controller for ADS1299 self.register = Register(self.spi, self.hardware.chip_select)
def main(): hardware = Hardware() with open(TIMESTAMPS_FILE, 'a', buffering=1) as f: try: # Use external trigger only hardware.send_message(messages.TriggerConditionMessage(0b1000000)) while True: msg = hardware.read_message() if type(msg) == messages.MeasuredDataMessage: logging.info("%s %s ns", msg.timestamp, msg.count_ticks_PPS) f.write("%s %s ns\n" % (msg.timestamp, msg.count_ticks_PPS)) except KeyboardInterrupt: print "Interrupted by user." finally: hardware.close()
def __init__(self, house_sections_seed_file, io_parts_seed_file): self.hardware = Hardware(io_parts_seed_file) house_sections_seeds = json.load( codecs.open(house_sections_seed_file, "r", "utf-8")) self.house_sections = {} for section_name, section in house_sections_seeds.items(): priority = section["priority"] message_name = section["message_name"] self.house_sections[section_name] = HouseSection( self.hardware, section_name, message_name, priority) for name, condition in section["conditions"].items(): message_name = condition["message_name"] priority = condition["priority"] io_part_statuses = condition["io_part_statuses"] self.house_sections[section_name].add_condition( name, message_name, priority, io_part_statuses) self.update_section_current_conditions()
def __init__(self): self.now = 0 self.demo_now = 0 self.event_queue = [] self.hw = Hardware() self.hw.enter_button.when_pressed = self.enter_button_pressed self.hw.up_button.when_pressed = self.up_button_pressed self.hw.down_button.when_pressed = self.down_button_pressed self.hw.exit_button.when_pressed = self.exit_button_pressed self.dmd = self.hw.dmd self.modes = { 'clock': clock.Mode(self.dmd), 'menu': menu.Mode(self.dmd), 'clock-select': menu.ClockSelectMode(self.dmd), 'status': status.Mode(self.dmd), } self.mode = 'clock' self.dmd.brightness = 0.5 self.dmd.rotation = 180 self.modes[self.mode].start() self.dmd.show()
def __init__(self, fullscreen=False): self.bg_color = (0, 0, 0) self.clock = pygame.time.Clock() if fullscreen: self.screen = pygame.display.set_mode((800, 600), pygame.FULLSCREEN) else: self.screen = pygame.display.set_mode((800, 600)) self.modes = [HeartMode(assets_path), TemperatureMode(assets_path), WeatherMode(assets_path), FortuneMode(assets_path), LinesMode(assets_path), ClockMode(assets_path)] self.current_mode = 0 self.running = True self.standby = False self.hw = Hardware() self.led_level = 0
def new_bus(bus: Bus): print(bus) bus.on_close().subscribe( on_next=lambda x: print(f"CLOSE BUS {x}"), on_error=lambda e: logging.exception(e) ) def new_device(device: Device): logging.info(f"FOUND {device}") device.on_close().subscribe( on_next=lambda reason: print(f"CLOSE DEVICE {reason}"), on_error=logging.warning ) try: Hardware().get_buses().subscribe(new_bus, logging.exception) Hardware().get_devices().subscribe(new_device, logging.exception) Hardware().get_values().pipe( ).subscribe(None, logging.exception) input() finally: Hardware().dispose()
from time import time parser = argparse.ArgumentParser() c = Config() parser.add_argument('--node', help='Node id', default='master', choices=c.settings['nodes'].keys()) parser.add_argument('--loglevel', help='Log level for server & playback', default='INFO') args = parser.parse_args() logging.getLogger().setLevel(args.loglevel) hw = Hardware(c, args.node) script = [] @route('/cmd', method='POST') def start_show(): global script logging.info("Starting!") t = time() hw.play_script(script) response.content_type = "application/json" return json.dumps({'total_runtime': time() - t})
pop_job["id"])) return jsonify(pop_job) else: return make_response("", 204) @application.route("/api/job/<string:id>/results", methods=["PUT"]) def job_results_route(id): req_hardware = request.args.get("hardware") if request.method == "PUT": status = request.json["failed"] if not check_password(request.args["FLASK_PASS"]): return make_response("", 403) job_db_dao.update_end_job(id, status) log.info("{} has completed job {}.".format(req_hardware, id)) return make_response("", 200) hardware_list = ["Omar", "Goose", "Nicki", "Beth"] hardware_dict = {name: Hardware(name) for name in hardware_list} job_db_dao = JobDbDao() jobs_cache = JobsCache(job_db_dao) if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "prod": application.run(port=80, host="0.0.0.0") else: application.run(debug=True)
def __init__(self, db, bottle_ip='127.0.0.1', pigpio_host="", pigpio_port=8888): """- Create the controller, its Viewer and connect to database (Model) - Select all the hardware (sensors/switches) for the systems under its control - Launch the scheduler - host:port is used to connect to the pigpio server running on the Raspberry Pi. Need to execute 'sudo pigpiod' to get that daemon running if it is not automatically started at boot time :param db: instance of a Ponicwatch_Db :param bottle_ip: IP to reach the webpages. Important to set properly for remote access. """ global _simulation # if no PGIO port as we are not running on a Raspberry Pi self.debug = DEBUG self.bottle_ip = bottle_ip # keep a link to the database i.e. M in MVC self.db = db self.db.allow_close = False # finding the Controller User entry --> currently 'hard coded' as 'ctrl'/'passwd' --> to improve later self.user = User(self, id=1) self.name = self.user[ "name"] # this name is used to identify the log messages posted by this controller # opening the LOGger with the debug level for this application run self.log = Ponicwatch_Log(controller=self, debug=DEBUG) # Create the background scheduler that will execute the actions (using the APScheduler library) self.scheduler = BackgroundScheduler() # select all the systems, sensors, switchs to monitor and the necessary hardware drivers self.pig = pigpio.pi( pigpio_host, pigpio_port) if not _simulation else pigpio_simu.pi() if not self.pig.connected: if self.debug >= 2: print("WARNING: not connected to a RasPi") self.pig = pigpio_simu.pi() _simulation = True # some plural are "fake" to respect the logic of: <cls name> + 's' --> dictionary of <cls> PonicWatch Object self.systems, self.sensors, self.switchs, self.hardwares, self.interrupts = {}, {}, {}, {}, {} # system_id <= 0: inactive link --> ignore this row self.db.curs.execute( "SELECT * from tb_link where system_id > 0 order by system_id desc, order_for_creation" ) self.links = self.db.curs.fetchall() for system_id, sensor_id, switch_id, hardware_id, order_for_creation, interrupt_id in self.links: # (1) create all necessary objects # (2) and register the system and hardware to a sensor/switch if system_id not in self.systems: self.systems[system_id] = System(self, id=system_id) if hardware_id and hardware_id not in self.hardwares: self.hardwares[hardware_id] = Hardware( controller=self, id=hardware_id, system_name=self.systems[system_id]["name"]) if sensor_id and sensor_id not in self.sensors: self.sensors[sensor_id] = Sensor( controller=self, id=sensor_id, system_name=self.systems[system_id]["name"], hardware=self.hardwares[hardware_id]) if switch_id and switch_id not in self.switchs: self.switchs[switch_id] = Switch( controller=self, id=switch_id, system_name=self.systems[system_id]["name"], hardware=self.hardwares[hardware_id]) if interrupt_id and interrupt_id not in self.interrupts: self.interrupts[interrupt_id] = Interrupt( controller=self, id=interrupt_id, system_name=self.systems[system_id]["name"], hardware=self.hardwares[hardware_id]) self.db.allow_close = True self.db.close()
player_map = { '.wav': 'aplay {}'.format(song_path), '.mp3': 'mpg123 {}'.format(song_path) } if file_extension not in player_map.keys(): raise RuntimeError( "Player for %s not configured.".format(file_extension)) return player_map[file_extension.lower()] if __name__ == "__main__": c = config.Config() hw = Hardware(c) parser = argparse.ArgumentParser() parser.add_argument('--loglevel', default='INFO', help='Log level. Defaults to INFO') parser.add_argument('--song', required=True, help='Song to play', choices=c.settings['music'].keys()) parser.add_argument('--no-cache', action='store_true', default=False, help='Set to disable caching')
def __init__(self): self.hwData = Hardware() self.flData = Flavor() self.imgData = Image()
from werkzeug.utils import secure_filename # Import of own classes from tracks import Tracks from playlist import Playlist from hardware import Hardware from lighting import Lighting, Section try: from led import Leds except: from led_nohw import Leds # Initializations tracks = Tracks("tracks") playlist = Playlist() hardware = Hardware(tracks, playlist) ledHw = Leds(64) ledConfig = Lighting(ledHw) event_start = threading.Event() event_stop = threading.Event() event_shutdown = threading.Event() # Creating the web server app = Flask(__name__, template_folder=".", static_folder="assets") app.config.from_object('config.Config') log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) # Definition of all the server routings
def tuple_to_hw_object(rows): hw_list = list() for row in rows: hw_list.append(Hardware(row)) return hw_list
p1, p2 = self.race.best_time self.p1_best_time.SetLabel("%0.2f sec" % p1) self.p2_best_time.SetLabel("%0.2f sec" % p2) for num, (old, new) in enumerate( zip(self.last_num_laps, self.race.num_laps)): if old != new: lap_list = [self.p1_lap_list, self.p2_lap_list][num] pos = lap_list.InsertStringItem(0, "%d" % new) lap_list.SetStringItem( pos, 1, "%0.2f" % (sum(self.race.laps[num]))) lap_list.SetStringItem(pos, 2, "%0.2f" % (self.race.laps[num][-1])) self.last_num_laps = self.race.num_laps if __name__ == "__main__": hardware = Hardware("/dev/ttyUSB0") race = RaceThread(hardware, [1, 1]) try: app = wx.PySimpleApp(0) wx.InitAllImageHandlers() rt = RaceTimer(app, race, None, -1, "") app.SetTopWindow(rt) rt.Show() app.MainLoop() finally: race.stop() hardware.close()
def handle_config(cmd_parts): global hardware, hardware_configs global images, image_configs global flavors, flavor_configs global curr_command if (len(cmd_parts) != 4): sys.stderr.write("ERROR: Invalid command." + "\n") logger.info(curr_command + ": Failure") return if (cmd_parts[2] == "--hardware"): file = cmd_parts[3] my_file = "../p0_config/" + file if (os.path.exists(my_file)): hardware = True with open(my_file) as f: lines = f.readlines() num_configs = int(lines[0]) for x in range(1, num_configs + 1): cfg = lines[x].split(" ") h = Hardware(cfg[0], cfg[1], cfg[2], cfg[3], cfg[4]) hardware_configs[cfg[0]] = h sys.stdout.write( str(len(hardware_configs)) + ' physical servers now available.' + "\n") logger.info(curr_command + ": Success") else: sys.stderr.write("ERROR: File you specified does not exist." + "\n") logger.info(curr_command + ": Failure") elif (cmd_parts[2] == "--images"): file = cmd_parts[3] my_file = "../p0_config/" + file if (os.path.exists(my_file)): images = True with open(my_file) as f: lines = f.readlines() num_configs = int(lines[0]) for x in range(1, num_configs + 1): cfg = lines[x].split(" ") img = Image(cfg[0], cfg[1]) image_configs[cfg[0]] = img sys.stdout.write( str(len(image_configs)) + ' images now available.' + "\n") logger.info(curr_command + ": Success") else: sys.stderr.write("ERROR: File you specified does not exist." + "\n") logger.info(curr_command + ": Failure") elif (cmd_parts[2] == "--flavors"): file = cmd_parts[3] my_file = "../p0_config/" + file if (os.path.exists(my_file)): flavors = True with open(my_file) as f: lines = f.readlines() num_configs = int(lines[0]) for x in range(1, num_configs + 1): cfg = lines[x].split(' ') flv = Flavor(cfg[0], cfg[1], cfg[2], cfg[3]) flavor_configs[cfg[0]] = flv sys.stdout.write( str(len(flavor_configs)) + ' VM flavors now available.' + "\n") logger.info(curr_command + ": Success") else: sys.stderr.write("ERROR: File you specified does not exist." + "\n") logger.info(curr_command + ": Failure") else: sys.stderr.write("ERROR: Invalid command." + "\n") logger.info(curr_command + ": Failure")
import tornado.ioloop, argparse, os from hardware import Hardware from web import SocketHandler, StatusHandler from settings import Parameters from camera import Camera from neural import Neural from wrist import Wristband if __name__ == "__main__": parameters = Parameters() hardware = Hardware() wrist = None parser = argparse.ArgumentParser() parser.add_argument('-s', '--stream', action='store_true', help="enable web stream") parser.add_argument('-c', '--camera', action='store_true', help="enable camera ") parser.add_argument('-l', '--logfile', action='store', help="save stats to file") parser.add_argument('-w', '--wristband',
""" Walks through the grid map, in a very naive way """ import time import pickle from hardware import Hardware from state import State hardware = Hardware("../test/live.txt") # /dev/tty.HC-06-DevB # # hardware = Hardware(serial_port='/dev/rfcomm0', output_file='../test/live.txt') # , testfile='../test/live.txt' state = State(n_particles=150) sumdeltas = 0 current_time = 0 start = time.time() i = 0 for update in hardware.updates(): i += 1 start_time = time.time() state.update(update) stop_time = time.time() current_time += update.timedelta timedeltadelta = update.timedelta - (stop_time - start_time) * 1000 sumdeltas += timedeltadelta
from socket import * import threading from hardware import Hardware from storage import Storage from physicalMemory import PhysicalMemory from swap import Swap from datetime import datetime import subprocess #initialize objects h = Hardware() m = PhysicalMemory() s = Swap() st = Storage() logAccess = {} def analyze(byteMessage): message = byteMessage.decode('utf-8') if 'hard' in message: return analyzeHardware(message).encode('utf-8') elif 'mem' in message: return analyzePhysicalMemory(message).encode('utf-8') elif 'swap' in message: return analyzeSwap(message).encode('utf-8') elif 'stor' in message: return analyzeStorage(message) elif 'netstat' in message: return checkConnection() elif 'log' in message: return log().encode('utf-8') else:
plt.show() return I_total # Parameters # Velocity Mode max_coil_pos = 0.0012 # 5mm T = 1.5 # Period of the sin. actuation voltage in s runningTime = 1 # Velocity Mode measuring time in s dt = 0.001 p_gain_vel = 900 i_gain_vel = 700 d_gain_vel = 10 hw = Hardware() hw.switchRelay(False) #calibrate() ##### Calibration hw.setOutput(0) input("Move the balance in a levelled position and press enter!") setpoint = hw.readFotodiode() # level position ##### Velocity Mode t = 0 t_start = time.time() # Fotodiode calibration values foto_slope = 4.9042 foto_yoffset = -0.0209
[time_array, val0_array, val1_array, val2_array] = hw.getArrays() if (len(time_array) > 0): self.plot1_curve1.setData(x=time_array, y=val0_array) self.plot2_curve1.setData(x=time_array, y=val1_array) self.plot3_curve1.setData(x=time_array, y=val2_array) self.plot4_curve1.setData(x=time_array, y=val0_array) self.plot4_curve2.setData(x=time_array, y=val1_array) self.plot4_curve3.setData(x=time_array, y=val2_array) # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- if __name__ == '__main__': if (len(sys.argv) < 2): print("What is the port address?") else: print("Serial port name " + sys.argv[1]) # Initalise hwrdware device hw = Hardware(sys.argv[1]) # Initialise GUI app = QtGui.QApplication(sys.argv) window = UIClass() window.show() sys.exit(app.exec_())