def rtc_ntp_sync(TZ=0, timeout_s = 30): from machine import RTC print("sync rtc via ntp, TZ=", TZ) rtc = RTC() print("synced?", rtc.synced()) rtc.ntp_sync('nl.pool.ntp.org') print("synced?", rtc.synced()) #time.sleep_ms(750) time.timezone(TZ * 3600) timeout_ms = 1000 * timeout_s for i in range(0, timeout_ms): if rtc.synced(): print("rtc is synced after", i/1000, "s") # if rtc.now()[0] == 1970: # print() break if i % 100 == 0: print(".", end="") time.sleep_ms(1) if not rtc.synced(): raise Exception("RTC did not sync in", timeout_ms/1000, "s") print("rtc.now", rtc.now()) print("time.gmtime", time.gmtime()) print("time.localtime", time.localtime()) print("gmt ", end=" ") pretty_gmt() print("local", end=" ") pretty_local()
def setRTCLocalTime(): rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org") time.sleep_ms(750) print('\nRTC Set from NTP to UTC', rtc.now()) time.timezone(3600) # GMT + 1 Copenhagen, Amsterdan, Paris print('Adjusted from UTC to GMT+1', time.localtime(), '\n')
def rtc_init(): global rtc_synced rtc = RTC() rtc.ntp_sync('pool.ntp.org', update_period=15) print('Waiting for RTC/NTP sync...') chrono = Timer.Chrono() chrono.start() while not rtc.synced(): # wait for 30 seconds, then give up and try manual NTP sync if chrono.read() > 30: print('Sync timed out after %s seconds...' % chrono.read()) rtc.ntp_sync(None) break time.sleep(1) if rtc.synced(): print('RTC Set from NTP daemon to UTC:', rtc.now()) rtc_synced = True else: print('Fetching time from NTP server manually...') try: NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1b addr = socket.getaddrinfo('pool.ntp.org', 123)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(3) s.sendto(NTP_QUERY, addr) msg = s.recv(48) s.close() # 70 years difference between NTP and Pycom epoch val = struct.unpack("!I", msg[40:44])[0] - 2208988800 tm = time.localtime(val) rtc.init(tm) rtc_synced = True gc.collect() except socket.timeout: print('Timed out while fetching time from remote server.') if not rtc.synced() and rtc_synced: print('RTC Set from manual NTP call to UTC:', rtc.now()) # adjust timezone if rtc_synced: # UTC-7/MST for testing time.timezone(-7*60*60) print('RTC adjusted from UTC to local timezone:', time.localtime()) else: print('Unable to set RTC', rtc.now()) print('Resetting NTP sync to 15 minutes') rtc.ntp_sync('pool.ntp.org', 60*15)
def create_venue_submission(): # DONE: insert form data as a new Venue record in the db, instead # DONE: modify data to be the data object returned from db insertion error = False form = VenueForm() try: if form.validate_on_submit(): name = request.form['name'] city = request.form['city'] state = request.form['state'] address = request.form['address'] phone = request.form['phone'] genres = request.form.getlist('genres') fb_link = request.form['facebook_link'] img_link = request.form['image_link'] website_link = request.form['website_link'] seeking_talent = True if 'seeking_talent' in request.form else False seeking_description = request.form['seeking_description'] venue = Venue( name=name, city=city, state=state, address=address, phone=phone, genres=genres, facebook_link=fb_link, image_link=img_link, website=website_link, seeking_talent=seeking_talent, seeking_description=seeking_description, created_at=datetime.now(timezone(timedelta(hours=-3))), updated_at=datetime.now(timezone(timedelta(hours=-3)))) db.session.add(venue) db.session.commit() else: for e in form.errors: flash('An error has occurred. {}'.format(form.errors[e])) db.session.rollback() return render_template('pages/home.html') except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() # DONE: on unsuccessful db insert, flash an error instead. if error: flash('An error has occurred. Venue {} could not be listed.'.format( request.form['name'])) else: # on successful db insert, flash success flash('Venue {} was successfully listed.'.format(request.form['name'])) # e.g., flash('An error occurred. Venue ' + data.name + ' could not be listed.') # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/ return render_template('pages/home.html')
def create_artist_submission(): # called upon submitting the new artist listing form # DONE: insert form data as a new Venue record in the db, instead # DONE: modify data to be the data object returned from db insertion error = False form = ArtistForm() try: if form.validate_on_submit(): name = request.form['name'] city = request.form['city'] state = request.form['state'] phone = request.form['phone'] genres = request.form.getlist('genres') fb_link = request.form['facebook_link'] img_link = request.form['image_link'] website_link = request.form['website_link'] seeking_venue = True if 'seeking_venue' in request.form else False seeking_description = request.form['seeking_description'] artist = Artist( name=name, city=city, state=state, phone=phone, genres=genres, facebook_link=fb_link, image_link=img_link, website=website_link, seeking_venue=seeking_venue, seeking_description=seeking_description, created_at=datetime.now(timezone(timedelta(hours=-3))), updated_at=datetime.now(timezone(timedelta(hours=-3)))) db.session.add(artist) db.session.commit() else: for e in form.errors: flash('An error has occurred. {}'.format(form.errors[e])) db.session.rollback() return render_template('pages/artists.html') except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() # DONE: on unsuccessful db insert, flash an error instead. # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.') if error: flash('An error has occurred. Artist {} could not be listed.'.format( request.form['name'])) else: # on successful db insert, flash success flash('Artist ' + request.form['name'] + ' was successfully listed!') return render_template('pages/home.html')
def set_RTC(): connect_LTE() rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org", 3600) while not rtc.synced(): debugprint('Syncing RTC...') time.sleep_ms(750) debugprint('RTC Set from NTP to UTC: ' + str(rtc.now())) time.timezone(3600) debugprint('Adjusted from UTC to EST timezone: ' + str(time.localtime())) disconnect_LTE()
def datetime(): rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org") #adjust your local timezone, by default, NTP time will be GMT time.timezone(8 * 60**2) x = time.localtime() datetimeFormat = " [ " + str(x[2]) + "/" + str(x[1]) + "/" + str( x[0]) + " | " + str(x[3]) + ":" + str(x[4]) + " ] " return datetimeFormat
def sync_time(): rtc = machine.RTC() while not rtc.synced(): rtc.ntp_sync("se.pool.ntp.org") machine.idle() if not rtc.synced(): print("Failed to sync time. Trying again...") time.sleep(1) #time.timezone(3600) # adjust for local time zone (Sweden Winter time) time.timezone(7200) # adjust for local time zone (Sweden Summer time) print("Time synced to: " + present(time.localtime()))
def edit_artist_submission(artist_id): # DONE: take values from the form submitted, and update existing # artist record with ID <artist_id> using the new attributes error = False form = ArtistForm() try: if form.validate_on_submit(): artist = Artist.query.get(artist_id) artist.name = request.form['name'] artist.city = request.form['city'] artist.state = request.form['state'] artist.phone = request.form['phone'] artist.genres = request.form.getlist('genres') artist.facebook_link = request.form['facebook_link'] artist.image_link = request.form['image_link'] artist.website = request.form['website_link'] artist.seeking_venue = True if 'seeking_venue' in request.form else False artist.seeking_description = request.form['seeking_description'] artist.updated_at = datetime.now(timezone(timedelta(hours=-3))) db.session.commit() else: for e in form.errors: flash('An error has occurred. {}'.format(form.errors[e])) db.session.rollback() return render_template('pages/edit_artist.html') except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() return redirect(url_for('show_artist', artist_id=artist_id))
def edit_venue_submission(venue_id): # DONE: take values from the form submitted, and update existing # venue record with ID <venue_id> using the new attributes error = False form = VenueForm() try: if form.validate_on_submit(): venue = Venue.query.get(venue_id) venue.name = request.form['name'] venue.city = request.form['city'] venue.state = request.form['state'] venue.address = request.form['address'] venue.phone = request.form['phone'] venue.genres = request.form.getlist('genres') venue.fb_link = request.form['facebook_link'] venue.img_link = request.form['image_link'] venue.website_link = request.form['website_link'] venue.seeking_talent = True if 'seeking_talent' in request.form else False venue.seeking_description = request.form['seeking_description'] venue.updated_at = datetime.now(timezone(timedelta(hours=-3))) db.session.commit() else: for e in form.errors: flash('An error has occurred. {}'.format(form.errors[e])) db.session.rollback() return render_template('pages/edit_venue.html') except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() return redirect(url_for('show_venue', venue_id=venue_id))
def _getMBRegisters(CT): if (_getDReg(40003) == 0): return False # zero is not a valid voltage! global data unixLocalTime = time.time() + time.timezone() data['totalActiveEnergy'] = _getDReg( 40001 ) / 10 * CT # read Input Active Energy Accumulator in units of 0.1 kWh data['voltage'] = _getReg(40003) / 100.0 # read voltage data['current'] = _getDReg(40004) / 1000.0 * CT # read current data['activepower'] = _getDReg(40006) / 10.0 * CT # read active power data['apparentpower'] = _getDReg(40008) / 10.0 * CT # read apparent power data['reactivepower'] = _getDReg(40010) / 10.0 * CT # read reactive power data['frequency'] = _getReg(40012) / 100.0 # read frequency data['powerfactor'] = _getReg(40013) / 1000.0 # read frequency data['importActiveEnergy'] = _getDReg( 40014) / 10 * CT # read Input Active Energy data['exportActiveEnergy'] = _getDReg( 40016) / 10 * CT # read Export Active Energy data['importReactiveEnergy'] = _getDReg( 40020) / 10 * CT # read Input Reactive Energy data['exportReactiveEnergy'] = _getDReg( 40022) / 10 * CT # read Export Reactive Energy data['totalReactiveEnergy'] = _getDReg( 40024) / 10 * CT # read Input Reactive Energy data['timestamp'] = unixLocalTime return True
def _getInstDataM11(): unixLocalTime = time.time() + time.timezone() sMsg = ('"V":{:.1f},"I":{:.2f},"P":{:.1f},"Q":{:.1f},"S":{:.1f},' '"PF":{:.2f},"Mem":{:d},"T":{:d}').format( data['voltage'], data['current'], data['activepower'], data['reactivepower'], data['apparentpower'], data['powerfactor'], gc.mem_free(), unixLocalTime) return (sMsg)
def create_show_submission(): # called to create new shows in the db, upon submitting new show listing form # DONE: insert form data as a new Show record in the db, instead error = False form = ShowForm() show_id = db.session.query(db.func.max(Show.id)).scalar() try: if form.validate_on_submit(): id = show_id + 1 venue_id = request.form['venue_id'] artist_id = request.form['artist_id'] start_time = request.form['start_time'] show = Show(id=id, venue_id=venue_id, artist_id=artist_id, start_time=start_time, created_at=datetime.now(timezone(timedelta(hours=-3))), updated_at=datetime.now(timezone(timedelta(hours=-3)))) db.session.add(show) db.session.commit() else: for e in form.errors: flash('An error has occurred. {}'.format(form.errors[e])) db.session.rollback() return render_template('pages/shows.html') except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() # DONE: on unsuccessful db insert, flash an error instead. if error: flash('An error has occurred. Show could not be listed.') else: # on successful db insert, flash success flash('Show was successfully listed!') # e.g., flash('An error occurred. Show could not be listed.') # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/ return render_template('pages/home.html')
def _liAlarmHandler(ze, logger, phase): if logger != None: logger.info("Alarm Loop impendance: " + str(ze) + " mOhm") if ze == None: return unixLocalTime = time.time() + time.timezone() #timetuple = time.localtime() #timeslot10M = int(timetuple[4] / 10) + timetuple[3] * 6 # 1 - 144 10 min timeslot in a day #timeslot600s = int((timetuple[5] + timetuple[4]*60 + timetuple[3] * 3600 - timeslot10M * 10 * 60) / 3 ) # 1-200 3s timeslot in the 10 m slot currentAlarmLoraMessageToSend = buildLIAlarmMessage( unixLocalTime, int(ze), phase) res = LoraQueueP5.put(currentAlarmLoraMessageToSend) if res == LoraQueueP5.SUCCESS: logger.debug("Add msg to LPQ5: " + str(currentAlarmLoraMessageToSend)) else: logger.error("LQP5 is full")
def PowerFailCb(logger): power_fail = Pin(POWER_FAIL_PIN) if debouncedPFSignal(power_fail) == 1: #stopTasksButLora() # save power by leaving all non essential tasks ASAP pycom.nvs_set(POWER_FAIL_STATE, MODE_POWER_FAIL) unixLocalTime= time.time() + time.timezone() pycom.nvs_set(POWER_FAIL_TS, unixLocalTime) currentAlarmLoraMessageToSend = buildPFAlarmMessage(unixLocalTime) lora_queue_immediate_semaphore.acquire(0) rand=int(getRandom() * 2000) # 0-2000 value time.sleep_ms(rand) # just randow m wait of 3s LoraQueueImmediate.put(currentAlarmLoraMessageToSend) lora_queue_immediate_semaphore.acquire(1,2) # wait 2s max for msg to be sent by the Lora task time.sleep_ms(WAIT_TIME_BEFORE_SLEEP) # time for the LoRA MAC layer to send that message rand=int(getRandom() * 20) # 0-20 value machine.deepsleep((WAKEUP_DELAY+rand)*1000) # GO TO SLEEP NOW AND PRESERVE POWER
def show_venue(venue_id): # shows the venue page with the given venue_id # DONE: replace with real venue data from the venues table, using venue_id venue = Venue.query.filter_by(id=venue_id).first() fix_json_array(venue, "genres") if not venue: return render_template('errors/404.html') past_shows = [] upcoming_shows = [] for show in venue.shows: show = { "artist_id": show.artist_id, "artist_name": show.artist.name, "artist_image_link": show.artist.image_link, "start_time": show.start_time } if show["start_time"] <= datetime.now(timezone(timedelta(hours=-3))): past_shows.append(show) else: upcoming_shows.append(show) data = { "id": venue.id, "name": venue.name, "genres": venue.genres, "address": venue.address, "city": venue.city, "state": venue.state, "phone": venue.phone, "website": venue.website, "facebook_link": venue.facebook_link, "seeking_talent": venue.seeking_talent, "seeking_description": venue.seeking_description, "image_link": venue.image_link, "past_shows": past_shows, "past_shows_count": len(past_shows), "upcoming_shows": upcoming_shows, "upcoming_shows_count": len(upcoming_shows) } return render_template('pages/show_venue.html', venue=data)
def eventTask(): global event_wdt_lock, event_stop_flag global voltageAlarmStateThresholds logger = Logger(name = 'EVENT ' + __version__,level=logging.DEBUG,filename=None) logger.debug('** Event Task started **') voltageAlarmState = [ALARM_VERY_LOW,ALARM_VERY_LOW,ALARM_VERY_LOW] voltageAlarmStateThresholds = { 1: int(getConfigurationVariable(NVS_HV_ALARM)), 2: int(getConfigurationVariable(NVS_VHV_ALARM)), 3: int(getConfigurationVariable(NVS_LV_ALARM)), 4: int(getConfigurationVariable(NVS_VLV_ALARM)), } deviceType=int(getConfigurationVariable(NVS_DEVICE_TYPE)) while not event_stop_flag.locked(): unixLocalTime= time.time() + time.timezone() if event_wdt_lock.locked(): event_wdt_lock.release() # Tell the WDT Event is alive counter = 10 while counter > 0: counter = counter -1 # ----------------- High priority Processing (within 100 ms) ------------------------- if power_fail_semaphore.acquire(0) == True : PowerFailCb(logger) # other high priority tasks go here time.sleep_ms(100) # -------------------------------Low priority Processing (every 1s) ProcessC2DMessage(logger,deviceType) # Process any message from the Cloud if time_set_flag.locked() == False : voltageAlarmState = VoltageAlarmCheck(logger,voltageAlarmState,unixLocalTime,deviceType) # check the Voltages logger.error('** Event Task ended **')
def show_artist(artist_id): # shows the artist page with the given artist_id # DONE: replace with real artist data from the artist table, using artist_id artist = Artist.query.filter_by(id=artist_id).first() fix_json_array(artist, "genres") if not artist: return render_template('errors/404.html') past_shows = [] upcoming_shows = [] for show in artist.shows: show = { "venue_id": show.venue_id, "venue_name": show.venue.name, "venue_image_link": show.venue.image_link, "start_time": show.start_time } if show["start_time"] <= datetime.now(timezone(timedelta(hours=-3))): past_shows.append(show) else: upcoming_shows.append(show) data = { "id": artist.id, "name": artist.name, "genres": artist.genres, "city": artist.city, "state": artist.state, "phone": artist.phone, "seeking_venue": artist.seeking_venue, "seeking_description": artist.seeking_description, "facebook_link": artist.facebook_link, "website": artist.website, "image_link": artist.image_link, "past_shows": past_shows, "past_shows_count": len(past_shows), "upcoming_shows": upcoming_shows, "upcoming_shows_count": len(upcoming_shows) } return render_template('pages/show_artist.html', artist=data)
class WxPayConf(object): """配置账号信息""" # ===============【基本信息设置】=================== AppId = "" AppSecret = "" MchId = "" # 商户支付密钥key Merchant_key = "" # ===============【异步通知url设置】================ NOTIFY_URL = "http://" # ================【证书路径】====================== # # 证书路径,应该填写绝对路径(仅退款、撤销订单时需要) SSLCERT_PATH = "../cert/apiclient_cert.pem" SSLKEY_PATH = "../cert/apiclient_key.pem" # ================【curl超时设置】================== CURL_TIMEOUT = 30 # 商户订单 时间+随机数 now = datetime.fromtimestamp(time.time(), tz=time.timezone('Asia/Shanghai')) OUT_TRADE_NO = '{0}{1}{2}'.format(MchId, now.strftime('%Y%m%d%H%M%S'), random.randint(1000, 10000))
def print_debug_local(level, msg): """ Print log messages. log messages will be stored in the device so the user can access that using FTP or Flash OTA. """ if DEBUG is not None and level <= DEBUG: print_debug(0, 'adding local log') rtc = RTC() if not rtc.synced(): rtc.ntp_sync("pool.ntp.org") while not rtc.synced(): pass current_year, current_month, current_day, current_hour, current_minute, current_second, current_microsecond, current_tzinfo = rtc.now() # noqa msg = '\n {}-{}-{} {}:{}:{} (GMT+{}) >>> {}'.format( current_day, current_month, current_year, current_hour, current_minute, current_second, timezone(), msg ) try: fsize = os.stat('logs.log') if fsize.st_size > 1000000: # logs are bigger than 1 MB os.remove("logs.log") except Exception: pass log_file = open('logs.log', 'a+') log_file.write(msg) log_file.close()
def FixedOffset(minutes): return timezone(timedelta(minutes=minutes))
import asyncio import time # Event loop is a routine that can make two or more things at same time. # The 'Await' means ..... safe point of async def go to another coroutine. # This is a respose to solve very intensive I.O operations. # All this stuff runs under the event loop. contador1 = 0 contador2 = 0 contador3 = 0 star_time = time.timezone() async def func1(): global contador1 while True: contador1 += 1 print("This is function One", contador1) await asyncio.sleep(1) async def func2(): global contador2 while True: contador2 += 1 print("This is function Two", contador2)
The test_oracle file. Authors: Wang Jianxiang ([email protected]) """ import re from time import timezone import cx_Oracle import os os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' from datetime import datetime from pytz import utc from pytz import timezone cst_tz = timezone('Asia/Shanghai') utc_tz = timezone('UTC') utcnow = datetime.utcnow() print(utcnow) utcnow = utcnow.replace(tzinfo=utc_tz) china = utcnow.astimezone(cst_tz) print(china) now = datetime.utcnow().replace(tzinfo=utc_tz).astimezone(cst_tz) print now # now.fromtimestamp() def table_exists(cursor, table_name): #这个函数用来判断表是否存在 stmt = "select Table_name from user_tables" cursor.execute(stmt)
import machine import time from network import WLAN import config wlan = WLAN(mode=WLAN.STA) # get current object, without changing the mode if not wlan.isconnected(): # change the line below to match your network ssid, security and password wlan.connect(config.WiFiSSID, auth=(WLAN.WPA2, config.WiFiKey)) while not wlan.isconnected(): machine.idle() # save power while waiting print("WiFi connected ...") print(wlan.ifconfig()) rtc = machine.RTC() rtc.init((2019, 11, 21, 20, 00, 0, 0, 0)) rtc.ntp_sync('pool.ntp.org') while not rtc.synced(): time.sleep_ms(100) time.timezone(3600) print('Time synced: {}'.format(time.localtime()))
try: try: from Config import useGPS, G_Tx, G_Rx import GPS_dexter as GPS except: useGPS = None if useGPS: useGPS = GPS.GROVEGPS(port=len(uart),baud=9600,debug=False,pins=(G_Tx,G_Rx)) uart.append(len(uart)) print("GPS UART %d: Rx ~> Tx %s, Tx ~> Rx %s" % (len(uart),G_Tx, G_Rx)) if useGPS: if not useGPS.date: useGPS.UpdateRTC() if useGPS.date: now = localtime() if 3 < now[1] < 11: timezone(7200) # simple DST else: timezone(3600) display('%d/%d/%d %s' % (now[0],now[1],now[2],('mo','tu','we','th','fr','sa','su')[now[6]])) display('time %02d:%02d:%02d' % (now[3],now[4],now[5])) thisGPS[LON] = round(float(useGPS.longitude),5) thisGPS[LAT] = round(float(useGPS.latitude),5) thisGPS[ALT] = round(float(useGPS.altitude),1) else: display('GPS bad QA %d' % useGPS.quality) useGPS.ser.deinit() useGPS = None else: display('No GPS') except Exception as e: display('GPS failure', (0,0), clear=True) print(e)
def ProcessC2DMessage(logger,deviceType): global voltageAlarmStateThresholds LoraMessage = LoraQueueRx.get() numberOfPhase = getNumberOfPhase(deviceType) if LoraMessage != None: try: hexdata = binascii.hexlify(LoraMessage) logger.info("Received Msg: " + str(hexdata) + " : Len:" + str(len(LoraMessage))) # TIME SYNC = > Device is always using Mike time (NZST) # TODO refactor this msg = unpackDataFromBinary(LoraMessage) if (msg[C2D_REQUEST] == MESSAGE_TYPE_TIME_RESPONSE): logger.debug("Received Time Synch Msg") timeoffset = 0 timezone = msg[7] if timezone == 122: # zulu time timeoffset = 12*3600 if timezone == 109: # mike time timeoffset = 0 time.timezone(timeoffset) rtc=RTC() rtc.init(( int(msg[1])+2000, int(msg[2]), int(msg[3]),int(msg[4]), int(msg[5]), int(msg[6]), 0, 0)) logger.debug(time.localtime()) if time_set_flag.locked(): time_set_flag.release() # we know the time! if msg[C2D_REQUEST] == MESSAGE_TYPE_C2D_SET_REQUEST: logger.debug("Received Set request Msg Id:" + str(msg[C2D_SET_REQ_ID]) + "val:" + str(msg[C2D_SET_REQ_VAL])) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_UPGRADE and msg[C2D_SET_REQ_VAL] == 1 : upgradeFirmware(UPGRADE_URL) # start the updgrade if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_RELAY: LED_OUT = Pin(LED_OUT_PIN) LED_OUT.value(int(msg[C2D_SET_REQ_VAL])) logger.debug("LED OUT state:" + str(msg[C2D_SET_REQ_VAL])) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_RESET and int(msg[C2D_SET_REQ_VAL]) == 1 : machine.reset() if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_RADIO_OFFSET : #validate radio_delay = int(msg[C2D_SET_REQ_VAL]) if radio_delay > 0 and radio_delay < 300 : setConfigurationVariable(NVS_RADIO_DELAY,radio_delay) logger.debug("New Radio delay :" + str(radio_delay)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_HV_ALARM : #validate HV alarm hv_alarm = int(msg[C2D_SET_REQ_VAL]) if hv_alarm > 100000 and hv_alarm < 300000 : setConfigurationVariable(NVS_HV_ALARM,hv_alarm) voltageAlarmStateThresholds[ALARM_HIGH] = hv_alarm logger.debug("New HV Alarm threshold :" + str(hv_alarm)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_VHV_ALARM : #validate VHV alarm vhv_alarm = int(msg[C2D_SET_REQ_VAL]) if vhv_alarm > 100000 and vhv_alarm < 300000 : setConfigurationVariable(NVS_VHV_ALARM,vhv_alarm) voltageAlarmStateThresholds[ALARM_VERY_HIGH] = vhv_alarm logger.debug("New VHV Alarm threshold :" + str(vhv_alarm)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_LV_ALARM : #validate LV alarm lv_alarm = int(msg[C2D_SET_REQ_VAL]) if lv_alarm > 100000 and lv_alarm < 300000 : setConfigurationVariable(NVS_LV_ALARM,lv_alarm) voltageAlarmStateThresholds[ALARM_LOW] = lv_alarm logger.debug("New LV Alarm threshold:" + str(lv_alarm)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_VLV_ALARM : #validate VLV alarm vlv_alarm = int(msg[C2D_SET_REQ_VAL]) if vlv_alarm > 100000 and vlv_alarm < 300000 : setConfigurationVariable(NVS_VLV_ALARM,vlv_alarm) voltageAlarmStateThresholds[ALARM_VERY_LOW] = vlv_alarm logger.debug("New VLV Alarm threshold:" + str(vlv_alarm)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_CT_RATIO : #validate ct_ratio = int(msg[C2D_SET_REQ_VAL]) if ct_ratio >= 1 and ct_ratio <= 10000 : setConfigurationVariable(NVS_CT_RATIO,ct_ratio) logger.debug("New CT Ratio:" + str(ct_ratio)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_DEV_TYPE : #validate devType = int(msg[C2D_SET_REQ_VAL]) if devType >= M11 and devType <= C11_SPM33 : setConfigurationVariable(NVS_DEVICE_TYPE,devType) logger.debug("New Dev Type" + str(devType)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_ANTENNA : #validate antenna = int(msg[C2D_SET_REQ_VAL]) if antenna == 1 or antenna ==0 : setConfigurationVariable(NVS_ANTENNA_CONFIGURATION,antenna) logger.debug("New Antenna Setting: " + str(antenna)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_INST_FREQ : #validate inst_freq = int(msg[C2D_SET_REQ_VAL]) if inst_freq >= 2 : setConfigurationVariable(NVS_INST_DATA_FREQ,inst_freq) logger.debug("New Inst Frequency Setting: " + str(inst_freq)) if CD2_SET_PARAMETERS_LIST[msg[C2D_SET_REQ_ID]] == C2D_PARAM_LOAD : #validateS load_id = pack('i',int(msg[C2D_SET_REQ_VAL])) load_number= load_id[LOAD_NUMBER] load_address= load_id[LOAD_ADDRESS] load_value= load_id[LOAD_VALUE] if load_address > 0 : # zero is an invalid mb address writeLoad(load_address,deviceType,load_number, load_value) logger.debug("Load control command for address " + str(load_address) + " number " + str(load_number) + " Value: " + str(load_value)) if msg[C2D_REQUEST] == MESSAGE_TYPE_C2D_GET_REQUEST: logger.debug("Received Get request Msg Id:" + str(msg[C2D_GET_REQ_ID])) if CD2_GET_PARAMETERS_LIST[msg[C2D_GET_REQ_ID]] == C2D_PARAM_HHDATA: timestamp = msg[C2D_GET_REQ_PARAM] # see if we can found this HH message in our queue for x in range(0, MAX_HH_QUEUE_ITEM): msg = HHQueue.get() # get() does not erase the message in this queue if (msg != None and msg[TIMESTAMP] == timestamp): LoraQueueP3.put(msg) # re-send! logger.debug("Add HH msg to LQP3 " + str(binascii.hexlify((msg[MESSAGE])))) break if CD2_GET_PARAMETERS_LIST[msg[C2D_GET_REQ_ID]] == C2D_PARAM_INST_DATA: unixLocalTime= time.time() + time.timezone() typereq = msg[C2D_GET_REQ_PARAM] print(typereq) mesg = getLoRaInstData(deviceType,int(typereq)) currentLoraMessageToSend = buildInstantaneousMessage(unixLocalTime, mesg[MESSAGE_DATA], mesg[MESSAGE_LENGTH],typereq) LoraQueueImmediate.put(currentLoraMessageToSend) logger.debug("Add inst msg to Immediately " + str(binascii.hexlify((currentLoraMessageToSend[MESSAGE])))) if CD2_GET_PARAMETERS_LIST[msg[C2D_GET_REQ_ID]] == C2D_PARAM_PROCESSED_DATA: unixLocalTime= time.time() + time.timezone() rssi,snr = getRSSI_SNR() compute=[0,0,0] for phase in range (0 , numberOfPhase): compute[phase] = getComputedValues(phase) ProcessedLoraMessageToSend = buildComputedMessage(unixLocalTime, getLatestLIValue(),rssi,snr,compute,numberOfPhase) # create current LoRA Inst message LoraQueueImmediate.put(ProcessedLoraMessageToSend) logger.debug("Add Processed msg to Immediately " + str(binascii.hexlify((ProcessedLoraMessageToSend[MESSAGE])))) if CD2_GET_PARAMETERS_LIST[msg[C2D_GET_REQ_ID]] == C2D_PARAM_LOAD: unixLocalTime= time.time() + time.timezone() load_id = pack('i',int(msg[C2D_GET_REQ_PARAM])) load_number= load_id[LOAD_NUMBER] load_address= load_id[LOAD_ADDRESS] # assume SPM32 here as it is the only one we support for now payload=readRegisters(load_address,deviceType,40039,1) # register 40039 is the one used for this val = 0 if ( payload & 1 << load_number) == (1 << load_number) : val = 1 myintarray=bytearray(4) myintarray[LOAD_NUMBER]=load_number myintarray[LOAD_ADDRESS]=load_address myintarray[LOAD_VALUE]=val myintarray[LOAD_SPARE]=0 resVal= unpack('i',myintarray) currentLoraMessageToSend = buildGetResponseMessage(unixLocalTime,CD2_GET_PARAMETERS_LIST.index(C2D_PARAM_LOAD),resVal) LoraQueueImmediate.put(currentLoraMessageToSend) logger.debug("Add get msg to Immediately " + str(binascii.hexlify((currentLoraMessageToSend[MESSAGE])))) if msg[C2D_REQUEST] == MESSAGE_TYPE_C2D_GET_MODBUS_REQUEST: unixLocalTime= time.time() + time.timezone() logger.debug("Received Get Modbus request Address:" + str(msg[C2D_GET_MD_REQ_ADDRESS]) + " " + str(msg[C2D_GET_REQ_PARAM])) #get the data payload=readRegisters(msg[C2D_GET_MD_REQ_ADDRESS],deviceType,msg[C2D_GET_REQ_PARAM][0],msg[C2D_GET_REQ_PARAM][1]) #convert endianness for ii in range(0, len(payload)/2): temp = payload[ii*2] payload[ii*2] = payload[ii*2+1] payload[ii*2+1] = temp #build the response logger.debug("MB data " + str(len(payload)) + "bytes : " + (str(binascii.hexlify((payload))))) msg=buildGetModbusResponseMessage(unixLocalTime,deviceType,msg[C2D_GET_MD_REQ_ADDRESS],msg[C2D_GET_REQ_PARAM][0],msg[C2D_GET_REQ_PARAM][1],payload) #add to queue LoraQueueImmediate.put(msg) logger.debug("Add Processed msg to Immediately " + str(binascii.hexlify((msg[MESSAGE])))) return if msg[C2D_REQUEST] == MESSAGE_TYPE_C2D_SET_MODBUS_REQUEST: unixLocalTime= time.time() + time.timezone() logger.debug("Received Set Modbus request Address:" + str(msg[C2D_GET_MD_REQ_ADDRESS]) + " " + str(msg[C2D_GET_REQ_PARAM])) buff=bytearray(len(msg[C2D_GET_REQ_PARAM][2])) #convert endianness for ii in range(0, len(msg[C2D_GET_REQ_PARAM][2])/2): buff[ii*2] = msg[C2D_GET_REQ_PARAM][2][ii*2+1] buff[ii*2+1] = msg[C2D_GET_REQ_PARAM][2][ii*2] #set the data result=writeRegisters(msg[C2D_GET_MD_REQ_ADDRESS],deviceType,msg[C2D_GET_REQ_PARAM][0],msg[C2D_GET_REQ_PARAM][1],buff) logger.debug("Result: " + result) #TODO send a response return except Exception as e: logger.error("Processing incoming message: " + str(e)) pass
def _getMBRegistersSPM33(CTSecondary): #before we udpate, let validate this data... #if (_getReg(40001)== 0 or _getReg(40002) ==0 or _getReg(40003)==0) : # print("Zero voltage") # return False # zero is not a valid voltage! global data unixLocalTime = time.time() + time.timezone() ctRatio = int(_getRegUint16(40041) / CTSecondary) # the secondary is set to 5 on the SPM33 data['ctratio'] = ctRatio data['voltage'] = _getRegUint16(40001) / 100.0 # read voltage (phase Red) data['voltage2'] = _getRegUint16( 40002) / 100.0 # read voltage (phase White) data['voltage3'] = _getRegUint16( 40003) / 100.0 # read voltage (phase Blue) data['current'] = _getRegUint16( 40007) / 1000.0 * ctRatio # read current (phase Red) data['current2'] = _getRegUint16( 40008) / 1000.0 * ctRatio # read current (phase White) data['current3'] = _getRegUint16( 40009) / 1000.0 * ctRatio # read current (phase Blue) data['activepower'] = _getReg( 40016) / 10.0 * ctRatio # read active power (phase Red) data['activepower2'] = _getReg( 40017) / 10.0 * ctRatio # read active power (phase Blue) data['activepower3'] = _getReg( 40018) / 10.0 * ctRatio # read active power (phase White) data['reactivepower'] = _getReg( 40019) / 10.0 * ctRatio # read reactive power (phase Red) data['reactivepower2'] = _getReg( 40020) / 10.0 * ctRatio # read reactive power (phase Blue) data['reactivepower3'] = _getReg( 40021) / 10.0 * ctRatio # read reactive power (phase white) data['frequency'] = _getRegUint16(40025) / 100.0 # read frequency data['powerfactor'] = _getReg(40022) / 1000.0 # read power factor data['powerfactor2'] = _getReg(40023) / 1000.0 # read power factor data['powerfactor3'] = _getReg(40024) / 1000.0 # read power factor data['importActiveEnergy'] = _getDRegUint32( 40030) / 10 # read Input Active Energy (total all phases) data['exportActiveEnergy'] = _getDRegUint32( 40032) / 10 # read Export Active Energy (total all phases) data['importReactiveEnergy'] = _getDRegUint32( 40034) / 10 # read Input Reactive Energy (total all phases) data['exportReactiveEnergy'] = _getDRegUint32( 40036) / 10 # read Export Reactive Energy (total all phases) data['totalActiveEnergy'] = _getDRegUint32( 40026) / 10 # read Active Energy Accumulator in units of 0.1 kWh data['totalReactiveEnergy'] = _getDRegUint32( 40028) / 10 # read Total Reactive Energy (total all phases) data['thdv'] = _getRegUint16(40801 - 759) / 10.0 # read thd voltage (phase Red) data['thdv2'] = _getRegUint16(40802 - 759) / 10.0 # read thd voltage (phase White) data['thdv3'] = _getRegUint16(40803 - 759) / 10.00 # read thd voltage (phase Blue) data['thdi'] = _getRegUint16(40804 - 759) / 10.0 # read thd voltage (phase Red) data['thdi2'] = _getRegUint16(40805 - 759) / 10.0 # read thd voltage (phase White) data['thdi3'] = _getRegUint16(40806 - 759) / 10.0 # read thd voltage (phase Blue) data['hv_3'] = _getRegUint16( 40808 - 759) / 10.0 # read 3rd harmonic voltage (phase Red) data['hv_5'] = _getRegUint16( 40810 - 759) / 10.0 # read 5th harmonic voltage (phase Red) data['hv_7'] = _getRegUint16( 40812 - 759) / 10.0 # read 7th harmonic voltage (phase Red) data['hv_9'] = _getRegUint16( 40814 - 759) / 10.0 # read 9th harmonic voltage (phase Red) data['hv_11'] = _getRegUint16( 40816 - 759) / 10.0 # read 11th harmonic voltage (phase Red) data['hv_13'] = _getRegUint16( 40818 - 759) / 10.0 # read 13th harmonic voltage (phase Red) data['hv2_3'] = _getRegUint16( 40838 - 778) / 10.0 # read 3rd harmonic voltage (phase White) data['hv2_5'] = _getRegUint16( 40840 - 778) / 10.0 # read 5th harmonic voltage (phase White) data['hv2_7'] = _getRegUint16( 40842 - 778) / 10.0 # read 7th harmonic voltage (phase White) data['hv2_9'] = _getRegUint16( 40844 - 778) / 10.0 # read 9th harmonic voltage (phase White) data['hv2_11'] = _getRegUint16( 40846 - 778) / 10.0 # read 11th harmonic voltage (phase White) data['hv2_13'] = _getRegUint16( 40848 - 778) / 10.0 # read 13th harmonic voltage (phase White) data['hv3_3'] = _getRegUint16( 40868 - 797) / 10.0 # read 3rd harmonic voltage (phase Blue) data['hv3_5'] = _getRegUint16( 40870 - 797) / 10.0 # read 5th harmonic voltage (phase Blue) data['hv3_7'] = _getRegUint16( 40872 - 797) / 10.0 # read 7th harmonic voltage (phase Blue) data['hv3_9'] = _getRegUint16( 40874 - 797) / 10.0 # read 9th harmonic voltage (phase Blue) data['hv3_11'] = _getRegUint16( 40876 - 797) / 10.0 # read 11th harmonic voltage (phase Blue) data['hv3_13'] = _getRegUint16( 40878 - 797) / 10.0 # read 13th harmonic voltage (phase Blue) data['timestamp'] = unixLocalTime return True
def _getMBRegistersSPM93(): #before we udpate, let validate this data... if (_getReg(40101 - 100) == 0 or _getReg(40102 - 100) == 0 or _getReg(40103 - 100) == 0): return False # zero is not a valid voltage! global data CT = _getRegUint16(44002 - 3942) # the PT ratio is not supported (LV only) data['ctratio'] = CT unixLocalTime = time.time() + time.timezone() data['voltage'] = _getRegUint16(40101 - 100) / 100.0 # read voltage (phase Red) data['voltage2'] = _getRegUint16(40102 - 100) / 100.0 # read voltage (phase White) data['voltage3'] = _getRegUint16(40103 - 100) / 100.0 # read voltage (phase Blue) data['current'] = _getDRegUint32( 40107 - 100) / 1000.0 * CT # read current (phase Red) data['current2'] = _getDRegUint32( 40109 - 100) / 1000.0 * CT # read current (phase White) data['current3'] = _getDRegUint32( 40111 - 100) / 1000.0 * CT # read current (phase Blue) data['activepower'] = _getDReg( 40115 - 100) / 100.0 * CT # read active power (phase Red) data['activepower2'] = _getDReg( 40117 - 100) / 100.0 * CT # read active power (phase Blue) data['activepower3'] = _getDReg( 40119 - 100) / 100.0 * CT # read active power (phase White) data['reactivepower'] = _getDReg( 40123 - 100) / 100.0 * CT # read reactive power (phase Red) data['reactivepower2'] = _getDReg( 40125 - 100) / 100.0 * CT # read reactive power (phase Blue) data['reactivepower3'] = _getDReg( 40127 - 100) / 100.0 * CT # read reactive power (phase white) data['frequency'] = _getRegUint16(40143 - 100) / 100.0 # read frequency data['apparentpower'] = _getDReg( 40131 - 100) / 100.0 * CT # read apparent power (phase 1) data['apparentpower2'] = _getDReg( 40133 - 100) / 100.0 * CT # read apparent power (phase 1) data['apparentpower3'] = _getDReg( 40135 - 100) / 100.0 * CT # read apparent power (phase 1) data['powerfactor'] = _getRegUint16(40139 - 100) / 1000.0 # read power factor data['powerfactor2'] = _getRegUint16(40140 - 100) / 1000.0 # read power factor data['powerfactor3'] = _getRegUint16(40141 - 100) / 1000.0 # read power factor data['importActiveEnergy'] = _getDRegUint32( 41001 - 953) / 10 * CT # read Input Active Energy (total all phases) data['exportActiveEnergy'] = _getDRegUint32( 41003 - 953) / 10 * CT # read Export Active Energy (total all phases) data['totalActiveEnergy'] = _getDRegUint32( 41005 - 953) / 10 * CT # read Total Active Energy (total all phases) data['importReactiveEnergy'] = _getDRegUint32( 41007 - 953) / 10 * CT # read Input Reactive Energy (total all phases) data['exportReactiveEnergy'] = _getDRegUint32( 41009 - 953) / 10 * CT # read Export Reactive Energy (total all phases) data['totalReactiveEnergy'] = _getDRegUint32( 41011 - 953) / 10 * CT # read Total Reactive Energy (total all phases) data['timestamp'] = unixLocalTime return True
import time import socket import time from machine import RTC TZ = 0 print("sync rtc via ntp, TZ=", TZ) rtc = RTC() print("synced?", rtc.synced()) rtc.ntp_sync('nl.pool.ntp.org') print("synced?", rtc.synced()) #time.sleep_ms(750) time.timezone(TZ * 3600) i = 0 while True: if rtc.synced(): print("rtc is synced after", i / 1000, "s") # if rtc.now()[0] == 1970: # print() break if i % 100 == 0: print(".", end="") time.sleep_ms(1) print("rtc.now", rtc.now()) print("time.gmtime", time.gmtime()) print("time.localtime", time.localtime()) print("gmt ", end=" ") print("local", end=" ")
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> # Case1: import <module> >>> import random >>> dir(random) ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate'] >>> import time >>> dir(time) ['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname'] >>> time.time() 1632457508.035703 >>> time.timezone() Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> time.timezone() TypeError: 'int' object is not callable >>> time.timezone -19800 >>> ============================================== RESTART: Shell ============================================== >>> # Case2 : from <module_name> import <fun1>, <fun2> >>> from time import time, timezone >>> >>> time() 1632457626.424537 >>> timezone -19800 >>> ============================================== RESTART: Shell ============================================== >>> >>> from time import *