def _read(self, duration: str, white: float = 1.0, ir: float = 1.0, gain: float = 1.0, **kwargs): self._disable_all() # parse duration (in case of an error, leds won't stay on) duration_s = parse_time(duration) # set brightness and gain _white = self._set_leds(BrightPi.LEDS_WHITE, white) _ir = self._set_leds(BrightPi.LEDS_IR, ir) _gain = self._set_gain(gain) # enable all leds self._enable(BrightPi.LEDS_ALL) time.sleep(duration_s) self._disable_all() return [duration_s, _white, _ir, _gain]
def _read(self, duration: str = "0s", white: float = 1.0, ir: float = 1.0, gain: float = 1.0, **kwargs): self._disable_all() # parse duration (in case of an error, leds won't stay on) duration_s = parse_time(duration) # set brightness and gain _white = self._set_leds(BrightPi.LEDS_WHITE, white) _ir = self._set_leds(BrightPi.LEDS_IR, ir) _gain = self._set_gain(gain) # enable all leds self._enable(BrightPi.LEDS_ALL) # sleep for the configured duration and take a photo time.sleep(duration_s) cam_read = PiCamera._read(self, **kwargs) # disable camera lights again self._disable_all() return [duration_s, _white, _ir, _gain] + cam_read
def _read(self, file_path: str, duration: str, **kwargs): device_name = "hw:{},{}".format(self.card, self.device) duration_s = parse_time(duration) if self.file_ext == "wav": save_cmd = "{file_path}".format(file_path=file_path) elif self.file_ext == "flac": save_cmd = "| flac - -s -o {file_path}".format(file_path=file_path) cmd = "arecord -q -D {device_name} -t wav -f {sample_format} -r {rate} -d {duration_s} {save_cmd}".format( device_name=device_name, sample_format=self.sample_format, rate=self.rate, duration_s=duration_s, save_cmd=save_cmd, ) logger.debug("Recording audio: '{}'".format(cmd)) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() err_msg = p.communicate()[0] if p.returncode != 0: raise SensorNotAvailableException( "arecord returned {}: '{}'".format(p.returncode, err_msg)) logger.info("audio file written to '{}'".format(file_path))
def _read(self, res_X: int = 2592, res_Y: int = 1944, adjust_time: str = "2s", **kwargs): file_path = self.generate_path() adjust_time_s = parse_time(adjust_time) logger.debug( f"Reading {self.__class__.__name__} with {res_X}x{res_Y} for {adjust_time_s}s" ) try: with picamera.PiCamera() as camera: camera.resolution = (res_X, res_Y) camera.start_preview() time.sleep(adjust_time_s) camera.capture(file_path, format=self.format) camera.stop_preview() except picamera.exc.PiCameraMMALError as e: raise SensorNotAvailableException(e) except picamera.exc.PiCameraError as se: raise SensorNotAvailableException(e) logger.info(f"image file written to '{file_path}'") return [file_path, res_X, res_Y, adjust_time_s]
def _read(self, file_path: str, res_X: int, res_Y: int, adjust_time: str, filter_ir: bool = False, **kwargs): adjust_time_s = parse_time(adjust_time) logger.debug("Reading IrCutCamera with {}x{} for {}s".format( res_X, res_Y, adjust_time_s)) try: with picamera.PiCamera() as camera: camera.resolution = (res_X, res_Y) camera.start_preview() # set cam gpio to the matching value with open(self.cam_gpio_path, "a") as gpio_file: gpio_file.write(str(int(filter_ir))) time.sleep(2) time.sleep(adjust_time_s) camera.capture(file_path, format=self.format) camera.stop_preview() except picamera.exc.PiCameraMMALError as e: raise SensorNotAvailableException(e) except picamera.exc.PiCameraError as e: raise SensorNotAvailableException(e) logger.info("image file written to '{}'".format(file_path))
def _schedule_metering(self, name: str, metering: dict): # default values for start and end (whole day) start = 0 end = 24 * 60 * 60 if "start" in metering["schedule"]: start = parse_time(metering["schedule"]["start"]) if "end" in metering["schedule"]: end = parse_time(metering["schedule"]["end"]) interval = parse_time(metering["schedule"]["interval"]) logger.info("metering '{}' from {} until {}, every {}".format( name, start, end, interval)) def schedule_day_second(day_second): ts = datetime.datetime.fromtimestamp(day_second) time = ts.time() s = schedule.every().day s.at_time = time s.do(run_threaded, self._run_metering, name, metering) if start < end: for day_second in range(start, end, interval): schedule_day_second(day_second) else: logger.info( "metering {} runs over night (start: {}, end: {})".format( name, metering["schedule"]["start"], metering["schedule"]["end"])) # add one day to end end += 24 * 60 * 60 for day_second in range(start, end, interval): # align day_second to the actual day day_second %= (60 * 60 * 24) schedule_day_second(day_second)
def _read(self, duration: str, **kwargs): duration_s = parse_time(duration) # enable logger.debug(f"LED {self.led_pin} on for {duration_s}s") GPIO.output(self.led_pin, GPIO.HIGH) # sleep time.sleep(duration_s) # disable logger.debug(f"LED {self.led_pin} off") GPIO.output(self.led_pin, GPIO.LOW) return [duration_s]
def record(self, count: int = 1, delay: str = "0s", tries=2, **kwargs): logger.debug("acquire access to {}".format(self.name)) self._lock.acquire() records = [] successful = 0 try: for num in range(count * tries): try: ts = Sensor.time_repr() reading = self._read(**kwargs) if len(reading) != len(self._header_sensor): raise SensorNotAvailableException( "Reading length ({}) does not match header length ({})." .format(len(reading), len(self._header_sensor))) self._publish(ts, reading, **kwargs) records.append(reading) successful += 1 logger.debug( "Sensor '{}' measured correctly (try {}/{}, {} successful)." .format(self.name, num + 1, count * tries, successful)) if successful < count: time.sleep(parse_time(delay)) else: break except SensorNotAvailableException as e: logger.warn( "Sensor '{}' measurement failed (try {}/{}, {} successful): {}" .format(self.name, num + 1, count * tries, successful, e)) finally: if successful < count: logger.error( "Sensor '{}': {} successful of {} requested measurements.". format(self.name, successful, count)) logger.debug("release access to {}".format(self.name)) self._lock.release() return records
async def mute(self, ctx, member_descriptor, time_descriptor, *reason): member = await get_member(self.bot, member_descriptor) if not member: await ctx.send(embed=await error( f"No member found by descriptor '{member_descriptor}'")) return n_seconds = parse_time(time_descriptor) if not n_seconds: await ctx.send( embed=await error(f"Unknown time period '{time_descriptor}'")) return reason = " ".join(reason) log_data = { "muted": str(member), "muted by": str(ctx.author), "muted for": str(datetime.timedelta(seconds=n_seconds)), "reason": reason, "timestamp": datetime.datetime.now().isoformat() } await log(self.bot, member.id, log_data, "mute_log", EmbedColor.orange) self.mutes.append((member, datetime.datetime.now(), n_seconds, reason)) if reason: desc = f"You have been **muted** in the Speedrunners discord server for {str(datetime.timedelta(seconds=n_seconds))} for the following reason:\n```{reason}```" else: desc = f"You have been **muted** in the Speedrunners discord server for {str(datetime.timedelta(seconds=n_seconds))}" embed = discord.Embed(description=desc, color=EmbedColor.dark_green) try: await member.send(embed=embed) except discord.errors.Forbidden: pass await ctx.send(embed=await success( f"Successfully muted {str(member)} for {str(datetime.timedelta(seconds=n_seconds))}" ))
async def mute(ctx: commands.Context, user: str, *args: str) -> None: member = await get_member(bot.get_guild(sr), user) if member is None: await ctx.send(embed=await error_embed(f"Unknown user '{user}'")) n_seconds = parse_time("".join(*args)) if n_seconds is None: await ctx.send(embed=await error_embed(f"Unknown time period '{' '.join(*args)}'")) await mute_member(member, n_seconds) await ctx.send(embed=await success_embed(f"Muted '{user}' for {str(datetime.timedelta(seconds=n_seconds))}")) desc = await log("mutes", { "Muted": member.name, "Muted by": ctx.message.author.name, "Time period": str(datetime.timedelta(seconds=n_seconds)), "Timestamp": ctx.message.created_at.now().isoformat() }) embed = discord.Embed(title="Muted member", description=desc, color=0xFFA500) channel = bot.get_channel(mute_log) await channel.send(embed=embed)