# Attempts connection to stored wifi networks. Broadcasts accesspoint webserver if no success. if not wifi.connect_to_known_network(): server_socket = webserver.ap_webserver_start() while not wifi.wlan_sta.isconnected(): webserver.ap_webserver_loop(server_socket) webserver.ap_webserver_stop(server_socket) # ------------------------- SETUP ------------------------------------------------------------------- import umqttsimple import logfile from scheduler_light import Scheduler, Job utime.sleep(1) # Digesting time, imports. log = logfile.LogFile("Mainloop", config.log_filename, config.log_sizelimit, config.log_level, config.log_print) # Establish MQTT client: mqtt_client = umqttsimple.MQTTClient(config.client_id, config.mqtt_broker, config.mqtt_port, config.mqtt_user, config.mqtt_password) # MQTT callbacks: def callback_mqtt_subscription(topic, msg): """ Callback upon MQTT publication of subscribed topics. """ log.debug("MQTT message recieved:") log.debug('%s,%s' % (topic.decode('utt-8'), msg.decode('utf-8'))) def mqtt_subscriptions():
ESP microcontroller wifi connection related fuctions. Aslak Einbu and Torbjørn Pettersen, Jan 2020. """ import network import ujson import os import config import machine import ntptime import crypt import utime import logfile log = logfile.LogFile("Wifi-connection", config.log_filename, config.log_sizelimit, config.log_level, config.log_print) networks_stored = "networks_stored.json" # File for storage of applied SSIDs and their passwords networks_detected = "networks_detected.json" # File for storage of currently present Wifi networks networks_provisioned = "wifi.json" # File for provisioning of known SSIDs and passwords crypt_seed = config.crypt_seed TypeX = crypt.Crypt(crypt_seed) wlan_ap = network.WLAN(network.AP_IF) wlan_ap.active(False) wlan_sta = network.WLAN(network.STA_IF) wlan_sta.active(False)
"""Job scheduler - light version. Inspiration: https://github.com/rguillon/schedule Torbjørn Pettersen, 12.01.2020. """ import utime import machine import utime import config import logfile log = logfile.LogFile("scheduler", "scheduler.log", config.log_sizelimit, config.log_level, config.log_print) class Job: """Job class. :param name: job name :type name: str :param job: function called to do job :type job: fun :param repeat: number of times to repeat job :type repeat: int :param interval: number of seconds between repeated job runs :type interval: int :returns: Job object to be used by Scheduler :rtype: object """ def __init__(self, name, job, interval, repeat):
"""Tester for logfile.py.""" import logfile levels = "DEBUG INFO WARNING ERROR".split() log = logfile.LogFile("TestLog", "testlog.txt", 200, "DEBUG", False) for i in range(10): ind = i % 4 msg = "Melding {}".format(i) if levels[ind] == "DEBUG": log.debug(msg) elif levels[ind] == "INFO": log.info(msg) elif levels[ind] == "WARNING": log.warning(msg) elif levels[ind] == "ERROR": log.error(msg) log.level = "DEBUG" log.debug("Sjekk om vi får ut debug melding til slutt")
# ------------------------- SETUP ------------------------------------------------------------------- import umqttsimple import logfile from scheduler_light import Scheduler, Job from machine import Pin from timers import Countdown mqtt_timer = Countdown(5) # Timer for checking recieved mqtt message last 5 seconds. relay = Pin(14, Pin.OUT) # Relay pin. relay.off() # Relay off at start. utime.sleep(1) # Digesting time, imports. log = logfile.LogFile("Relay-1", config.log_filename, config.log_sizelimit, config.log_level, config.log_print) # Establish MQTT client: mqtt_client = umqttsimple.MQTTClient(config.client_id, config.mqtt_broker, config.mqtt_port, config.mqtt_user, config.mqtt_password) # MQTT callbacks: def callback_mqtt_subscription(topic, msg): """ Callback upon MQTT publication of subscribed topics. """ if topic == b'switches/relay-1/state/read': mqtt_timer.start()
""" Button interactions - with callback. Aslak Einbu, Jan 2020 """ from machine import Pin import logfile import config log = logfile.LogFile("Button-test", config.log_filename, config.log_sizelimit, config.log_level, config.log_print) class Button: """ Attach pin and callback to button.""" def __init__(self, pin, callback): self.pin = pin self.state = Pin(pin, Pin.IN, Pin.PULL_UP) self.laststate = self.state.value() self.callback = callback log.debug("Button attached to pin %s with callback %s" % (str(pin), str(callback))) def check_pressed(self): """ Run callback function if button was pressed since last check. """ state = self.state.value() if state != self.laststate: if state == 1: self.callback() self.laststate = state
def main(): '''Things the mains do...''' parser = argparse.ArgumentParser(description="Does $LogFile things", epilog="Author: P. Polakovic") parser.add_argument("-f", "--file", nargs=1, required=True, help="Path to NTFS logfile", type=str) args = parser.parse_args() with open(args.file[0], "rb+") as logfile_stream: lrb, lrbb = logfile.get_lsn_restart_blocks(logfile_stream) print("Journal version: {}.{}".format( lrb.header.major_ver, lrb.header.minor_ver)) print("System page size:", hex(lrb.header.system_page_size)) print("Log page size:", hex(lrb.header.log_page_size)) print("-- SNAPSHOT INFO --") print("Current LSN:", hex(lrb.area.current_lsn)) print("Clients:", lrb.area.log_clients) for client in lrb.clients.clients: print("\tClient name:", client.get_name()) print("\tClient's restart LSN:", hex(client.client_restart_lsn)) print("\tClient's sequence number:", client.seq_number) print("Sequence:", lrb.area.seq_number_bits) print("File size:", hex(lrb.area.file_size)) print("-- SNAPSHOT INFO BACKUP --") print("Current LSN:", hex(lrbb.area.current_lsn)) for client in lrbb.clients.clients: print("Client:", client.get_name()) print("\tClient's restart LSN:", hex(client.client_restart_lsn)) print("\tClient's sequence number:", client.seq_number) print("Sequence:", lrbb.area.seq_number_bits) print("File size:", hex(lrbb.area.file_size)) journal = logfile.LogFile(logfile_stream, lrbb) logfile_stream.seek(journal.lcb.system_page_size << 1) pages_file = os.path.join(os.path.dirname(args.file[0]), "pages.txt") with open(pages_file, "w") as pages_stream: pages_stream.write("Page offset;Last LSN;Last end LSN;Flags\n") npages = (journal.lcb.file_size - logfile_stream.tell()) / \ journal.lcb.log_page_size for _ in range(int(npages)): page = logfile_stream.read(journal.lcb.log_page_size) page_header = layout.RecordPageHeader.from_buffer_copy(page) pages_stream.write( "{:>10};{:>18};{:>18};{}\n".format( hex(logfile_stream.tell() - journal.lcb.log_page_size), hex(page_header.copy.last_lsn), hex(page_header.last_end_lsn), hex(page_header.flags))) restart_area = journal.get_client_restart_area("NTFS") print("-- CLIENT RESTART INFO --") print("Version:", "{}.{}".format(restart_area.major_version, restart_area.minor_version)) print("Checkpoint LSN:", hex(restart_area.start_of_checkpoint)) print("Open attributes LSN:", hex(restart_area.open_attr_table_lsn)) print("Attribute names LSN:", hex(restart_area.attr_names_lsn)) print("Dirty pages LSN:", hex(restart_area.dirty_pages_table_lsn)) print("Transaction table LSN:", hex(restart_area.transaction_table_lsn)) pages_file = os.path.join(os.path.dirname(args.file[0]), "working_set_records.txt") with open(pages_file, "w") as records_stream: records_stream.write("""LSN;Previous LSN;Undo next LSN;""" """Redo operation;Undo operation;Transaction\n""") for record, data in journal.records(lrbb.area.current_lsn): client_header = layout.ClientLogHeader.from_buffer_copy(data) records_stream.write( "{:>18};{:>18};{:>18};{};{};{}\n".format( hex(record.this_lsn), hex(record.client_previous_lsn), hex(record.client_undo_next_lsn), layout.LOG_OPERATION.get(client_header.redo_op), layout.LOG_OPERATION.get(client_header.undo_op), record.transaction_id))
""" ESP access point webserver. Aslak Einbu, Jan 2020. """ import os import gc import socket import ure import utime import config import logfile import wifi log = logfile.LogFile("Webserver", config.log_filename, config.log_sizelimit, config.log_level, config.log_print) gc.enable() files_on_chip = os.listdir() mimetypes = { '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.svg': 'image/svg', '.ico': 'image/vnd.microsoft.icon', '.py': 'text/html', '.txt': 'text/css', '.json': 'application/json'