Python源码示例:utime.time()

示例1
def do_connect():
    sta_if = network.WLAN(network.STA_IF)
    start = utime.time()
    timed_out = False

    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(config.wifi_config["ssid"], config.wifi_config["password"])
        while not sta_if.isconnected() and \
            not timed_out:        
            if utime.time() - start >= 20:
                timed_out = True
            else:
                pass

    if sta_if.isconnected():
        ntptime.settime()
        print('network config:', sta_if.ifconfig())
    else: 
        print('internet not available') 
示例2
def status_handler(mqtt_link, status):
    global out_time
    res = await default_status_handler(mqtt_link, status)
    if res is not None:  # Handle failure on initialisation
        # res == 1 occurs on 1st run only. Tells driver to try the network
        # specified in net_local.
        # res == 0 indicates failure to connect. The default handler waits 30 secs
        # before returning 0 to give time for the network to come up.
        # If we return 0 the ESP8266 will be rebooted
        return res
    # WiFi handling for demo: easier to use wifi_handler (see pb_simple.py)
    if status == WIFI_UP:
        amber.on()
        delta = time() - out_time
        mqtt_link.publish('result', 'WiFi up: out time = {}s'.format(delta), 0, qos)
        return
    if status == WIFI_DOWN:
        out_time = time()
        amber.off()
        return
    if status == PUBOK:
        return
    status_vals.append(status)  # We will publish non-routine values 
示例3
def _do_rtc(self):
        lnk = self._lnk
        lnk.vbprint('Start RTC synchroniser')
        self._time_valid = not self._rtc_last_syn == 0  # Valid on restart
        while True:
            while not self._time_valid:
                lnk.channel.send(TIME)
                # Give 5s time for response
                await asyn.sleep(5)
                if not self._time_valid:
                    # WiFi may be down. Delay 1 min before retry.
                    await asyn.sleep(60)
            else:  # Valid time received or restart
                if self._rtc_interval < 0:
                    break  # One resync only: done
                tend = self._rtc_last_syn + self._rtc_interval
                twait = max(tend - time(), 5)  # Prolonged outage
                await asyn.sleep(twait)
                self._time_valid = False 
示例4
def get_time(self, set_rtc = False):
        if set_rtc:
            data = self.await_transition()      # For accuracy set RTC immediately after a seconds transition
        else:
            self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf)
            data = self.timebuf
        ss = bcd2dec(data[0])
        mm = bcd2dec(data[1])
        if data[2] & 0x40:
            hh = bcd2dec(data[2] & 0x1f)
            if data[2] & 0x20:
                hh += 12
        else:
            hh = bcd2dec(data[2])
        wday = data[3]
        DD = bcd2dec(data[4])
        MM = bcd2dec(data[5] & 0x1f)
        YY = bcd2dec(data[6])
        if data[5] & 0x80:
            YY += 2000
        else:
            YY += 1900
        if set_rtc:
            rtc.init((YY, MM, DD, hh, mm, ss, 0))
        return (YY, MM, DD, hh, mm, ss, 0, 0) # Time from DS3231 in time.time() format (less yday) 
示例5
def create_jwt(project_id, private_key, algorithm, token_ttl):
    print("Creating JWT...")
    private_key = rsa.PrivateKey(*private_key)

    # Epoch_offset is needed because micropython epoch is 2000-1-1 and unix is 1970-1-1. Adding 946684800 (30 years)
    epoch_offset = 946684800
    claims = {
            # The time that the token was issued at
            'iat': utime.time() + epoch_offset,
            # The time the token expires.
            'exp': utime.time() + epoch_offset + token_ttl,
            # The audience field should always be set to the GCP project id.
            'aud': project_id
    }

    #This only supports RS256 at this time.
    header = { "alg": algorithm, "typ": "JWT" }
    content = b42_urlsafe_encode(ujson.dumps(header).encode('utf-8'))
    content = content + '.' + b42_urlsafe_encode(ujson.dumps(claims).encode('utf-8'))
    signature = b42_urlsafe_encode(rsa.sign(content,private_key,'SHA-256'))
    return content+ '.' + signature #signed JWT 
示例6
def temp_update(self):
        tick = utime.time()
        buffer = ustruct.pack(
            "<HB",
            tick,
            (270 + urandom.randint(0, 32767)))
        result = self.aci_gatt_update_char_value(
            serv_handle=self.hw_serv_handle,
            char_handle=self.temperature_bluest_char_handle,
            char_val_offset=0,
            char_value_len=len(buffer),
            char_value=buffer).response_struct
        if result.status != status.BLE_STATUS_SUCCESS:
            raise ValueError("aci_gatt_update_char_value status: {:02x}".format(
                result.status))
        log.debug("aci_gatt_update_char_value %02x", result.status) 
示例7
def pwr_update(self):
        tick = utime.time()
        chg = urandom.randint(0, 100)
        voltage = urandom.randint(0, 100)
        current = urandom.randint(0, 100)
        npwrstat = urandom.randint(0, 100)
        buffer = ustruct.pack(
            "<HHHHB",
            tick,
            chg, voltage, current, npwrstat)
        result = self.aci_gatt_update_char_value(
            serv_handle=self.hw_serv_handle,
            char_handle=self.pwr_bluest_char_handle,
            char_val_offset=0,
            char_value_len=len(buffer),
            char_value=buffer).response_struct
        if result.status != status.BLE_STATUS_SUCCESS:
            raise ValueError("aci_gatt_update_char_value status: {:02x}".format(
                result.status))
        log.debug("aci_gatt_update_char_value %02x", result.status) 
示例8
def press_update(self):
        tick = utime.time()
        buffer = ustruct.pack(
            "<HI",
            tick,
            100000 + urandom.randint(0, 32767))
        result = self.aci_gatt_update_char_value(
            serv_handle=self.hw_serv_handle,
            char_handle=self.pressure_bluest_char_handle,
            char_val_offset=0,
            char_value_len=len(buffer),
            char_value=buffer).response_struct
        if result.status != status.BLE_STATUS_SUCCESS:
            raise ValueError("aci_gatt_update_char_value status: {:02x}".format(
                result.status))
        log.debug("aci_gatt_update_char_value %02x", result.status) 
示例9
def _PMdata(self):
        d = {}
        check = False
        # check data
        control_sum = 0x42 + 0x4d
        for b in range(len(self._data)-2):
            control_sum += self._data[b]

        control_sum_data = self._data[28] * 256 + self._data[29]
        print()
        if control_sum == control_sum_data:
            check = True

        d['time'] = utime.time() + epoch_offset
        d['cpm10'] = self._data[4] * 256 + self._data[5]
        d['cpm25'] = self._data[6] * 256 + self._data[7]
        d['cpm100'] = self._data[8] * 256 + self._data[9]
        d['apm10'] = self._data[10] * 256 + self._data[11]
        d['apm25'] = self._data[12] * 256 + self._data[13]
        d['apm100'] = self._data[14] * 256 + self._data[15]

        return [check, d] 
示例10
def connect(self, timeout=_CONNECT_TIMEOUT):
        end_time = time.time() + timeout
        while not self.connected():
            if self._state == self.DISCONNECTED:
                try:
                    self._get_socket()
                    self._authenticate()
                    self._set_heartbeat()
                    self._last_rcv_time = ticks_ms()
                    self.log('Registered events: {}\n'.format(list(self._events.keys())))
                    self.call_handler(self._CONNECT)
                    return True
                except BlynkError as b_err:
                    self.disconnect(b_err)
                    sleep_ms(self.TASK_PERIOD_RES)
                except RedirectError as r_err:
                    self.disconnect()
                    self.server = r_err.server
                    self.port = r_err.port
                    sleep_ms(self.TASK_PERIOD_RES)
            if time.time() >= end_time:
                return False 
示例11
def start(mqtt_link):
    global reset_count
    mqtt_link.subscribe('green', qos, cbgreen)    # LED control qos 1
    loop = asyncio.get_event_loop()
    loop.create_task(asyn.Cancellable(publish, mqtt_link, 10)()) # Publish a count every 10 seconds
    loop.create_task(pulse(blue))  # Flash blue LED each time we restart ESP8266
    reset_count += 1 
示例12
def cbnet(state, objlink):
    global out_time
    if state:
        amber.on()
        delta = time() - out_time
        objlink.publish('result', 'WiFi up: out time = {}s'.format(delta), 0, qos)
    else:
        amber.off()
        out_time = time() 
示例13
def start(mqtt_link):
    global reset_count
    mqtt_link.subscribe('green', qos, cbgreen)    # LED control qos 1
    mqtt_link.wifi_handler(cbnet, mqtt_link)  # Detect WiFi changes
    loop = asyncio.get_event_loop()
    loop.create_task(asyn.Cancellable(publish, mqtt_link, 10)()) # Publish a count every 10 seconds
    loop.create_task(pulse(blue))  # Flash blue LED each time we restart ESP8266
    reset_count += 1 
示例14
def _publish(self):
        while True:
            if len(self.pubs): 
                args = self.pubs.pop(0)
                secs = 0
                # pub free can be a long time coming if WiFi is down
                while not self._pub_free:
                    # If pubs are queued, wait 1 sec to respect ESP8266 buffers
                    await asyncio.sleep(1)
                    if self._wifi_up:
                        secs += 1
                    if secs > 60:
                        self.quit('No response from ESP8266')
                        break
                else:
                    self.channel.send(argformat(PUBLISH, *args))
                    # All pubs send PUBOK.
                    # No more pubs allowed until PUBOK received.
                    self.pub_free(False)
            else:
                await asyncio.sleep_ms(20)

# start() is run each time the channel acquires sync i.e. on startup and also
# after an ESP8266 crash and reset.
# Behaviour after fatal error with ESP8266:
# It sets _running False to cause local tasks to terminate, then returns.
# A return causes the local channel instance to wait on the exit_gate to cause
# tasks in this program terminate, then issues a hardware reset to the ESP8266.
# (See SynCom.start() method). After acquiring sync, start() gets rescheduled. 
示例15
def _observe(self):
        try:
            v = self.sensor.sample()
            self._dispatch_next((self.sensor.sensor_id, utime.time(), v),)
        except FatalError:
            raise
        except StopIteration:
            self._dispatch_completed()
        except Exception as e:
            self._dispatch_error(e) 
示例16
def _readid(s, to_secs):
    data = ''
    start = time.time()
    while True:
        try:
            d = s.recv(4096).decode()
        except OSError as e:
            err = e.args[0]
            if err == errno.EAGAIN:
                if (time.time() - start) > to_secs:
                    raise OSError  # Timeout waiting for data
                else:
                    # Waiting for data from client. Limit CPU overhead. 
                    await asyncio.sleep(TIM_TINY)
            else:
                raise OSError  # Reset by peer 104
        else:
            if d == '':
                raise OSError  # Reset by peer or t/o
            data = '{}{}'.format(data, d)
            if data.find('\n') != -1:  # >= one line
                return data


# API: application calls server.run()
# Allow 2 extra connections. This is to cater for error conditions like
# duplicate or unexpected clients. Accept the connection and have the
# Connection class produce a meaningful error message. 
示例17
def _waitack(self, mid):
        tstart = time.time()  # Wait for ACK
        while mid in self._acks_pend:
            await asyncio.sleep(TIM_TINY)
            if not self() or ((time.time() - tstart) > self._to_secs):
                self._verbose and print('waitack timeout', mid)
                return False  # Outage or ACK not received in time
        return True

    # Verbatim write: add no message ID. 
示例18
def _send(self, d):
        if not self():
            return False
        d = d.encode('utf8')  # Socket requires bytes
        start = time.time()
        while d:
            try:
                ns = self._sock.send(d)  # Raise OSError if client fails
            except OSError as e:
                err = e.args[0]
                if err == errno.EAGAIN:  # Would block: try later
                    await asyncio.sleep(0.1)
                    continue
                break
            else:
                d = d[ns:]
                if d:
                    await asyncio.sleep(self._tim_short)
                    if (time.time() - start) > self._to_secs:
                        break
        else:
            # The 0.2s delay is necessary otherwise messages can be lost if the
            # app attempts to send them in quick succession. Also occurs on
            # Pyboard D despite completely different hardware.
            # Is it better to return immediately and delay subsequent writes?
            # Should the delay be handled at a higher level?
            #await asyncio.sleep(0.2)  # Disallow rapid writes: result in data loss
            return True  # Success
        self._close('Write fail: closing connection.')
        return False 
示例19
def now():  # Return the current time from the RTC in millisecs from year 2000
    secs = utime.time()
    ms = int(rtc.now()[6]/1000)
    if ms < 50:                                 # Might have just rolled over
        secs = utime.time()
    return 1000 * secs + ms 
示例20
def initialize(init_time=None):
        """Class to initializa the static class
        creates the file to write and the instance of the class """
        dprint('Init statsct module')
        if init_time is None:
            init_time = time.time() # XXX: need refactor, should be obtained from Scheduler
        Statsct.results['init_time'] = init_time #utime.time() -->exception
        Statsct.results['packet_list'] = []
        Statsct.sender_packets['packet_list'] = []
        Statsct.receiver_packets['packet_list'] = []
        Statsct.src_id = None
        Statsct.dst_id = None
        Statsct.device_rule = dict()
        Statsct.gw_rule = dict()
        Statsct.gw_rule['fragSender'] = []
        Statsct.channel_occupancy = 0
        Statsct.goodput = 0
        Statsct.total_delay = 0
        Statsct.reliability = 0
        Statsct.total_packet_send = dict()
        Statsct.msg_type = ""
        Statsct.packet_info = dict()
        Statsct.last_msg_type = ""
        Statsct.succ_packets = 0
        Statsct.fail_packets = 0
        Statsct.total_data_send = 0
        Statsct.msg_type_queue = []
        Statsct.channel_occupancy_sender = 0
        Statsct.channel_occupancy_receiver = 0 
示例21
def addTotalDelay(time):
        Statsct.total_delay += time
        dprint("total_delay -> {}".format(Statsct.total_delay)) 
示例22
def dc_time_off(time_on,dc):
        """Calculates the time off for a given duty cycle 
        :param dc: duty cycle
        :param time_on: time on air, active time
        :returns time_off: time off required after transmission
        """
        time_off = time_on * ((100-dc)/dc)
        return time_off 
示例23
def print_ordered_packets():
        dprint('print_ordered_packets ')
        for i,k in enumerate(Statsct.results['packet_list']):
            dprint('{}:{}:,source:{},toa_packet: {}, time off: {},status: {}, packet_length:{}, msg_type: {}'.format(i,k['time'],k['src_dev_id'],k['toa_packet'],k['time_off'], k['status'],k['packet_length'],k['msg_type']))
        
        



    # @staticmethod
    # def log(self, name, message):
    #     self.system.log(name, message) 
示例24
def set_time():
    ntptime.settime()
    tm = utime.localtime()
    tm = tm[0:3] + (0,) + tm[3:6] + (0,)
    machine.RTC().datetime(tm)
    print('current time: {}'.format(utime.localtime())) 
示例25
def ensure_element(e) :
    assert type(e) is dict
    assert 'time' in e
    ensure_time(e['time'])
    assert 'color_name' in e
    ensure_color_name(e['color_name'])
    return True 
示例26
def get_localtime(self) :
        secs = utime.time()
        secs += self.tzd.get_offset_hours() * 60 * 60
        return utime.localtime(secs) 
示例27
def find_index_in_range(secs, seq) :
        n = len(seq)
        for i in range(n) :
            seq_i = seq[i]
            seq_i_secs = Scheduler.get_secs(seq_i['time'])
            if secs < seq_i_secs :
                return -1
            elif i < n - 1 : # and seq_i <= secs
                seq_iplus1 = seq[i+1]
                seq_iplus1_secs = Scheduler.get_secs(seq_iplus1['time'])
                if secs < seq_iplus1_secs :
                    return i
            i += 1
        return -1 
示例28
def get_secs(time) :
        return time["h"]*60*60 + time["m"]*60 + time["s"] 
示例29
def uptime():
    current_secs = utime.time()
    secs = current_secs - start_time
    return core.util.duration(secs) 
示例30
def accgyromag_update(self):
        # accel = pyb.Accel()
        # acc_axis_x, acc_axis_y, acc_axis_z = accel.x(), accel.y(), accel.z()
        tick = utime.time()
        acc_axis_x, acc_axis_y, acc_axis_z = (
            urandom.randint(0, 32767) % X_OFFSET,
            urandom.randint(0, 32767) % Y_OFFSET,
            urandom.randint(0, 32767) % Z_OFFSET)
        gyto_axis_x, gyto_axis_y, gyto_axis_z = (
            urandom.randint(0, 32767) % X_OFFSET,
            urandom.randint(0, 32767) % Y_OFFSET,
            urandom.randint(0, 32767) % Z_OFFSET)
        mag_axis_x, mag_axis_y, mag_axis_z = (
            urandom.randint(0, 32767) % X_OFFSET,
            urandom.randint(0, 32767) % Y_OFFSET,
            urandom.randint(0, 32767) % Z_OFFSET)

        buffer = ustruct.pack(
            "<HHHHHHHHHH",
            tick,
            acc_axis_x, acc_axis_y, acc_axis_z,
            gyto_axis_x, gyto_axis_y, gyto_axis_z,
            mag_axis_x, mag_axis_y, mag_axis_z)
        result = self.aci_gatt_update_char_value(
            serv_handle=self.hw_serv_handle,
            char_handle=self.acc_gyro_mag_bluest_char_handle,
            char_val_offset=0,
            char_value_len=len(buffer),
            char_value=buffer).response_struct
        if result.status != status.BLE_STATUS_SUCCESS:
            raise ValueError("aci_gatt_update_char_value status: {:02x}".format(
                result.status))
        log.debug("aci_gatt_update_char_value %02x", result.status)