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 __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']))
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 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 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_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 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): 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, 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 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, 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 start(self): RTC().wakeup(self.__interval, self.__tick) self.__status = SchedulerStatusRunning() self.__logger.debug("Scheduler {} started.".format(self))
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()
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)
# 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)
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)
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
from micropython import const from class_camera import Camera from thresholds_holder import ThresholdsHolder from log import * from clock import set_time from pid import SteeringPid def time_correct(): (year, month, day, weekday, hours, minutes, seconds, subseconds) = RTC().datetime() return year >= 2018 and month >= 5 and day >= 5 and hours >= 23 and minutes >= 30 if not time_correct(): print("Time is incorrect.", RTC().datetime()) set_time(2018, 5, 6, 20, 55) ## run the pulse_led.py script if the board was reset because of the watchdog if (machine.reset_cause() == machine.WDT_RESET): wdt_reset_str = ConfigFile().get_property("wdt_reset") error("reset was caused by WDT_RESET") if (reset_str == None): num_of_watchdog_resets = 1 else: num_of_watchdog_resets = int(wdt_reset_str) + 1 error("This has happened", str(num_of_watchdog_resets), "times") ConfigFile().set_property("wdt_reset", str(num_of_watchdog_resets))
# 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
def time_correct(): (year, month, day, weekday, hours, minutes, seconds, subseconds) = RTC().datetime() return year >= 2018 and month >= 5 and day >= 5 and hours >= 23 and minutes >= 30
# Datalogger code for Cawthron Institute's mussel farm accelerometer chain # Author: Kevin Tang 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 if sys.platform == 'pyboard': # Pin connections tx_enable = Pin('X20', mode=Pin.OUT) # RTC initialisation i2c = I2C(1) ds3231 = DS3231(i2c) # UART initialisation uart = UART(4, 115200) # Pins X1 and X2 uart.init(115200, bits=8, parity=None, stop=1, timeout=500) # Non-blocking UART else: print('Incompatible system detected, please connect a pyboard') # Date initialisation rtc = RTC() timeCheck = ds3231.get_time() # Gets current time rtc.datetime( (timeCheck[0], timeCheck[1], timeCheck[2], timeCheck[6], timeCheck[3], timeCheck[4], timeCheck[5], 0)) # Syncs RTC clock to local time """ # Sets up RTC clock, uncomment to manually set the clock (NOTE: DAY OF WEEK AND TIME ZONE IS NOT WORKING) rtc.datetime((2020, 1, 22, 3, 15, 14, 50, 0)) # Comment out if already programmed
# 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(
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))
def stop(self): RTC().wakeup(None) self.__status = SchedulerStatusStopped() self.__logger.debug("Scheduler {} stopped.".format(self))