Esempio n. 1
0
def connect_and_sync():
    """ Attempt wifi connection and ntp synchronization
    """

    w = network.WLAN(network.STA_IF)

    attempts = 4  # How many times to attempt network connection
    while not w.isconnected():
        # s.connect('ShArVa')
        print("Network not connected - sleeping")
        knight_rider()

        attempts -= 1
        if not attempts:
            return()

    print("Netowrk connected")
    knight_rider(200, 10)

    ntp_sync = False
    while not ntp_sync:
        try:
            print("NTP time sync")
            ntptime.settime()
        except:
            print("NTP fail")
            knight_rider(100, 5)
        else:
            print("NTP synced")
            ntp_sync = True

    knight_rider(200, 0)
Esempio n. 2
0
async def ntp_sync():
    while True:
        try:
            ntptime.settime()
        except OSError as err:
            LOG.error('timesync: %s', err)
        else:
            LOG.info('Time synchronized')
        await asyncio.sleep(3600)
Esempio n. 3
0
def query_utctime():
    time_get = False
    while time_get == False:
        try:
            ntptime.settime()
            time_get = True
        except:
            print('ntp timeout')
    print('current time is: ', utime.localtime())
Esempio n. 4
0
def settime():
    if get_config("ntp_enabled", True) is True:
        try:
            # log_message("NTP TIME")
            ntptime.host = config["ntp_server"]
            ntptime.settime()
        except OSError as err:
            log_exception(err, 2)
            pass
Esempio n. 5
0
 def ntp(self):
     self.net()
     time.sleep(5)
     ntptime.host = "ntp1.aliyun.com"
     ntptime.NTP_DELTA = 3155644800
     try:
         ntptime.settime()
     except Exception as e:
         pass
Esempio n. 6
0
def _ntp_settime(uPK):
  if settime is not None:
    try:
      if uPK.info:
        uPK.info('Attempting to set the time using NTP...')
      settime()
    except Exception as e:
      if uPK.error:
        uPK.error('Failed to set NTP time: %s' % e)
Esempio n. 7
0
def main():
    ntptime.settime()
    matrix = ht1632c.HT1632C()
    while True:
        matrix.fill(ht1632c.BLACK)
        text = '{0:02}{1:02}'.format(*utime.localtime()[3:5])
        matrix.text(text, 0, 4, ht1632c.GREEN)
        matrix.show()
        utime.sleep_ms(10000)
Esempio n. 8
0
 def reset_time(self):
     self.wlan = network.WLAN(network.STA_IF)
     if not self.wlan.active():
         wlan.active(True)
     try:
         ntptime.settime()
     except:
         print("error calling ntptime")
     self.start_time = time.time()
Esempio n. 9
0
def uptime_time():
    try:
        ntptime.settime()
        current_time = pretty_time()
        print('The time from NTP is ' + current_time)
        print('Debug info: ', rtc.datetime())
    except Exception:
        print('Cannot update time from NTP.')
    print()
Esempio n. 10
0
def get_time():
    settime()

    local_time_sec = utime.time() - 5 * 3600
    local_time = utime.localtime(local_time_sec)

    print(local_time)

    return (local_time)
Esempio n. 11
0
def cycle() -> None:
    """Measurement cycle."""
    # Init I2C.
    i2c = machine.I2C(scl=machine.Pin(config.SCL_PIN),
                      sda=machine.Pin(config.SDA_PIN))

    # Init BME280 sensor connected to I2C.
    bme = bme280.BME280(address=config.BME280_I2C_ADDR, i2c=i2c)

    # Read measurements.
    t, p, h = bme.read_compensated_data()
    t, p, h = t / 100, p / 256, h / 1024

    print(t, p, h)

    error = False
    # Sync RTC.
    try:
        ntptime.settime()
    except Exception as err:
        error = True
        log_error('syncing clock', err)

    url = config.URL_TEMPLATE.format(t=t, p=p, h=h)
    try:
        urlopen(url)
    except Exception as err:
        error = True
        log_error('sending metrics', err)

    # Init display.
    display = ssd1306.SSD1306_I2C(DISPLAY_WIDTH,
                                  DISPLAY_HEIGHT,
                                  i2c,
                                  addr=config.DISPLAY_I2C_ADDR)

    display.fill(0)

    # Calculate current time.
    hours = utime.localtime()[3] + config.UTC_OFFSET
    if hours >= 24:
        hours -= 24
    minutes = utime.localtime()[4]
    display.text('{:02d}:{:02d}'.format(hours, minutes), DISPLAY_WIDTH - 40, 2)

    if error:
        display.text('Error', 0, 0)

    # Show measurements.
    display.text('T: {:.2f}C'.format(t), 0, 16)
    display.text('P: {:.2f}hPa'.format(p / 100), 0, 26)
    display.text('H: {:.2f}%'.format(h), 0, 36)

    display.show()
    utime.sleep(5)
    display.poweroff()
Esempio n. 12
0
    def run(self):
        loop_delay_ms = 250
        loop_counter = 0
        slept_since_set_mode = 0
        since_settime_ms = 0
        fade_steps = 1
        colour_changed = False

        while True:
            loop_counter += 1
            if loop_counter > 255:
                loop_counter = 0

            self.dirty = self.dirty or ((self.mode == "schedule" or self.mode == "random") and slept_since_set_mode > 16000)
            if self.dirty:
                self.dirty = False
                print('dirty mode={} slept_since_set_mode={}'.format(self.mode, slept_since_set_mode))
                if self.mode == "schedule":
                    self.apply_scheduled_colour()
                    slept_since_set_mode = 0
                elif self.mode == "on":
                    self.ledController.set_target(self.static_colour[0], self.static_colour[1], self.static_colour[2], self.static_colour[3])
                elif self.mode == "random":
                    self.apply_rainbow_colour()
                    slept_since_set_mode = 0
                elif self.mode == "off":
                    self.ledController.set_target(0, 0, 0, 0)

            if self.mode == "random":
                if loop_counter % 5 == 0:
                    fade_steps = int(self.rainbow_brightness / 8)
                    colour_changed = self.ledController.fade_to_target(fade_steps)
                else:
                    colour_changed = False
            elif self.mode == "schedule":
                if loop_counter % 8 == 0:
                    fade_steps = 4
                    colour_changed = self.ledController.fade_to_target(fade_steps)
                else:
                    colour_changed = False
            else:
                fade_steps = 1.414
                colour_changed = self.ledController.fade_to_target(fade_steps)

            if not colour_changed:
                utime.sleep_ms(loop_delay_ms)
            slept_since_set_mode += loop_delay_ms
            since_settime_ms += loop_delay_ms

            if since_settime_ms > 86400000: # 24 hours
                try:
                    settime()
                    since_settime_ms = 0
                except Exception:
                    print("Exception calling settime")
                    since_settime_ms = 82800000 # retry in 1 hour
Esempio n. 13
0
async def setTime():
    while True:
        print("time is unset")
        try:
            settime()  #No timezones, we use UTC.
        except IndexError:
            await asyncio.sleep(5)  #Wait 5 seconds and try again
        else:
            print("time is", *time.localtime())
            break
Esempio n. 14
0
 def _set_time(self):
     """
     synchronize time with ntp and set rtc localtime by setted gmt.
     """
     sleep(2)
     ntptime.settime()
     (year, month, mday, hour, minute, second, weekday,
      yearday) = localtime(time() + (3600 * self._gmt))
     self._rtc.datetime((year, month, mday, 0, hour, minute, second, 0))
     print("\nTime setted: {}".format(localtime()))
Esempio n. 15
0
def sync_time():
    import ntptime
    try:
        print('sync time')
        ntptime.settime()
        clear_tdiff()
        return True
    except Exception as e:
        sys.print_exception(e)
        print('sync time failure')
Esempio n. 16
0
 def ntpInit(self):
     if bProto.ntpInit is False:
         time.sleep(5)
         if wlan.isconnected():
             ntptime.settime()
             t = utime.time()
             tm = utime.localtime(t + 8 * 60 * 60)
             tm = tm[0:3] + (0, ) + tm[3:6] + (0, )
             machine.RTC().datetime(tm)
             bProto.ntpInit = True
Esempio n. 17
0
def update_time():
    try:
        ntptime.host = secrets['ntp']
        ntptime.settime()
        t1 = time.time()
        t2 = t1 + (secrets['tz'] * 3600)
        (yr, mn, md, hr, mn, sc, wd, yd) = time.localtime( t2 )
        rtc.datetime( (yr, mn, md, 0, hr, mn, sc, 0) )
    except OSError as e:
        print( e )
Esempio n. 18
0
def update_time():
    hour, minute = rtc.datetime()[4:6]
    hour = (hour + int(TIME_ZONE)) % 24
    if 0 == minute:
        try:
            settime()
        except:
            pass
    go_to(adc_hour, None, HOUR_LUT[hour])
    go_to(adc_minute, None, MINUTE_LUT[minute])
Esempio n. 19
0
    async def _updateTime(self):
        while True:
            try:
                settime()
                print("> NTP time updated at {}".format(RTC().datetime()))

                await sleep(300)
            except Exception as e:
                print("> NtpTime._updateTime error: {}".format(e))
                await sleep(30)
Esempio n. 20
0
def ntp():
    print('')
    ntptime.host = key_store.get('ntp_host')
    print("NTP Server:", ntptime.host)
    while utime.time() < 10000:  # Retry until clock is set
        ntptime.settime()
        utime.sleep(1)
    print('UTC Time:   {}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(
        *utime.localtime()))
    print('')
Esempio n. 21
0
def time_correct():
    config = get_config('config')
    ntptime.host = config['ntphost']
    ntptime.settime()
    rtc = machine.RTC()
    tm = time.localtime(
        time.mktime(time.localtime()) + config['utc_shift'] * 3600)
    tm = tm[0:3] + (0, ) + tm[3:6] + (0, )
    rtc.datetime(tm)
    update_config()
Esempio n. 22
0
def nptset():
    while True:
        try:
            settime()
            log.debug('{} : Timeset'.format(timeout()))
        except KeyboardInterrupt:
            raise
        except:
            log.warning('{} : timeout exception'.format(timeout()))
        time.sleep(20)
Esempio n. 23
0
def settime():
    (hour_offset, minute_offset) = get_offset_from_api()
    log.info("fetching time from ntp")
    ntptime.settime()

    # add offset
    rtc = RTC()
    (year, month, day, _, hour, minute, second, subsecond) = rtc.datetime()
    rtc.datetime((year, month, day, 0, hour + hour_offset,
                  minute + minute_offset, second, subsecond))
Esempio n. 24
0
 def listen_time(self):
     while True:
         try:
             ntptime.settime()
             print('time = ' + str(utime.localtime()))
             break
         except OSError as err:
             print('restarting network and trying again', err)
             self.wifi_tcp.active(False)
             self.start_wifi()
Esempio n. 25
0
def aseta_aika():
    if NTPPALVELIN is not None:
        ntptime.host = NTPPALVELIN
    try:
        ntptime.settime()
    except OSError as e:
        print("NTP-palvelimelta %s ei saatu aikaa! Virhe %s" %
              (NTPPALVELIN, e))
        ei_voida_yhdistaa()
    print("Aika: %s " % str(utime.localtime(utime.time())))
Esempio n. 26
0
def ntp_update():
    global lastNtpUpdate
    tnow = time.time()
    if tnow - lastNtpUpdate > NTP_UPDATE_TIME_SECS and is_wifi_ok():
        DPRINT('Updating ntp time')
        try:
            ntptime.settime()
            lastNtpUpdate = tnow
        except Exception:
            DPRINT('Cannot update ntp! Retrying later...')
Esempio n. 27
0
    def __init__(self, scope_id, registration_id, credentials_type: IoTCConnectType, credentials, logger, model_id=None, endpoint='global.azure-devices-provisioning.net'):
        self._endpoint = endpoint
        self._scope_id = scope_id
        self._registration_id = registration_id
        self._credentials_type = credentials_type
        self._api_version = '2019-01-15'
        if logger is not None:
            self._logger=logger
        else:
            self._logger=ConsoleLogger(IoTCLogLevel.DISABLED)

        if model_id is not None:
            self._model_id = model_id

        if self._credentials_type in (IoTCConnectType.DEVICE_KEY, IoTCConnectType.SYMM_KEY):
            self._device_key = credentials
            if self._credentials_type == IoTCConnectType.SYMM_KEY:
                self._device_key = self._compute_key(
                    credentials, self._registration_id)
                # self._logger.debug('Device key: {}'.format(self._key_or_cert))
        else:
            self._key_file = self.credentials['key_file']
            self._cert_file = self.credentials['cert_file']
            # try:
            #     self._cert_phrase = self.credentials['cert_phrase']
            #     # TODO: x509 = X509(self._cert_file, self._key_file, self._cert_phrase)
            # except:
            #     # self._logger.debug(
            #         'No passphrase available for certificate. Trying without it')
            #     # TODO: x509 = X509(self._cert_file, self._key_file)
        self._username = '******'.format(
            scope_id, registration_id, self._api_version)
        resource_uri = '{}/registrations/{}'.format(
            scope_id, registration_id)
        try:
            from ntptime import settime
            settime()
            gc.collect()
            del sys.modules['ntptime']
            gc.collect()
        except:
            pass
        
        expiry = time() + 946706400   # 6 hours from now in epoch
        signature = encode_uri_component(self._compute_key(
            self._device_key, '{}\n{}'.format(resource_uri, expiry)))
        self._password = '******'.format(
            resource_uri, signature, expiry)
        del expiry
        del signature
        gc.collect()
        self._logger.debug(self._username)
        self._logger.debug(self._password)
        self._headers = {"content-type": "application/json; charset=utf-8",
                         "user-agent": "iot-central-client/1.0", "Accept": "*/*", 'authorization': self._password}
Esempio n. 28
0
def json_c(temp_v,sta_if, buffer):
    if sta_if.isconnected():
        try:
            settime()
        except:
            pass
        time = utime.localtime()
        years = time[0]
        month = time[1]
        day = time[2]
        hour = time[3]
        minute = time[4]
        second = time[5]
        time_res ="{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}.000Z".format(years,month,day,hour,minute,second)
        
        #encode obj. to json
        temp_final = "{0:.2f}".format(temp_v)
        temp_json = json.dumps({'ite_message': 
                                {'team_name': "blue", 
                                 'created_on': time_res, 
                                 'temperature':temp_final}})
        rtc.datetime([time[0],time[1], time[2], time[6], time[3], time[4],time[5], 0])
        #(year, month, day, weekday, hours, minutes, seconds, subseconds)
        
        #mqtt connect
        try:
            mqttCon = MQTTClient("umqtt_client", SERVER_MQTT, user = "******",password = "******")
            mqttCon.connect()
            if buffer != []:
                for i in buffer:
                    mqttCon.publish(TOPIC, i)
                del buffer[:]
            mqttCon.publish(TOPIC, temp_json)
            mqttCon.disconnect()
        except:
            print("Failed to send json...")
            buffer.append(temp_json)
            
        
    else:
        time = rtc.datetime()
        years = time[0]
        month = time[1]
        day = time[2]
        hour = time[4]
        minute = time[5]
        second = time[6]
        time_res ="{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}Z".format(years,month,day,hour,minute,second)
        temp_finale = "{0:.2f}".format(temp_v)
        #encode obj. to json
        temp_json = json.dumps({'ite_message': 
                                {'team_name': "blue", 
                                 'created_on': time_res, 
                                 'temperature':temp_finale}})
        buffer.append(temp_json)
 def set_time(self):
     # Set Time RTC
     from ntptime import settime
     try:
         settime()
         (y, m, d, h, mm, s, c, u) = time.localtime()
         self.config['starttime'] = '%d-%d-%d %d:%d:%d UTC' % (y, m, d, h,
                                                               mm, s)
     except:
         print('Cannot set time')
         pass
Esempio n. 30
0
 def handle_command(self, args):
     import ntptime
     if "-s" in args:
         ntptime.settime()
         print(self.get_localtime())
     else:
         secs = ntptime.time()
         if "-r" in args:
             print(secs)
         else:
             print(DateTimeCmd.get_datetime_from_secs(secs))
Esempio n. 31
0
async def nptset():
    while True:
        try:
            log.debug('{} : Timeset'.format(timeout()))
            settime()
            log.debug('{} : Timeset'.format(timeout()))
        except KeyboardInterrupt:
            raise
        except:
            log.warning('{} : timeout exception'.format(timeout()))
        await asyncio.sleep(3600)
Esempio n. 32
0
def sync_ntp_time():
    ''' In case we have active and connected wifi, sync RTC via NTP '''
    if not(sta_if.active()):
        print("Can't sync NTP. Wifi not active.")
    elif not(sta_if.isconnected()):
        print("Can't sync NTP. Wifi not connected.")
    else:
        ntptime.settime()
        dt = utime.localtime()
        dt = [str(d) for d in dt] # int to str for concat
        print("NTP time loaded:", "-".join(dt[0:3]), ":".join(dt[3:6]))
Esempio n. 33
0
 def perform(self) :
     import ntptime
     import core.util
     import utime
     old_secs = utime.time()
     ntptime.settime()
     new_secs = utime.time()
     skew = new_secs - old_secs
     self.min_skew = min(skew, self.min_skew)
     self.max_skew = max(skew, self.max_skew)
     if self.verbose :
         logging.info("ntpd: time set to {} UTC (skew: {} secs)".format(core.util.secs_to_string(new_secs), skew))
     return True
Esempio n. 34
0
def ntpupdate():
    import ntptime
    ntptime.settime()
Esempio n. 35
0
        d.measure()
        payload_t["raw_t"].append(d.temperature())
        payload_h["raw_h"].append(d.humidity())
        print("SENSOR: READ {} SUCCESS".format(i + 1))
    except:
        pass
        print("SENSOR: READ {} FAIL".format(i + 1))
    time.sleep(2)

# sensor off
print("SENSOR: POWER OFF")
p12.value(0)

# timestamp
print("SETTIME")
ntptime.settime()  # UTC from pool0.ntp.org
payload_t["timestamp"] = payload_h["timestamp"] = "{:0>4d}-{:0>2d}-{:0>2d}T{:0>2d}:{:0>2d}:{:0>2d}Z".format(
    *time.localtime()
)

# average readings
try:
    payload_t["t"] = sum(payload_t["raw_t"]) / len(payload_t["raw_t"])
    payload_h["h"] = sum(payload_h["raw_h"]) / len(payload_h["raw_h"])
except:
    pass

c = MQTTClient(client, broker, port=broker_port)
for _ in range(5):
    try:
        print("MQTT: CONNECTING ...")
Esempio n. 36
0
letters = "        "
if client_id in fleet:
    letters = fleet[client_id]

for i in range(0, len(letters)):
    nps[i] = neopixel.NeoPixel(machine.Pin(4), lights)
    set_char(letters[i], nps[i])

client.set_callback(gotMessage)
client.subscribe("/strip/command/" + client_id)

ntp_sync = False
while not ntp_sync:
    try:
        print("NTP time sync")
        ntptime.settime()
        ntp_sync = True
    except:
        print("NTP fail")


allOff()

while True:
    client.check_msg()
    if mode == "sleep":
        allOff()
        time.sleep(1)
    if mode == "cycle":
        cycle_pallet(15)
    if mode == "ho":