Пример #1
0
def print_log(path='/sd/display.log'):
    sd = SD()
    os.mount(sd, '/sd')

    with open(path, 'r') as logfile:
        for line in logfile:
            print(line, end='')

    os.unmount('/sd')
    sd.deinit()
Пример #2
0
    def __init__(self, debug=False):
        self.cfg = None
        self.rtc = RTC()
        self.debug = debug
        self.battery = Battery()

        # use this pin for debug
        self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP)

        # Empty WDT object
        self.wdt = None

        if not debug:
            if not self.wifi_pin():
                self.wdt = WDT(timeout=20000)
            self.sd = None
        else:
            from machine import SD
            try:
                self.sd = SD()
                mount(self.sd, '/sd')
                self.logfile = open("/sd/display.log", "a")
            except OSError:
                self.sd = None
                self.logfile = None

        self.epd = EPD()

        self.log("Time left on the alarm: %dms" % self.rtc.alarm_left())

        # Don't flash when we're awake outside of debug
        heartbeat(self.debug)
    def __init__(self, rtc):
        self.rtc = rtc

        # Try to access the SD card and make the new path
        try:
            sd = SD()
            os.mount(sd, '/sd')
            self.sensor_file = "/sd/{0}".format(SENSOR_DATA)
            print("INFO: Using SD card for data.")
        except:
            print("ERROR: cannot mount SD card, reverting to flash!")
            self.sensor_file = SENSOR_DATA
        print("Data filename = {0}".format(self.sensor_file))

        # Setup the dictionary for each soil moisture sensor
        adc = ADC(0)
        soil_moisture1 = {
            'sensor': adc.channel(pin='P13', attn=3),
            'power': Pin('P19', Pin.OUT),
            'location': 'Green ceramic pot on top shelf',
            'num': 1,
        }
        soil_moisture2 = {
            'sensor': adc.channel(pin='P14', attn=3),
            'power': Pin('P20', Pin.OUT),
            'location': 'Fern on bottom shelf',
            'num': 2,
        }
        # Setup a list for each sensor dictionary
        self.sensors = [soil_moisture1, soil_moisture2]
        # Setup the alarm to read the sensors
        a = Timer.Alarm(handler=self._read_sensors,
                        s=UPDATE_FREQ,
                        periodic=True)
        print("Plant Monitor class is ready...")
 def __check_file(self, file_path, debug=False):
     if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:
         if file_path[
                 0] == '/' and not 'flash' in file_path and not file_path.split(
                     '/')[1] in os.listdir('/'):
             if self.__sdpath is None:
                 self.__sdpath = file_path.split('/')[1]
                 try:
                     sd = SD()
                     time.sleep(0.5)
                     os.mount(sd, '/{}'.format(self.__sdpath))
                 except Exception as ex:
                     print('Unable to mount SD card!')
                     return False
             else:
                 print('SD card already mounted on {}!'.format(
                     self.__sdpath))
                 return False
     try:
         size = os.stat(file_path)[6]
         if debug: print('File {} has size {}'.format(file_path, size))
         return True
     except Exception as ex:
         print('Exception when checking file {}... wrong file name?'.format(
             file_path))
         print('{}'.format(ex))
         return False
     return False
Пример #5
0
def gnss_task():
    sd_mounted = False

    with thread_list_mutex:
        thread_list[_thread.get_ident()] = 'GNSS'

    # Mount SD if possible
    sd = SD()
    try:
        os.mount(sd, '/sd')
        os.listdir('/sd')
        sd_mounted = True
    except OSError:
        pass
    
    gnss = L76GNSS(py, timeout=5)

    while True:
        coord = gnss.rmc()
        printt(coord)

        # if sd_mounted:
        #     logfile = open('/sd/gnss.txt', 'a')
        #     logfile.write(logstring)
        #     logfile.close()

        time.sleep(2)
    def mountSDCard():
        #MOSI G11 P4 CMD
        #MISO G15 P8 DATA
        #SCK G10 P23 CLOCK
        try:
            oVC0706.uart.stat('/sd')
        except OSError:
            print('Mounting SD Card\n')
            sd = SD()
            sd.init()
            oVC0706.uart.mount(sd, '/sd')
            VC0706.sd = sd
            print('SD Card mounted')
            print('%s\n' % oVC0706.uart.listdir('/sd'))

        print('SD Card mounted')
        print('%s\n' % oVC0706.uart.listdir('/sd'))
Пример #7
0
def setup():
    global logger, rtc, sd, iCAM, iACC, CTLR_IPADDRESS, logfile, filename
    global wdt, ow, temp, py, sensor

    gc.enable()

    # HW Setup
    wdt = WDT(timeout=wdt_timeout)
    sd = SD()
    rtc = RTC()
    os.mount(sd,'/sd')
    # Enable WiFi Antenna
    Pin('P12', mode=Pin.OUT)(True)

    # TEMPERATURE SENSORS: DS18B20 and SI7006A20
    ow = OneWire(Pin('P10'))
    temp = DS18X20(ow)
    py = Pysense()
    sensor = SI7006A20(py)


    # SYSTEM VARIABLES
    iCAM = pycom.nvs_get('iCAM') # pycom.nvs_set('iCAM',1)
    iACC = pycom.nvs_get('iACC') # pycom.nvs_set('iACC',1)

    logfile='/sd/log/{}.log'.format(datetime_string(time.time()))
    logging.basicConfig(level=logging.DEBUG,filename=logfile)
    logger = logging.getLogger(__name__)

    # # NETWORK VARIABLES
    # pbconf = pybytes.get_config()
    # AP = pbconf['wifi']['ssid']
    # if AP == 'wings':
    #     CTLR_IPADDRESS = '192.168.1.51'
    # elif AP == 'RUT230_7714':
    #     CTLR_IPADDRESS = '192.168.1.100'
    #     # CONNECT TO AP
    #     wlan = WLAN(mode=WLAN.STA)
    #     while not wlan.isconnected():
    #         nets = wlan.scan()
    #         for net in nets:
    #             if net.ssid == 'RUT230_7714':
    #                 pybytes.connect_wifi()
    #
        # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
        # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000)
        # while not wlan.isconnected():
        #     machine.idle() # save power while waiting
    socket_client.CTLR_IPADDRESS = CTLR_IPADDRESS

    # GREETING
    logger.info('--------------------')
    logger.info(' Starting CAM{}-ACC{}'.format(iCAM, iACC))
    logger.info('--------------------')
    logger.info('AP={}'.format(AP))
    gc.collect()

    return
Пример #8
0
 def __init__(self, fileName):
     self.fileName = fileName
     # mount
     self.sd = SD()
     os.mount(self.sd, '/sd')
     # rotate if required
     self.rotateIfNeeded(self)
     # open file
     self.f = open(self.fileName, 'w')
Пример #9
0
 def mount(path):
     """
         Mount the SD card.
     """
     if path not in os.listdir("/"):
         try:
             os.mount(SD(), "/" + path)
         except:
             return False
     return True
Пример #10
0
def initialize_sd_card():
    """Try to mount SD card and append /sd/lib to sys.path"""
    global sd
    try:
        sd = SD(pins=('GP10', 'GP11', 'GP15'))
        os.mount(sd, '/sd')
        sys.path.append('/sd/lib')
    except OSError:
        return False
    else:
        return True
Пример #11
0
def save_config(cfg):
    """
    Save out a configuration file
    :param Config cfg: config option
    :return: None
    """
    sd = SD()
    os.mount(sd, '/sd')

    with open("/sd/config.txt", "w") as cfgfile:
        cfgfile.write("Host:%s\n", cfg.host)
        cfgfile.write("WiFi:%s\n", cfg.wifi_ssid)
        cfgfile.write("Pass:%s\n", cfg.wifi_key)
        cfgfile.write("Port:%s\n", cfg.port)
        cfgfile.write("Image:%s\n", cfg.image_path)
        cfgfile.write("Meta:%s\n", cfg.metadata_path)
        if cfg.upload_path:
            cfgfile.write("Up:%s\n", cfg.upload_path)
    os.unmount(sd)
    sd.deinit()
Пример #12
0
    def mount_microSD(self):
        try:
            microSD = SD()
        except OSError:
            return False

        try:
            os.mount(microSD,'/microSD')
        except OSError:
            return False
        return True
Пример #13
0
    def __init__(self):
        self.debug('doing state init')
        #load (or create) a local file
        sd = SD()
        os.mount(sd, '/sd')

        #sigfox setup
        sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1)
        self.sig = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW)
        self.sig.setblocking(False)
        self.sig.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)

        #py = Pytrack()
        #self.gps = L76GNSS(py)

        self.debug('trying to get state from net...')
        try:
            data = {}
            data["order"] = '-createdAt'
            data["limit"] = '1'
            headers = {
                'X-Parse-Application-Id': PARSE_APPLICATION_ID,
                'X-Parse-REST-API-Key': PARSE_REST_API_KEY,
                'Content-Type': 'application/json'
            }
            self.debug('sending request.')
            resp = urequests.get(PARSE_BASE_URL + '/classes/ConfigObject',
                                 headers=headers,
                                 data=ujson.dumps(data))
            config = resp.json()
            resp.close()
            self.debug('got state from net:')
            self.debug(ujson.dumps(config))
            self.write_config(config["results"][0])

        except:
            self.debug('could not get state from net.')
            try:
                f = open('/sd/config.json', 'r')
                config = f.read()
                f.close()
                if config == '':
                    self.debug('found invalid local json file, writing...')
                    config = {}
                    config["state"] = 0
                    self.write_config(config)
                else:
                    self.debug('found valid local json file:')
                    self.debug(config)
                    self.config = ujson.loads(config)
            except:
                self.debug('ERROR - could not get/create a valid config file!')
                pass
Пример #14
0
def setup():
    global wdt, sd, logger, AP, pin_relay_AP, pin_relay_LED, pin_switch_setupMode, pin_switch_RPi, wdt

    # Logger
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    logger.info('===========================')
    logger.info(' Starting CTLR ')
    logger.info('===========================')

    # HW Setup
    wdt = WDT(timeout=20 * 60 * 100)
    sd = SD()
    os.mount(sd, '/sd')

    pin_relay_AP = Pin('P20', mode=Pin.OUT, pull=Pin.PULL_DOWN)
    pin_relay_LED = Pin('P19', mode=Pin.OUT, pull=Pin.PULL_DOWN)
    pin_switch_setupMode = Pin('P9', mode=Pin.IN, pull=Pin.PULL_DOWN)
    pin_switch_RPi = Pin('P7', mode=Pin.OUT, pull=Pin.PULL_DOWN)

    # Network Setup
    # CHANGE AP IN pybytes_config.json!
    pbconfig = pybytes.get_config()
    AP = pbconfig['wifi']['ssid']

    # WIFI Connection
    if AP == 'RUT230_7714':
        pin_relay_AP.value(1)
        wlan = WLAN(mode=WLAN.STA)
        while not wlan.isconnected():
            nets = wlan.scan()
            for net in nets:
                if net.ssid == 'RUT230_7714':
                    pybytes.connect_wifi()
        # # No Internet Case
        # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
        # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000)
        # while not wlan.isconnected():
        #     machine.idle() # save power while waiting

    socket_svr.setup()
    # _thread.stack_size(16384)
    _thread.start_new_thread(socket_svr.accept_thread, ())

    # UPDATE TIME BY GPS
    logger.info('GPS time fixing start...')
    shmGPSclock.update_RTC_from_GPS()
    socket_svr.var_lock.acquire()
    socket_svr.state = 1
    socket_svr.var_lock.release()
    logger.info('GPS time fixing done...')
Пример #15
0
    def load(debug=False, sd=None):
        """
         Load off SD our AP, pw, and URL details
        :param debug: Logging
        :param sd: SD object if mounted already
        :return: Config object
        """
        from machine import SD
        cfg = None
        try:
            unmount = False
            if sd is None:
                sd = SD()
                os.mount(sd, '/sd')
                unmount = True

            cfg = Config.load_file(open(Config.SD_CONFIG_PATH,"r"), debug)

            if unmount:
                try:
                    os.unmount('/sd') # got renamed in upy 1.9
                except AttributeError:
                    os.umount('/sd')
                sd.deinit()
                del sd
        except OSError:
            print("Can't open config file SD card")

        if not cfg:
            cfg = Config.load_file(open(Config.FLASH_CONFIG_PATH, "r"), debug)
            if not cfg:
                raise ValueError("No config file!")
            print("Loaded from flash")
            cfg.src = "flash"
        else:
            print("Loaded from SD card")
            cfg.src = "sd"
        return cfg
Пример #16
0
    def __init__(self, dir="/sd/hiverizelog"):
        self.dir = dir
        # Mount SD
        # Pins are Dat0: P8, SCLK: P23, CMD: P4, at least I think so
        # Apparently Pins can not be changed
        sd = SD()
        os.mount(sd, '/sd')

        # Check if directory, eg. hiverizelog, was already created,
        # and create it, if not existing:
        try:
            os.listdir(dir)
        except OSError:
            os.mkdir(dir)
        print("Init -> CSV logger in directory " + dir)
Пример #17
0
def mount_sd():
    from machine import SD
    sd = SD()
    # raises "OSError: the requested operation failed" on PyJTAG
    import os
    try:
        os.mount(sd, '/sd')
    except Exception as e:
        if os.stat('/sd'):
            # should be ok, probably previously mounted
            pass
        else:
            print("Exception while trying to mount:", e)
    os.chdir('/sd')
    print('/sd :', os.listdir())
Пример #18
0
def initialize_sd_card():
    """Try to mount SD card and append /sd/lib to sys.path"""
    global sd
    log = ulog.Logger('SD: ')
    try:
        log.info('preparing SD card')
        sd = SD(pins=('GP10', 'GP11', 'GP15'))
        os.mount(sd, '/sd')
        sys.path.append('/sd/lib')
    except OSError:
        log.info('no card found!')
        return False
    else:
        log.info('mounted to /sd')
        return True
Пример #19
0
def setup():
    global logger, rtc, sd, iCAM, iACC, CTLR_IPADDRESS, logfile, filename
    global wdt

    gc.enable()

    # HW Setup
    wdt = WDT(timeout=wdt_timeout)
    sd = SD()
    rtc = RTC()
    os.mount(sd, '/sd')

    # SYSTEM VARIABLES
    iCAM = pycom.nvs_get('iCAM')  # pycom.nvs_set('iCAM',1)
    iACC = pycom.nvs_get('iACC')  # pycom.nvs_set('iACC',1)

    logfile = '/sd/log/{}.log'.format(datetime_string(time.time()))
    logging.basicConfig(level=logging.DEBUG, filename=logfile)
    logger = logging.getLogger(__name__)

    # NETWORK VARIABLES
    pbconf = pybytes.get_config()
    AP = pbconf['wifi']['ssid']
    if AP == 'wings':
        CTLR_IPADDRESS = '192.168.1.51'
    elif AP == 'RUT230_7714':
        CTLR_IPADDRESS = '192.168.1.100'
        # CONNECT TO AP
        wlan = WLAN(mode=WLAN.STA)
        while not wlan.isconnected():
            nets = wlan.scan()
            for net in nets:
                if net.ssid == 'RUT230_7714':
                    pybytes.connect_wifi()
        # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
        # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000)
        # while not wlan.isconnected():
        #     machine.idle() # save power while waiting
    socket_client.CTLR_IPADDRESS = CTLR_IPADDRESS

    # GREETING
    logger.info('--------------------')
    logger.info(' Starting CAM{}-ACC{}'.format(iCAM, iACC))
    logger.info('--------------------')
    logger.info('AP={}'.format(AP))
    gc.collect()

    return
Пример #20
0
 def __init__(self, deviceID):
     DataWriter.sd = SD()
     DataWriter.rtc = RTC()
     os.mount(DataWriter.sd, '/sd')
     DataWriter.deviceID = deviceID
     now = DataWriter.rtc.now()
     DataWriter.year = now[0]
     DataWriter.month = now[1]
     DataWriter.day = now[2]
     DataWriter.dataFile = str(
         DataWriter.deviceID) + '_Fluxbot_Data_' + str(
             DataWriter.month) + '.' + str(DataWriter.day) + "." + str(
                 DataWriter.year) + '.csv'
     DataWriter.logFile = str(DataWriter.deviceID) + '_bootLog.csv'
     DataWriter.isMounted = True
     DataWriter.dataBuffer = []
Пример #21
0
def log_to_SD():
    t = rtc.now()
    ts = '{:04d}/{:02d}/{:02d} {:02d}:{:02d}:{:02d}'.format(
        t[0], t[1], t[2], t[3], t[4], t[5])
    stats = lora.stats()
    print(stats)
    try:
        sd = SD()
        os.mount(sd, '/sd')
        print("Logging to: {}".format(
            '/sd/{eui}.csv'.format(eui=my_config_dict['dev_eui'][-8:])))
        with open('/sd/{eui}.csv'.format(eui=my_config_dict['dev_eui'][-8:]),
                  'a') as output:
            output.write(ts + ",{counter},".format(counter=stats.tx_counter) +
                         ",".join(str(x) for x in float_values) + "\n")
    except Exception as ex:
        print("Error writing to SD: ", ex)
Пример #22
0
def sd_access():
    """ Function to access to SD.

    Returns
    -------
        sd: obj
            initialized sd object
    """
    try:
        sd = SD()

    except OSError as e:
        print("Error: {}. SD card not found".format(e))
        while True:
            blink_led(1, 500, led_red)

    os.mount(sd, sd_mount_dir)
    return sd
Пример #23
0
    def __init__(self,
                 name,
                 level=NOTSET,
                 filename=None,
                 maxfilesize=MAXNUMBEROFCHARACTERS):
        global _sd
        self.level = level
        self.name = name
        self.filename = filename
        self.numberOfCharacterWritten = 0
        self.currentIndex = 0
        self.lasttimestampsd = None
        self.maxfilesize = maxfilesize
        #read the size of the file
        try:
            if (self.filename != None):
                self.numberOfCharacterWritten = uos.stat(
                    self.getCurrentLogFileName())[6]
                if self.numberOfCharacterWritten > self.maxfilesize:
                    self.currentIndex = 1  # we must have been working from the next index log
                    self.numberOfCharacterWritten = uos.stat(
                        self.getCurrentLogFileName())[6]

        except:
            pass

        #try to mount the SD card if present
        try:
            if (self.filename != None and _sd == None):
                _sd = SD()
                uos.mount(_sd, '/sd')
        except:
            with log_lock:
                print("No SD card present")
            pass
        with log_lock:
            print(self.name + " logging to " + (self.getCurrentLogFileName()))
Пример #24
0
wlan = WLAN()
wlan.deinit()

# Disable the heartbeat LED and set to orange to indicate startup
pycom.heartbeat(False)
pycom.rgbled(0x552000)

# Try to mount SD card, if this fails, keep blinking red and do not proceed
try:
    import os
    import time
    from loggingpycom import DEBUG
    from LoggerFactory import LoggerFactory
    from userbutton import UserButton

    os.mount(SD(), "/sd")

    logger_factory = LoggerFactory()
    status_logger = logger_factory.create_status_logger(
        "status_logger",
        level=DEBUG,
        terminal_out=True,
        filename="status_log.txt")

    # Initialise button interrupt on pin 14 for user interaction
    user_button = UserButton(status_logger)
    pin_14 = Pin("P14", mode=Pin.IN, pull=Pin.PULL_DOWN)
    pin_14.callback(Pin.IRQ_RISING | Pin.IRQ_FALLING,
                    user_button.button_handler)

except Exception as e:
Пример #25
0
def mount_sd():
    sd = SD()
    os.mount(sd, '/sd/')
    return os.listdir('/sd')
Пример #26
0
from machine import SD
import os

sd = SD()
os.mount(sd, '/sd')

# check the content
os.listdir('/sd')

# try some standard file operations
f = open('/sd/test.txt', 'w')
f.write('Testing SD card write operations 5')
f.close()
f = open('/sd/test.txt', 'r')
print(f.read())
f.close()
Пример #27
0
def sd_setup():
    try:
        sd = SD()
        os.mount(sd, '/sd')
        print("SD card mounted")
        # try:
        #     os.remove('/sd/www/leader_mesh_list.txt')
        # except:
        #     print('did not delete')
        try:
            f = open('/sd/www/ack_log.txt', 'r')
            print("Already a ACK log, trimmed to last 100 ACKs")
            acks = f.readlines()
            f.close()
            os.remove('/sd/www/ack_log.txt')
            n = open('/sd/www/ack_log.txt', 'w+')
            for i in acks[-50:]:
                n.write(i)
            n.close()
        except:
            try:
                os.mkdir('/sd/www')
                f = open('/sd/www/ack_log.txt', 'w+')
                f.write("ACK log:\n")
            except:
                f = open('/sd/www/ack_log.txt', 'w+')
                f.write("ACK log:\n")
            print("ACK Log created")
        f.close()

        try:
            f = open('/sd/www/status_log.txt', 'r')
            print("Already a status log, trimmed to last 100 entries.")
            status = f.readlines()
            f.close()
            os.remove('/sd/www/status_log.txt')
            n = open('/sd/www/status_log.txt', 'w+')
            for i in status[-50:]:
                n.write(i)
            n.close()
        except:
            try:
                os.mkdir('/sd/www')
                f = open('/sd/www/status_log.txt', 'w+')
                f.write("Status log:\n")
            except:
                f = open('/sd/www/status_log.txt', 'w+')
                f.write("Status log:\n")
            print("Status Log created")
        f.close()

        try:
            f = open('/sd/www/chat.txt', 'r')
            print("Already a chat log, trimmed to last 100 entries.")
            chats = f.readlines()
            f.close()
            os.remove('/sd/www/chat.txt')
            n = open('/sd/www/chat.txt', 'w+')
            for i in chats[-50:]:
                n.write(i)
            n.close()
        except:
            try:
                os.mkdir('/sd/www')
                f = open('/sd/www/chat.txt', 'w+')
                f.write("Chat log:\n")
            except:
                f = open('/sd/www/chat.txt', 'w+')
                f.write("Chat log:\n")
            print("chat Log created")
        f.close()

        try:
            f = open('/sd/www/wschat.html', 'r')
            print("Chat is on SD card")
            c = open('/flash/www/wschat.html', 'r')
            count_of_f = len(f.read())
            count_of_c = len(c.read())
            f.close()
            c.close()
            print("Check if wschat has changed")
            if count_of_c != count_of_f:
                os.remove('/sd/www/wschat.html')
                copy('/flash/www/wschat.html', '/sd/www/wschat.html')
                print("Copied new wshchat")

        except:
            copy('/flash/www/wschat.html', '/sd/www/wschat.html')
            print("WSChat now on SD card")

        try:
            f = open('/sd/www/index.html', 'r')
            c = open('/flash/www/index.html', 'r')
            count_of_f = len(f.read())
            count_of_c = len(c.read())
            c.close()
            f.close()
            print("Did the index change?")
            if count_of_c != count_of_f:
                os.remove('/sd/www/index.html')
                copy('/flash/www/index.html', '/sd/www/index.html')
                print("copied new index")
        except:
            copy('/flash/www/index.html', '/sd/www/index.html')
            print("Index now on SD card")

        try:
            f = open('/sd/www/style.css', 'r')
            print("Style is already on SD card")
            f.close()
        except:
            copy('/flash/www/style.css', '/sd/www/style.css')
            print("Style now on SD card")

        try:
            print("Check Node Config status")
            f = open('/sd/www/node_config.txt', 'r')
            f.close()
            print("Node Config is on SD Card")

        except:
            try:
                os.mkdir('/sd/www')
                copy('/flash/node_config.txt', '/sd/www/node_config.txt')
                print("Node config is now on SD card")
            except:
                copy('/flash/node_config.txt', '/sd/www/node_config.txt')
                print("Node config is now on SD card")

        # try:
        #     print("Check Pymesh Config status")
        #     f = open('/sd/www/pymesh_config.json', 'r')
        #     f.close()
        #     print("Pymesh Config is on SD Card")
        #
        #
        # except:
        #         copy('/flash/pymesh_config.json', '/sd/www/pymesh_config.json')
        #         print("Pymesh config is now on SD card")

        try:
            print("Check Leader Mesh list status")
            f = open('/sd/www/leader_mesh_list.txt', 'r')
            f.close()
            print("Leader Mesh list is on SD Card")

        except:
            copy('/flash/lib/leader_mesh_list.txt',
                 '/sd/www/leader_mesh_list.txt')
            print("Leader Mesh list is now on SD card")

        try:
            f = open('/sd/www/sms.txt', 'r')
            print("Already a SMS log, trimmed to last 100 SMSs")
            sms = f.readlines()
            f.close()
            os.remove('/sd/www/sms.txt')
            n = open('/sd/www/sms.txt', 'w+')
            for i in sms[-50:]:
                n.write(i)
            n.close()
        except:
            try:
                os.mkdir('/sd/www')
                f = open('/sd/www/sms.txt', 'w+')
                f.write("SMS log:\n")
            except:
                f = open('/sd/www/sms.txt', 'w+')
                f.write("SMS log:\n")
            print("SMS Log created")
        f.close()

    except:
        print("SD card not loaded, chat not saved")
Пример #28
0
class Display(object):
    IMG_DIR = '/flash/imgs'

    def __init__(self, debug=False):
        self.cfg = None
        self.rtc = RTC()
        self.debug = debug
        self.battery = Battery()

        # use this pin for debug
        self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP)

        # Empty WDT object
        self.wdt = None

        if not debug:
            if not self.wifi_pin():
                self.wdt = WDT(timeout=20000)
            self.sd = None
        else:
            from machine import SD
            try:
                self.sd = SD()
                mount(self.sd, '/sd')
                self.logfile = open("/sd/display.log", "a")
            except OSError:
                self.sd = None
                self.logfile = None

        self.epd = EPD()

        self.log("Time left on the alarm: %dms" % self.rtc.alarm_left())

        # Don't flash when we're awake outside of debug
        heartbeat(self.debug)

    def log(self, msg, end='\n'):
        time = "%d, %d, %d, %d, %d, %d" % self.rtc.now()[:-2]
        msg = time + ", " + msg
        if self.logfile:
            self.logfile.write(msg + end)
        print(msg, end=end)

    def feed_wdt(self):
        if self.wdt:
            self.wdt.feed()

    def connect_wifi(self):
        from network import WLAN

        if not self.cfg:
            raise ValueError("Can't initialise wifi, no config")

        self.log('Starting WLAN, attempting to connect to ' + ','.join(self.cfg.wifi.keys()))
        wlan = WLAN(0, WLAN.STA)
        wlan.ifconfig(config='dhcp')
        while not wlan.isconnected():
            nets = wlan.scan()
            for network in nets:
                if network.ssid in self.cfg.wifi.keys():
                    self.log('Connecting to ' + network.ssid)
                    self.feed_wdt() # just in case
                    wlan.connect(ssid=network.ssid, auth=(network.sec, self.cfg.wifi[network.ssid]))
                    while not wlan.isconnected():
                        idle()
                    break

            self.feed_wdt() # just in case
            sleep_ms(2000)

        self.log('Connected as %s' % wlan.ifconfig()[0])

    @staticmethod
    def reset_cause():
        import machine
        val = machine.reset_cause()
        if val == machine.POWER_ON:
            return "power"
        elif val == machine.HARD_RESET:
            return "hard"
        elif val == machine.WDT_RESET:
            return "wdt"
        elif val == machine.DEEPSLEEP_RESET:
            return "sleep"
        elif val == machine.SOFT_RESET:
            return "soft"

    def set_alarm(self, now, json_metadata):
        import json
        json_dict = json.loads(json_metadata)

        # Now we know the time too
        self.rtc = RTC(datetime=now)
        list_int = json_dict["wakeup"][:6]
        time_str = ",".join([str(x) for x in list_int])

        self.log("Setting alarm for " + time_str)
        self.rtc.alarm(time=tuple(list_int))

        if self.rtc.alarm_left() == 0:
            self.log("Alarm failed, setting for +1 hour")
            self.rtc.alarm(time=3600000)

        del json

    def display_file_image(self, file_obj):
        towrite = 15016
        max_chunk = 250
        while towrite > 0:
            c = max_chunk if towrite > max_chunk else towrite
            buff = file_obj.read(c)
            self.epd.upload_image_data(buff, delay_us=2000)
            self.feed_wdt()
            towrite -= c

        self.epd.display_update()

    def display_no_config(self):
        self.log("Displaying no config msg")
        with open(Display.IMG_DIR + '/no_config.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_low_battery(self):
        self.log("Displaying low battery msg")
        with open(Display.IMG_DIR + '/low_battery.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_cannot_connect(self):
        self.log("Displaying no server comms msg")
        with open(Display.IMG_DIR + '/no_server.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_no_wifi(self):
        self.log("Displaying no wifi msg")
        with open(Display.IMG_DIR + '/no_wifi.bin', 'rb') as pic:
            self.display_file_image(pic)

    def check_battery_level(self):
        now_batt = 200
        last_batt = self.battery.battery_raw()
        while now_batt > last_batt:
            sleep_ms(50)
            last_batt = now_batt
            self.feed_wdt()
            now_batt = self.battery.battery_raw()
            self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw()))

        if not self.battery.safe():
            self.log("Battery voltage (%d) low! Turning off" % self.battery.battery_raw())
            self.feed_wdt()
            self.display_low_battery()
            return False
        else:
            self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw()))
        return True

    def run_deepsleep(self):

        if not self.run():
            # RTC wasn't set, try to sleep forever
            self.rtc.alarm(time=2000000000)

        # Set the wakeup (why do it earlier?)
        rtc_i = self.rtc.irq(trigger=RTC.ALARM0, wake=DEEPSLEEP)

        self.log("Going to sleep, waking in %dms" % self.rtc.alarm_left())

        # Close files on the SD card
        if self.sd:
            self.logfile.close()
            self.logfile = None
            unmount('/sd')
            self.sd.deinit()

        # Turn the screen off
        self.epd.disable()

        if not self.wifi_pin():
            # Basically turn off
            deepsleep()
        else:
            self.log("DEBUG MODE: Staying awake")
            pass
            # Do nothing, allow network connections in

    def run(self):

        woken = self.wifi_pin()
        self.epd.enable()

        if not self.check_battery_level():
            return False

        try:
            self.epd.get_sensor_data()
        except ValueError:
            self.log("Can't communicate with display, flashing light and giving up")
            heartbeat(True)
            sleep_ms(15000)
            return True

        if self.rtc.alarm_left() > 0:
            self.log("Woken up but the timer is still running, refreshing screen only")
            self.epd.display_update()
            self.feed_wdt()
            return True

        try:
            self.cfg = Config.load(sd=self.sd)
            self.log("Loaded config")
        except (OSError, ValueError) as e:
            self.log("Failed to load config: " + str(e))
            self.display_no_config()
            try:
                self.connect_wifi()
            except:
                pass # everything

            while True:
                sleep_ms(10)
                self.feed_wdt()

        self.feed_wdt()

        self.connect_wifi()

        content = b''
        try:
            self.log("Connecting to server %s:%d" % (self.cfg.host, self.cfg.port))
            c = Connect(self.cfg.host, self.cfg.port, debug=self.debug)

            self.feed_wdt()

            cause = Display.reset_cause()
            if woken:
                cause = "user"

            self.log("Reset cause: " + cause)

            if len(self.cfg.upload_path) > 0:
                temp = self.epd.get_sensor_data() # we read this already
                c.post(self.cfg.upload_path,
                       battery=self.battery.value(),
                       reset=cause,
                       screen=temp)

            self.log("Fetching metadata from " + self.cfg.metadata_path)
            metadata = c.get_quick(self.cfg.metadata_path, max_length=1024, path_type='json')

            # This will set the time to GMT, not localtime
            self.set_alarm(c.last_fetch_time, metadata)

            self.feed_wdt()
            del metadata
            del self.battery
            self.log("Fetching image from " + self.cfg.image_path)
            self.epd.image_erase_frame_buffer()
            self.feed_wdt()

            length, socket = c.get_object(self.cfg.image_path)

            if length != 15016:
                raise ValueError("Wrong data size for image: %d" % length)

            self.feed_wdt()

        except (RuntimeError, ValueError, OSError) as e:
            self.log("Failed to get remote info: " + str(e))
            self.display_cannot_connect()
            self.rtc.alarm(time=3600000)
            return True

        sleep_ms(1000) # How do we make the write to display more reliable?
        self.feed_wdt()
        self.log("Uploading to display")
        self.display_file_image(socket)
        c.get_object_done() # close off socket

        if self.cfg.src == "sd":
            # If we've got a working config from SD instead of flash
            self.log("Transferring working config")
            Config.transfer()
            self.log("SUCCESS")

        self.log("Finished. Mem free: %d" % gc.mem_free())
        return True
from machine import Pin
power_pin = Pin("GP6", Pin.OUT)
power_pin(1)

dac_reset_pin = Pin("GP7", Pin.OUT)
dac_reset_pin(1)

green_led_pin = Pin("GP25", Pin.OUT)
green_led_pin(1)

blue_led_pin = Pin("GP24", Pin.OUT)
#blue_led_pin(1) #is always on - can't be switched

from machine import Timer
timer1 = Timer(1, mode=Timer.PWM, width=16)

timer1a = timer1.channel(Timer.A, freq=1000,
                         duty_cycle=5000)  #Green LED PWM 50%
timer1b = timer1.channel(Timer.B, freq=1000,
                         duty_cycle=5000)  #Red LED PWM 50% - doesn't work

from machine import SD
sd = SD(pins=('GP10', 'GP11',
              'GP9'))  #won't work Error 5 EIO - SD has no voltage?!
Пример #30
0
    0,
]

pycom.heartbeat(False)  #arrete clignotement led bleue

if configuration in (101, 106, 110, 120, 130, 201, 206, 306):
    print('ok configuration : ', configuration)
[]

if configuration == 101:  # ON VA CONFIGURER LE RX il y a 0 capteurs sur le RX; il y a six capteurs 20 kg sur le TX;   PAS TESTE                  la trame reçue fait 37 octets : 1 [label] + 1 [numero_trame] +1 [T]+24 [6 long]+10 delimiteur
    lora = LoRa(mode=LoRa.LORA, frequency=863000000)
    s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    s.setblocking(False)
    i = 0
    if carte_sd == 2:
        sd = SD()
        os.mount(sd, '/sd')
    while True:
        i = i + 1
        trame_ch = s.recv(128)
        print(trame_ch, '   ', i)
        time.sleep(2)
        pycom.rgbled(0x007700)
        if trame_ch:  #      trame=delimiteur+label+delimiteur+str(numero_trame)+delimiteur+str(t)+trame+delimiteur+"\n"
            time.sleep(2)
            pycom.rgbled(0x660000)
            trame_ch = trame_ch.decode(
                'utf-8')  #sinon pbs compatibilité avec binaire?
            trame = trame_ch.split(
                delimiteur
            )  #on vire le delimiteur et on met les data dans une liste
Пример #31
0
pycom.rgbled(green)
print("Starting with lora...")
lora = LoRa(mode=LoRa.LORA,
            rx_iq=True,
            region=LoRa.EU868,
            frequency=freqs[7],
            power_mode=LoRa.ALWAYS_ON,
            bandwidth=LoRa.BW_125KHZ,
            sf=12)
lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
lora_sock.setblocking(False)
stats = []
detailed_stats = []
run_stats = 1
sd = SD()  # remove those lines if you don't use an SD card
os.mount(sd, '/sd')


def receive_stats():
    global stats
    global detailed_stats
    global sd
    global run_stats
    print("Ready to accept stats!")
    while (run_stats == 1):
        recv_pkg = lora_sock.recv(250)
        if (len(recv_pkg) > 2):
            recv_pkg_len = recv_pkg[1]
            recv_pkg_id = recv_pkg[0]
            if (recv_pkg_len > 10):
Пример #32
0
'''
os module test for the CC3200 based boards
'''

from machine import SD
import os

mch = os.uname().machine
if 'LaunchPad' in mch:
    sd_pins = ('GP16', 'GP17', 'GP15')
elif 'WiPy' in mch:
    sd_pins = ('GP10', 'GP11', 'GP15')
else:
    raise Exception('Board not supported!')

sd = SD(pins=sd_pins)

os.mount(sd, '/sd')
os.mkfs('/sd')
os.chdir('/flash')
print(os.listdir())

os.chdir('/sd')
print(os.listdir())

# create a test directory in flash
os.mkdir('/flash/test')
os.chdir('/flash/test')
print(os.getcwd())
os.chdir('..')
print(os.getcwd())
Пример #33
0
'''
os module test for the CC3200 based boards
'''

from machine import SD
import os

mch = os.uname().machine
if 'LaunchPad' in mch:
    sd_pins = ('GP16', 'GP17', 'GP15')
elif 'WiPy' in mch:
    sd_pins = ('GP10', 'GP11', 'GP15')
else:
    raise Exception('Board not supported!')

sd = SD(pins=sd_pins)

os.mount(sd, '/sd')
os.mkfs('/sd')
os.chdir('/flash')
print(os.listdir())

os.chdir('/sd')
print(os.listdir())

# create a test directory in flash
os.mkdir('/flash/test')
os.chdir('/flash/test')
print(os.getcwd())
os.chdir('..')
print(os.getcwd())
Пример #34
0
 def __init__(self):
     self.sd = SD()
     os.mount(self.sd, '/sd/')
     print(os.listdir())
Пример #35
0
    f.close()

    stat = os.stat("test/file")
    print(fs_text + " type of a file: " + str(stat[0]))  # File type
    print(fs_text + "size of the file: " + str(stat[6]))  # File size in bytes

    os.remove("test/file")

    #Expected: ENOENT - 2
    try:
        os.stat("inv_file")
    except OSError as e:
        print(fs_text + "os.stat(\"inv_file\") - " + repr(e))


sd = SD()
sd_fat_fs = os.mkfat(sd)
os.mount(sd_fat_fs, "/sd")

#Test mkdir
mkdir_test("LittleFs", "/flash")
mkdir_test("FatFs", "/sd")

#Test chdir and getcwd
getcwd_chdir_test("LittleFs", "/flash")
getcwd_chdir_test("FatFs", "/sd")

#Test listdir, rmdir and remove
os.chdir("/flash/test")
list_files_folders_test("LittleFs")
remove_files_folders_test("LittleFs")
Пример #36
0
def run(file_path, baudrate, port=None, resume=False):
    global sysname

    abort = True
    s = None

    print('<<< Welcome to the SQN3330 firmware updater >>>')

    if 'FiPy' in sysname or 'GPy' in sysname:
        if '/sd' in file_path and not 'sd' in os.listdir('/'):
            sd = SD()
            time.sleep(0.5)
            os.mount(sd, '/sd')
            time.sleep(0.5)

        if 'GPy' in sysname:
            pins = ('P5', 'P98', 'P7', 'P99')
        else:
            pins = ('P20', 'P18', 'P19', 'P17')

        s = UART(1, baudrate=baudrate, pins=pins, timeout_chars=100)
        s.read()
    else:
        if port is None:
            raise ValueError('serial port not specified')
        s = serial.Serial(port,
                          baudrate=921600,
                          bytesize=serial.EIGHTBITS,
                          timeout=0.1)
        s.reset_input_buffer()
        s.reset_output_buffer()

    blobsize = os.stat(file_path)[6]
    blob = open(file_path, "rb")

    if not resume:
        # disable echo
        s.write(b"ATE0\r\n")
        response = read_rsp(s, size=6)

        s.read(100)
        print('Entering recovery mode')
        s.write(b"AT+SMSWBOOT=3,0\r\n")
        response = read_rsp(s, size=6)
        if b'OK' in response:
            print('Resetting.', end='', flush=True)
            s.write(b'AT^RESET\r\n')
            wait_for_modem(s, send=False, expected=b'+SHUTDOWN')
            time.sleep(2)
            wait_for_modem(s)
            s.write(b"AT\r\n")
            s.write(b"AT\r\n")
        else:
            raise OSError('AT+SMSWBOOT=3,0 failed!')

    time.sleep(1)
    s.read()

    print('Starting STP (DO NOT DISCONNECT POWER!!!)')
    s.read(100)
    s.write(b'AT+SMSTPU=\"ON_THE_FLY\"\r\n')
    response = read_rsp(s, size=4)
    if response != b'OK\r\n' and response != b'\r\nOK' and response != b'\nOK':
        raise OSError("Invalid answer '%s' from the device" % response)
        blob.close()

    s.read()
    try:
        stp.start(blob, blobsize, s, baudrate, AT=False)
        print('Code download done, returning to user mode')
        abort = False
    except:
        blob.close()
        print('Code download failed, aborting!')
        abort = True

    time.sleep(1.5)
    s.read()
    s.write(b"AT+SMSWBOOT=1,0\r\n")
    response = read_rsp(s, size=6)

    print('Resetting (DO NOT DISCONNECT POWER!!!).', end='', flush=True)
    time.sleep(1.5)
    s.write(b"AT^RESET\r\n")
    wait_for_modem(s, send=False, expected=b'+SHUTDOWN')
    time.sleep(2)
    wait_for_modem(s, send=False, expected=b'+SYSSTART')

    if not abort:
        time.sleep(0.5)
        print('Deploying the upgrade (DO NOT DISCONNECT POWER!!!)...')
        s.write(b"AT+SMUPGRADE\r\n")
        response = read_rsp(s, size=6, timeout=120000)

        print('Resetting (DO NOT DISCONNECT POWER!!!).', end='', flush=True)
        time.sleep(1.5)
        s.write(b"AT^RESET\r\n")
        wait_for_modem(s, send=False, expected=b'+SHUTDOWN')
        time.sleep(2)
        wait_for_modem(s, send=False, expected=b'+SYSSTART')
        s.write(b"AT\r\n")
        s.write(b"AT\r\n")
        time.sleep(0.5)
        s.read()
        print('Upgrade completed!')
        print("Here's the current firmware version:")
        time.sleep(0.5)
        s.read()
        s.write(b"ATI1\r\n")
        response = read_rsp(s, size=100)
        print_pretty_response(response)
Пример #37
0
 def mount(path='/sd'):
     """ Mount a sd card to specified path """
     from machine import SD
     sd = SD()
     os.mount(sd, path)
Пример #38
0
'''
SD card test for the CC3200 based boards.
'''

from machine import SD
import os

mch = os.uname().machine
if 'LaunchPad' in mch:
    sd_pins = ('GP16', 'GP17', 'GP15')
elif 'WiPy' in mch:
    sd_pins = ('GP10', 'GP11', 'GP15')
else:
    raise Exception('Board not supported!')

sd = SD(pins=sd_pins)
print(sd)
sd.deinit()
print(sd)
sd.init(sd_pins)
print(sd)

sd = SD(0, pins=sd_pins)
sd = SD(id=0, pins=sd_pins)
sd = SD(0, sd_pins)

# check for memory leaks
for i in range(0, 1000):
    sd = sd = SD(0, pins=sd_pins)

# next ones should raise