Beispiel #1
0
 def login(self, instance):
     if verify(self.ut.text,
               Hash(self.pt.text)):  #if userID and passwords match
         weight, machineid, endtime = getData(
             self.ut.text, ['weight', 'machineid', 'endtime'
                            ])  #gets current wash info of the user
         timing, studentid = getState(
             globalMachine,
             ['state', 'studentid'
              ])  #gets current userids and state of washing machine
         if weight == None:  #if user has no current washes
             weight = [globalWeight]
             machineid = [globalMachine]
             if timing == 0:  #of no laudry in the machine, puts time of putting laundry
                 endtime = [time() + washTime + timeOut]
             else:  #uses the first user's time of putting laundry
                 endtime = [timing + washTime + timeOut]
         else:  #adds new wash info to current washes
             weight += [globalWeight]
             machineid += [globalMachine]
             if timing == 0:
                 endtime += [time() + washTime + timeOut]
             else:
                 endtime += [timing + washTime + timeOut]
         if studentid == None:  #if machine is empty, create the user list
             studentid = [self.ut.text]
         else:  #add user info to user list
             studentid += [self.ut.text]
         putData(self.ut.text,
                 weight=weight,
                 machineid=machineid,
                 endtime=endtime,
                 debt=globalCost,
                 pmstate=0)  #updates users data to firebase
         if globalState == -1:  #if last user (washing machine starts wash immediately after this user), updates info accordingly
             putState(globalMachine,
                      door=1,
                      state=-1,
                      weight=globalWeight,
                      studentid=studentid)
         elif getState(
                 globalMachine, 'state'
         ) == 0:  #if first user, puts time of putting laundry and updates info accordingly
             putState(globalMachine,
                      door=1,
                      state=time(),
                      weight=globalWeight,
                      studentid=studentid)
         else:  #if neither, keeps first user timing and updates rest of info accordingly
             putState(globalMachine,
                      door=1,
                      weight=globalWeight,
                      studentid=studentid)
         global globalState
         globalState = timing
         self.manager.current = 'wash'
     else:
         self.ut.text = ''
         self.pt.text = ''
         self.fail.text = 'Incorrect User ID or Password'
Beispiel #2
0
 def get_time(self):
     time_now = time.time()
     if time_now - self.last_time_update >= 3600:
         ntptime.time()
         ntptime.settime()
         time_now = time.time()
         self.last_time_update = time_now
     return time.localtime(time_now + 3600 * 8)
Beispiel #3
0
def ntpsettime(IF_NTP):
    try:
      ntptime.time()
      ntptime.settime()
      rtc=machine.RTC()
      tampon1=utime.time()
      tampon2=tampon1+8*60*60
      rtc.datetime ( utime.localtime(tampon2)[0:3] + (0,) + utime.localtime(tampon2)[3:6] + (0,))
      IF_NTP=1
      return IF_NTP
    except:
      print('无法从NTP服务器获取时间')
      IF_NTP=0
      return IF_NTP
Beispiel #4
0
def setTime():
    # 补时间差8小时
    lsTime = []
    for i in range(3):
        lsTime.insert(i, localtime(ntptime.time()))
        #print(lsTime[i][3:5])
        sleep(1)
    if lsTime[0][3:5] == lsTime[1][3:5] and lsTime[0][3:5] == lsTime[2][
            3:5] and lsTime[1][3:5] == lsTime[2][3:5]:
        t = ntptime.time() + 28800
        tm = localtime(t)
        tm = tm[0:3] + (0, ) + tm[3:6] + (0, )
        RTC().datetime(tm)
        return True
    return False
Beispiel #5
0
def putState(
        machine,
        door=None,
        state=None,
        weight=None,
        studentid=None):  #changes the attributes of the machines on firebase
    if door != None:
        if door == 0:  #0 is the command that door is closed
            firebase.put('/washingmachine/%d/' % (machine), 'door', door)
        elif door == 1:  #1 is the command that door is opened and puts time of openning
            firebase.put('/washingmachine/%d/' % (machine), 'door', time())
    if state != None:
        firebase.put('/washingmachine/%d/' % (machine), 'state', state)
    if weight != None:
        try:  #accumulates weight if the type is correct, else clears all the weight
            weight += getState(machine, 'weight')
            firebase.put('/washingmachine/%d/' % (machine), 'weight', weight)
        except TypeError:
            firebase.put('/washingmachine/%d/' % (machine), 'weight', 0.0)
    if studentid != None:
        if studentid == 'clear':  #clears the list of studentids
            firebase.put('/washingmachine/%d/' % (machine), 'studentid', None)
        else:  #puts studentid list
            firebase.put('/washingmachine/%d/' % (machine), 'studentid',
                         studentid)
Beispiel #6
0
    def generate_sas_token(self,
                           expiry=3600):  # default to one hour expiry period
        urlencoder = urlencode.Urlencode()

        # Time Epoch: Unix port uses standard for POSIX systems epoch of 1970-01-01 00:00:00 UTC.
        # However, embedded ports use epoch of 2000-01-01 00:00:00 UTC.
        # 946684800 is the offset from embedded epoch and unix epoch bases

        now = 0

        while now == 0:
            try:
                now = ntptime.time() + 946684800
            except:
                time.sleep(1)

        ttl = now + expiry
        urlToSign = urlencoder.quote(self.sasUrl)

        msg = "{0}\n{1}".format(urlToSign, ttl).encode('utf-8')

        h = hmac.HMAC(bytearray(self.sharedAccessKey),
                      msg=msg,
                      digestmod=sha256)
        decodedDigest = base64.b64encode(h.digest()).decode()
        signature = urlencoder.quote(decodedDigest)
        sas = "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}".format(
            urlToSign, signature, ttl, self.eventHubPolicyName)
        # print(sas)
        return sas
Beispiel #7
0
def datetime_formatted():
    '''
    input data format:
        utime.localtime(ntptime.time())
        (2019, 4, 6, 14, 32, 50, 5, 96)
        (YEAR, M, D, TT, MM, SS, w, dy)
    Format the data and time to look like in
    google calendar for easies comparison:
        'Sun',  'Apr',  '07',  '2019',  '08:00:00', 'GMT+0300'
    '''
    day = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
    mon = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
           'Oct', 'Nov', 'Dec')

    t = utime.localtime(ntptime.time())
    now = []
    now.append(day[t[6]])  #add wekday
    now.append(mon[t[1] - 1])  #add mount
    if t[2] < 10:
        now.append('0{}'.format(t[2]))  #add date
    else:
        now.append(t[2])  #add date
    now.append('{}'.format(t[0]))  #add year
    # TODO: add nice timezone correction
    if t[4] < 10:
        now.append('{}:0{}:00'.format(t[3] + 3, t[4]))  #add time
    else:
        now.append('{}:{}:00'.format(t[3] + 3, t[4]))  #add time

    return now
Beispiel #8
0
def settimeDS3231(sclPin=5, sdaPin=4):
    """Code to set a DS3231 external Real Time Clock from an NTP server
    """
    from ntptime import time  # use the ntp method in firmware
    import urtc
    from machine import I2C, Pin
    import utime
    t_ntp = time()  # get time from the NTP server
    tm_ntp = utime.localtime(t_ntp)  # convert time format
    # initialize I2C interface & create I2C device for clock
    i2c = I2C(scl=Pin(sclPin), sda=Pin(sdaPin))
    rtc_ds3231 = urtc.DS3231(i2c)
    # get time from the DS3231
    datetime_ds3231 = rtc_ds3231.datetime()
    print('Before resetting: rtc_ds3231.datetime() = ', datetime_ds3231)
    new_datetime = urtc.datetime_tuple(year=tm[0],
                                       month=tm[1],
                                       day=tm[2],
                                       hour=tm[3],
                                       minute=tm[4],
                                       second=tm[5])
    print('setting DS3231 datetime from NTP to: ', new_datetime)
    rtc_ds3231.datetime(new_datetime)  # Set new ds3231 time
    # confirm new time was set on ds3231
    datetime_ds3231 = rtc_ds3231.datetime()
    print('After resetting: rtc_ds3231.datetime() = ', datetime_ds3231)
Beispiel #9
0
 def __init__(self):
     utime.set_time(ntptime.time())
     self.year = 2000
     self.month = 1
     self.day = 1
     self.time_led_on = 0
     self.time_led_off = 0
Beispiel #10
0
 def main(self):
     if GPIO.input(
             self.doorbutton
     ):  #if door closed button is pressed, switches off green LED and switches on red LED
         GPIO.output(self.openlight, 0)
         GPIO.output(self.closelight, 1)
         putState(self.machine, door=0)
     if GPIO.input(self.washbutton) and GPIO.input(
             self.washlight
     ):  #if it was washing finished washing button is pressed, switches off amber LED and informs firebase wash is done
         GPIO.output(self.washlight, 0)
         putState(self.machine, state=-2)
         self.washing = False
     if not self.washing:  #if its not washing, it will check firebase if door should open
         if getState(self.machine, 'door') != 0:
             GPIO.output(self.closelight, 0)
             GPIO.output(self.openlight, 1)
         else:  #check firebase if washing should begin and updates wash time to users
             GPIO.output(self.openlight, 0)
             GPIO.output(self.closelight, 1)
             if getState(self.machine, 'state') == -1:
                 GPIO.output(self.washlight, 1)
                 for student in getState(self.machine, 'studentid'):
                     machineid, endtime = getData(student,
                                                  ['machineid', 'endtime'])
                     for machine in range(len(machineid)):
                         if machineid[machine] == self.machine:
                             endtime[machine] = time() + washTime
                     putData(student, endtime=endtime)
                     self.washing = True
Beispiel #11
0
    def save_time(self, ntp=0):
        if ntp:
            ntpTime = ntptime.time() + TIME_ZONE
            convertToDatetime = utime.localtime(ntpTime)
            convertToDatetime = convertToDatetime[0:3] + (
                0, ) + convertToDatetime[3:6] + (0, )
            rtc.init(convertToDatetime)

        (YY, MM, mday, hh, mm, ss, wday,
         yday) = utime.localtime()  # Based on RTC
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 0, tobytes(dec2bcd(ss)))
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 1, tobytes(dec2bcd(mm)))
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 2,
                                tobytes(dec2bcd(hh)))  # Sets to 24hr mode
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 3, tobytes(
            dec2bcd(wday + 1)))  # 1 == Monday, 7 == Sunday
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 4,
                                tobytes(dec2bcd(mday)))  # Day of month
        if YY >= 2000:
            self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5,
                                    tobytes(dec2bcd(MM)
                                            | 0b10000000))  # Century bit
            self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6,
                                    tobytes(dec2bcd(YY - 2000)))
        else:
            self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, tobytes(dec2bcd(MM)))
            self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6,
                                    tobytes(dec2bcd(YY - 1900)))
Beispiel #12
0
def connect(mdns_name=None):
    """connect to wifi, get ntp time, advertise hostname (if not None)"""
    wlan = network.WLAN(network.STA_IF)
    if wlan.isconnected(): return
    wlan.active(True)
    if not mdns_name:
        uid = machine.unique_id()
        mdns_name = "esp32_" + "".join("{:02x}".format(x) for x in uid)
    # known on net as mdns_name.local
    wlan.config(dhcp_hostname=mdns_name)
    print("Connecting to WLAN ... ", end="")
    wlan.connect(getattr(secrets, 'wifi_ssid', 'SSID'),
                 getattr(secrets, 'wifi_pwd', ''))
    # wait for connection to be established ...
    for _ in range(30):
        if wlan.isconnected(): break
        time.sleep_ms(100)
    if not wlan.isconnected():
        print("Unable to connect to WiFi!")
        wlan.disconnect()
        return
    print("IP", wlan.ifconfig()[0])
    print("mDNS", mdns_name + ".local")
    # set clock to local time
    tm = time.localtime(ntptime.time() + getattr(secrets, 'tz_offset', 0))
    print("time", tm)
    machine.RTC().datetime(
        (tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
Beispiel #13
0
    def __init__(self, wlan, SSID, PASSWD):
        #init wlan
        self.wlan = wlan
        self.SSID = SSID
        self.PASSWD = PASSWD

        #init time
        print('ntp_url:', self.ntp_url)
        ntptime.host = self.ntp_url
        print('ntp_host:', ntptime.host)
        ntptime.time()
        ntptime.settime()
        self.last_time_update = time.time()
        print('init_time:', time.localtime(self.last_time_update + 3600 * 8))

        #init data
        print('dat_url:', self.dat_url)

        #init display mod
        '''
        mode:
            0:cycle
            1:temp only
            2:pres only
            3:water only
            4:humi only
        '''
        self.mode = 0
        '''
        last:
            0:temp
            1:pres
            2:water
            3:humi
        '''
        self.last = 0

        #init tft
        print('init TFT...')
        spi = SPI(1, baudrate=32000000, polarity=0, phase=0)
        self.tft = TFT(spi, 2, 16, 0)
        self.tft.init_7735(self.tft.GREENTAB128x128)
        self.tft.fill(TFT.WHITE)
        self.tft.text((5, 10), "initlizing", TFT.YELLOW, 2, nowrap=True)
        self.tft.text((5, 50), "please wait", TFT.YELLOW, 2, nowrap=True)

        self.run()
Beispiel #14
0
def sync_time_tim(t):
    while True:
        try:
            connect_to_wifi()
            settime(ntptime.time())
            return
        except:
            pass
Beispiel #15
0
def settime_th():
    t = ntptime.time() + (7 * 3600)
    import machine
    import utime
    tm = utime.localtime(t)
    tm = tm[0:3] + (0, ) + tm[3:6] + (0, )
    machine.RTC().datetime(tm)
    print(utime.localtime())
def ntpsync():
    import ntptime
    h = c.get("ntphost")
    if h: ntptime.host = h
    with wifi:
        y, m, d, h, mi, s, _, _ = time.localtime(ntptime.time() +
                                                 TZ_DELTA_SECS)
    settime(y, m, d, 1, h, mi, s)
Beispiel #17
0
def ip_status():  #判断是否连接了路由器
    ip = wlan.ifconfig()
    if ip[1] != '0.0.0.0':
        try:
            return time.localtime(ntptime.time())
        except OSError:
            return '校对操作过快,请稍后再试!'
    else:
        return 'Unconnected'
def setTime():
    logger.log('Setting time...')
    if connection.test():
        tm = utime.gmtime(ntptime.time())
        machine.RTC().datetime(
            (tm[0], tm[1], tm[2], tm[6] + 1, tm[3] + 2, tm[4], tm[5], 0))
        logger.log('Time is set!')
    else:
        logger.log('Time could not be set!')
Beispiel #19
0
def set_rtc_from_ntp(config):
    global boot_time
    try:
        mytime = utime.localtime(ntptime.time() +
                                 int(config[cfg.idx('tz_offset')]))
    except:
        mytime = utime.localtime()
    boot_time = mytime
    year, month, day, hour, minute, second, weekday, yearday = mytime
    rtc.datetime((year, month, day, weekday, hour, minute, second, 0))
def showtime():
    global t, h
    t = ntptime.time()
    t = utime.localtime(t)
    if t[3] >= 4:
        h = t[3] - 4
    else:
        h = t[3] + 20
    b = str(h) + ':' + str(t[4]) + ':' + str(t[5])
    displaycontent(str=b)
Beispiel #21
0
def ip_status():  #判断是否连接了路由器
    #ip = wlan.ifconfig()
    #if ip[1] != '0.0.0.0':
    if wlan.isconnected():
        try:
            return time.localtime(ntptime.time())
        except:
            return '校对操作过快,请稍后再试!'
    else:
        return 'Unconnected'
Beispiel #22
0
def set_ntp_time(timer):
    ntptime.host = "tempus1.gum.gov.pl"
    for i in range(1, 10):
        try:
            t = ntptime.time()
            tm = utime.localtime(t)
            tm = tm[0:3] + (0, ) + tm[3:6] + (0, )
            RTC().datetime(tm)
            break
        except OSError:
            continue
 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))
Beispiel #24
0
def fetch_ntp_time(ntp_host=None):
    import ntptime
    if ntp_host:
        ntptime.host = ntp_host
    SECONDS_1970_TO_2000 = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0))
    # NTP returns seconds since 1900
    # The ntptime lib adjusts that to seconds since 2000
    seconds_2000_to_now = ntptime.time()
    # The Pycom time lib uses seconds since 1970
    seconds_1970_to_now = SECONDS_1970_TO_2000 + seconds_2000_to_now
    return seconds_1970_to_now
Beispiel #25
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))
Beispiel #26
0
def gettime():
    suceeded = False
    while suceeded == False:
        try:
            tm = utime.localtime(ntptime.time())
            print('ntp', tm)
            tm = tm[0:3] + (0, ) + tm[3:6] + (0, )
            machine.RTC().datetime(tm)
            return utime.localtime()
        except:
            time.sleep(1)
            pass
Beispiel #27
0
def setntp(ntpserver, timezone):
    res = False
    try:
        import ntptime
        ntptime.host = ntpserver
        t = ntptime.time()
        tm = utime.gmtime(t + (timezone * 60))
        machine.RTC().datetime(
            (tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
        res = True
    except:
        res = False
    return res
Beispiel #28
0
        def update():
            global _startup_time
            try:
                self._logger.info('Get NTP time')

                lock = _thread.allocate_lock()
                with lock:
                    _startup_time = ntptime.time() - time.time()

                self._logger.info('_startup_time=%s' % _startup_time)
            except Exception as e:
                self._logger.warning(e)
                sys.print_exception(e, self._log_stream)
Beispiel #29
0
def resolve_dst_and_set_time():
    global TIMEZONE_DIFFERENCE
    global dst_on
    dst_on = 1
    TIMEZONE_DIFFERENCE = 1
    print(' resolve_dst_and_set_time()..... ')
    
    # This is most stupid thing what humans can do!
    # Rules for Finland: DST ON: March last Sunday at 03:00 + 1h, DST OFF: October last Sunday at 04:00 - 1h
    # Sets localtime to DST localtime
    '''
    if network.WLAN(network.STA_IF).config('essid') == '':
        now = mktime(localtime())
        if DEBUG_ENABLED == 1:
            print("Network down! Can not set time from NTP!")
    else:
        now = ntptime.time()
    '''
    now = ntptime.time()
    #(year, month, mdate, hour, minute, second, wday, yday) = utime.localtime(now)
    
    year = utime.localtime(now)[0]  
    if year < 2020:
        if DEBUG_ENABLED == 1:
            print("Time not set correctly!")
        return False

    dstend = utime.mktime((year, 10, (31 - (int(5 * year / 4 + 1)) % 7), 4, 0, 0, 0, 6, 0))
    dstbegin = utime.mktime((year, 3, (31 - (int(5 * year / 4 + 4)) % 7), 3, 0, 0, 0, 6, 0))

    if TIMEZONE_DIFFERENCE >= 0:
        if (now > dstbegin) and (now < dstend):
            dst_on = True
            ntptime.NTP_DELTA = 3155673600 - ((TIMEZONE_DIFFERENCE + 1) * 3600)
        else:
            dst_on = False
            ntptime.NTP_DELTA = 3155673600 - (TIMEZONE_DIFFERENCE * 3600)
    else:
        if (now > dstend) and (now < dstbegin):
            dst_on = False
            ntptime.NTP_DELTA = 3155673600 - (TIMEZONE_DIFFERENCE * 3600)
        else:
            dst_on = True
            ntptime.NTP_DELTA = 3155673600 - ((TIMEZONE_DIFFERENCE + 1) * 3600)
    if dst_on is None:
        if DEBUG_ENABLED == 1:
            print("DST calculation failed!")
            return False
    else:
        ntptime.settime()  
Beispiel #30
0
def get_time(userID, i):
    """Called when makeReply is getting washInfo, to get information on time remaining"""
    endTimeList = firebase.get('/Accounts/%s/endtime' % (str(userID)))
    currentTime = time()
    #If endtime is not logged returns error
    if endTimeList == None:
        return None
    else:
        iTime = endTimeList[i]
        diff = iTime - currentTime
        if diff > 0:
            return formatTime(diff)
        else:
            return 0
Beispiel #31
0
def set_ntp_time(a_offset=0):
    """ Set time using NTP and given offset in seconds.

    The board does not support timezones, so time.localtime() will return UTC time.
    If real local time needs to be used then a_offset should be considered (in seconds).
    """
    import ntptime
    import machine
    import utime

    t = ntptime.time() + a_offset
    tm = utime.localtime(t)
    tm = tm[0:3] + (0, ) + tm[3:6] + (0, )
    machine.RTC().datetime(tm)