예제 #1
0
def nvs_transmit():
	while True:
		time.sleep(5)
		try:
			os.stat('data.dat')
			exists = True
		except:
			exists = False
	
		if exists:
		
			gc.collect() 
			gc.mem_free()
			p0 = int(pycom.nvs_get('p0'))
			p1 = int(pycom.nvs_get('p1'))
			pycom.nvs_set('t', p1)

			if p1 > p0:	
			
				print (p0)
				print (p1)
				f1 = open('data.dat', 'rb')
				f1.seek(p0)
				payload = binascii.hexlify(f1.read(p1-p0))
				print(payload)
				f1.close()		
				sendATcommandPOST(payload)
				print("Transmission completed")
예제 #2
0
def make_payload():
    pycom.rgbled(blue)
    #distance = distance_median()
    count = pycom.nvs_get('dist')
    utime.sleep_us(100)
    #randomize water distance
    distance = os.urandom(1)[0]
    print("distance = {0} inches".format(distance))
    utime.sleep_ms(100)
    #subract 0.1V from battery voltage every 5 counts
    c = count
    v = pycom.nvs_get('v')
    if c % 5 == 0:
        v += 1
        pycom.nvs_set('v', v)
    print("v={0}".format(v))
    voltage = 4.0 - v * 0.1
    print("Measured Voltage: {0}V".format(voltage))
    #randomize flow rate
    x = os.urandom(1)[0]
    flow_rate = x % 4
    if (flow_rate < 3):
        print(flow_rate)
    else:
        flow_rate -= 1
        print(flow_rate)
    print("Flow Rate: {0}".format(flow_rate))
    #generate encoded packet to send to webapp
    full_packet = ustruct.pack('f', count) + ustruct.pack(
        'f', float(distance)) + ustruct.pack('f', voltage) + ustruct.pack(
            'f', float(flow_rate))
    return full_packet
예제 #3
0
 def checkRolloutSuccess(self):
     # Check if the previous rollout was successful if it exists
     try:
         print("....Checking rollout success state....")
         if pycom.nvs_get("rolloutid"):
             print(pycom.nvs_get("rolloutid"))
             myobj = {}
             myobj["mac"] = ubinascii.hexlify(machine.unique_id(),
                                              ':').decode()
             myobj["firmware_version"] = "1.0.0"
             myobj["rollout_id"] = pycom.nvs_get("rolloutid")
             headers = {
                 "Content-Type": "application/json",
                 "x-access-token": self.authToken
             }
             x = post(config.checkRolloutSuccess,
                      json=myobj,
                      headers=headers)
             # print(x.text)
             # firmware_version = x.json()
             # More work required
         else:
             print("No rollout exists")
     except Exception as e:
         print("Failed to check rollout success: ", e)
    def test_pycom_nv_set_get(self):
        pycom.nvs_set("test_key_asdf", 1234)
        val = pycom.nvs_get("test_key_asdf")
        self.assertEqual(val, 1234)

        pycom.nvs_set("test_key_asdf", 5678)
        val = pycom.nvs_get("test_key_asdf")
        self.assertEqual(val, 5678)
예제 #5
0
def aggregate():
    try:
        pycom.nvs_set('val', int(pycom.nvs_get('val')) + 1)
    except:
        pycom.nvs_set('val', 0)
    print('Deepsleep Remaining: ' + str(machine.remaining_sleep_time()))
    print('New Aggregate: ' + str(pycom.nvs_get('val')))
    print('Current Message ID: ' + str(pycom.nvs_get('msgID')))
예제 #6
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
예제 #7
0
def nvs_write():
	while True:
		time.sleep(1)
		print('Write.....')
		p = int(pycom.nvs_get('p'))
		pycom.nvs_set('t'+str(p), utime.mktime(utime.gmtime()))
		pycom.nvs_set('d'+str(p), utime.mktime(utime.gmtime()))
		p = p + 1
		pycom.nvs_set('p', p)
		print(pycom.nvs_get('p'))
예제 #8
0
def nvs_read():
	while True:
		print('Read.....')
		p = int(pycom.nvs_get('p'))
		c = 0
		while c < p:
			#print("Position No. %d time: $d, data: %d" % (p, pycom.nvs_get('t'+str(p)), pycom.nvs_get('d'+str(p))))
			print("Position No. %d %02x %02x" % (c, pycom.nvs_get('t'+str(c)), pycom.nvs_get('d'+str(c))))
			#print("Position No. %d %d %d" % (c, pycom.nvs_get('t'+str(c)), pycom.nvs_get('d'+str(c))))
			c += 1
		time.sleep(1)
예제 #9
0
 def __init__(self, bq25895):
     self._bq25895 = bq25895
     self.adc = ADC()
     self.p_SHDN_ = Pin('P21', mode=Pin.OUT)  #shutdown/enable ampli op
     self.pwr_ticks = utime.ticks_us()
     try:
         pycom.nvs_get("pwr_uAH")
     except Exception as e:
         pycom.nvs_set("pwr_uAH", 0)
     self.pwr_nAH = 0
     self.__alarm = Timer.Alarm(self.mesure, 1, periodic=True)
예제 #10
0
 def _getNVS(key):
     '''
     Looks up at the non volatile storage for a specified key. If it exists, returns the value stored
     for that key. Otherwise, returns None
     '''
     try:
         if pycom.nvs_get(key) is not None:
             return pycom.nvs_get(key)
     except Exception:
         # Do nothing, key doesnt exist
         pass
     return None
예제 #11
0
 def readLongList(self, name):
     longVars = []
     i = 0
     while True:
         try:
             lsb = pycom.nvs_get(name + str(i) + 'l')
             msb = pycom.nvs_get(name + str(i) + 'm')
         except:
             break
         else:
             longVars.append(struct.pack(">HI", msb, lsb))
             i = i + 1
     return longVars
예제 #12
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
예제 #13
0
 def extractInt(self, topic):
     # extract integer from nvram topic and put string in self.string
     cnt = 0
     self.string = ""
     x = []
     while True:
         if nvs_get(topic + str(cnt)) == None:
             break
         else:
             x.append(
                 self.int2str(nvs_get(topic + str(cnt))).decode("utf-8"))
             cnt += 1
     while len(x) > 0:
         self.string = self.string + x[len(x) - 1]
         x = x[:len(x) - 1]
     temp = self.string
예제 #14
0
def flash_detect_main():
    flash_counter = pycom.nvs_get('flash_counter')
    if flash_counter is None:
        flash_counter = 0
    flash_counter += 1
    pycom.nvs_set('flash_counter', flash_counter)
    go_back_to_sleep()
 def __init__(self, config, message_callback):
     if config is not None:
         self.__conf = config
         try:
             self.__host = pycom.nvs_get('pybytes_server')
         except:
             self.__host = config.get('server')
         self.__ssl = config.get('ssl', False)
         self.__ssl_params = config.get('ssl_params', {})
         self.__user_name = config.get('username')
         self.__device_id = config.get('device_id')
         self.__mqtt_download_topic = "d" + self.__device_id
         self.__mqtt_upload_topic = "u" + self.__device_id
         self.__pybytes_protocol = PybytesProtocol(
             config, message_callback, pybytes_connection=self
         )
     self.__connection = None
     self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED
     self.__lora_socket = None
     self.lora = None
     self.lora_lock = _thread.allocate_lock()
     self.__sigfox_socket = None
     self.lte = None
     self.wlan = None
     self.__network_type = None
     self.__wifi_lte_watchdog = None
예제 #16
0
def forceRTC(dt, type_dt):
    global rtc
    try:
        # dt = pycom.nvs_get('rtc')

        if type_dt == "tuple":
            print("Step RTC - Forcing Tuple RTC to " + str(dt))
            rtc.init(dt)
        elif type_dt == "epoch":
            print("Step RTC - Forcing Epoch RTC to " + str(int(dt)))
            rtc.init(utime.gmtime(int(dt)))

        utime.sleep(3)
        tools.debug("Setting time: " + str(int(utime.time())), "v")
        try:
            pycom.nvs_set('clock', str(int(utime.time())))
        except OSError as err:
            tools.debug("Error setting RTC: " + str(err), "v")

        utime.sleep(5)
        try:
            dt_current = pycom.nvs_get('clock')
        except OSError as err:
            dt_current = -1
            tools.debug("Error getting RTC: " + str(err), "v")

        tools.debug(
            "Current time: " + str(int(dt_current)) + " - RTC: " +
            str(getDatetime()), "v")
    except Exception as e1:
        checkError("Step RTC - Error initializing parametetr", e1)
예제 #17
0
def getResetCause():
    try:
        reset_cause = machine.reset_cause()
        debug(
            "Reset cause: " + str(reset_cause) + " - Sleeping secs: " +
            str(globalVars.deepSleepSec), "v")
        try:
            globalVars.deepSleepSec = pycom.nvs_get('deepSleepSecs')
        except BaseException as ea:
            checkError("Error getting flash value of", ea)
        if globalVars.deepSleepSec == 0:
            debug("Coming from other reasons", "v")
            BeepBuzzer(1)
        elif globalVars.deepSleepSec > 0:
            pycom.nvs_set('deepSleepSecs', 0)
            globalVars.deepSleepSec = 0
            if synchronizeRTC():
                globalVars.flag_rtc_syncro = True

            BeepBuzzer(0.2)
        else:
            debug("Another reason for the reset", "v")
            BeepBuzzer(1)
    except BaseException as e:
        checkError("Error getting reset cause", e)
def nvs_get_default(key, default=None):
    try:
        val = pycom.nvs_get(key)
        if val == None:
            val = default
        return val
    except ValueError:
        return default
예제 #19
0
def measurements():
    global MSG_ID, TEMP, MOIST, VOLTAGE
    MSG_ID = pycom.nvs_get('msg_id')
    TEMP = _temp_sensor()
    VOLTAGE = _battery()
    MOIST = _moist_sensor()

    print('Measurements:', MSG_ID, TEMP, VOLTAGE, MOIST)
예제 #20
0
def initRTC():
    global rtc
    try:
        dt = pycom.nvs_get('clock')
        print("Step RTC - Initializing RTC to " + str(int(dt)))
        rtc.init(utime.gmtime(int(dt)))
        utime.sleep(2)
    except Exception as e1:
        checkError("Step RTC - Error initializing parametetr", e1)
예제 #21
0
def LoRaSend(val,ch):
    sl = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    sl.setblocking(True)
    sl.send(encrypt(SITE+mac()+'/'+ch+'&'+val)) # Send on LoRa Network & wait Reply
    sl.setblocking(False)
    try:
        pycom.nvs_set('msgID',pycom.nvs_get('msgID')+1)
    except:
        pycom.nvs_set('msgID',0)
    print("Sent",ch)
예제 #22
0
def deep_sleep():
    id = pycom.nvs_get('msg_id')
    pycom.nvs_set('msg_id', id + 1)
    print('Start deep sleep...')
    py.setup_int_pin_wake_up(True)
    py.setup_int_wake_up(False, True)
    #py.setup_sleep(3600)  # 1 hour
    py.setup_sleep(600)  # 10 min

    deep_sleep_led()
    py.go_to_sleep()
예제 #23
0
def nvs_get(key, default=None):
    """ Reads non-volatile state and returns default if not defined

    Some Pycom versions return None if the value is undefined. Some throw an
    error. This function suppresses the error and adds a default feature.
    """

    try:
        return pycom.nvs_get(key) or default
    except:
        return default
예제 #24
0
 def log(self, level, msg, *args):
     if level >= (self.level or _level):
         _stream.write("%3d %2d - %5s - %s :" %
                       (pycom.nvs_get('day'), time.time(),
                        self._level_str(level), self.name))
         if not args:
             print(msg, file=_stream)
         else:
             print(msg % args, file=_stream)
         if _filename is not None:
             _stream.flush()
예제 #25
0
 def mesure(self, alarm):
     old = self.pwr_ticks
     self.pwr_ticks = utime.ticks_us()
     delta = utime.ticks_diff(self.pwr_ticks, old)
     self.pwr_nAH = self.pwr_nAH + int(self.getPWR() * delta / 3600)
     uAH = self.pwr_nAH // 1000
     #print("nAH : {}, uAH : {}".format(self.pwr_nAH, uAH))
     if uAH > 0:
         self.pwr_nAH = self.pwr_nAH - (uAH * 1000)
         uAH = pycom.nvs_get("pwr_uAH") + uAH
         #print("pwr_uAH :{}".format(uAH))
         pycom.nvs_set("pwr_uAH", uAH)
예제 #26
0
def nvs_get(key, default_value=0):
    """ Get value for key from NVRAM. Create the key if it does not exist.

    :param str key:
    :param int default_value: value to use when creating the key
    :return value int: (NVRAM can only store integers)
    """
    value = pycom.nvs_get(key)
    if value is None:
        pycom.nvs_set(key, int(default_value))
        value = int(default_value)
    return value
예제 #27
0
def synchronizeRTC():
    try:
        tools.debug("Synching RTC to " + str(int(utime.time())), "v")
        last_valid_time = 0
        offset = 15
        sleepTime = 0

        try:
            sleepTime = pycom.nvs_get('deepSleepSecs')
            last_valid_time = pycom.nvs_get('clock')
        except Exception as e:
            checkError("Error getting DT", e)
            return False

        utime.sleep(2)
        current_dt = int(last_valid_time) + int(sleepTime) + offset
        forceRTC(int(current_dt), "epoch")
        return True
    except Exception as e:
        checkError("Error updating RTC", e)
        return False
예제 #28
0
def ammend_to_file():
    try:
        f = open('/flash/log.txt', 'r')
        lines = f.readlines()
        f.close()
        lines = lines[1:]
        print(lines[-20:-1])
        f = open('/flash/log.txt', 'w')
        for a in range(0, 999):
            try:
                f.write(lines[a])
            except:
                f.write('\n')
        f.close()
    except:
        pass
    f = open('/flash/log.txt', 'a')
    f.write(str(pycom.nvs_get('msgID')))
    f.write(',')
    f.write(str(pycom.nvs_get('val')))
    f.write('\n')
    f.close()
예제 #29
0
def dbg(v=None, verbose=True):
    if v is None:
        try:
            d = pycom.nvs_get(key)
            if verbose:
                print("current", d)
            return d
        except:
            if verbose:
                print("not set")
            return 0
    else:
        try:
            d = pycom.nvs_get(key)
            if verbose:
                print("previous", d)
        except:
            if verbose:
                print("not set yet, setting ...")
        pycom.nvs_set(key, v)  # 1,2,3,4,5,6, 99
        if verbose:
            print("new", pycom.nvs_get(key))
예제 #30
0
def set_GPS_timeout(l76=None):
    """Set the GPS timeout according to the number of satellites in view"""
    if l76 == None:
        l76 = L76GNSS(timeout=conf.GPS_TIMEOUT)
    if l76.check_satellites() < '04' and pycom.nvs_get('gpscount') < 2:
        pycom.nvs_set('gpscount', pycom.nvs_get('gpscount') + 1)
        conf.DEEP_SLEEP_PERIOD = 150  # 2 minutes 30s
    elif l76.check_satellites() < '04':
        pycom.nvs_set('gpscount', 0)
        conf.DEEP_SLEEP_PERIOD = 900  # 15 minutes
    else:
        #latlng  = l76.coordinates(1)
        """
        if latlng[0] == None or latlng[1] == None:
            conf.GPS_TIMEOUT = 300
            conf.DEEP_SLEEP_PERIOD = 60 # 1 minute
            return True
        else:
            conf.DEEP_SLEEP_PERIOD = 300 # 15 minutes
            return True
        """
        return True
    return False