def setup_gps(): time.sleep(2) gc.enable() rtc = RTC() rtc.ntp_sync("pool.ntp.org") utime.sleep_ms(750) print('\nRTC Set from NTP to UTC:', rtc.now()) utime.timezone(7200) print('Adjusted from UTC to EST timezone', utime.localtime(), '\n') if rtc.now()[0] == 1970: print("Datetime could not be automatically set") date_str = (input( 'Enter datetime as list separated by commas (y, m, d, h, min, s): ' )).split(',') date_str = tuple([int(item) for item in date_str]) try: rtc.init(date_str) print('Time successfully set to ', rtc.now(), '\n') except Exception: print("Failed to set time...") py = Pytrack() l76 = L76GNSS(py, timeout=30) print("GPS Timeout is {} seconds".format(30)) chrono = Timer.Chrono() chrono.start() # while (True): # coord = l76.coordinates(debug=True) # print("{} - {} - {}".format(coord, rtc.now(), gc.mem_free())) return l76
def syncTime(): t = time() if t==0: return 0 t+=3600*8 tm = utime.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) print(tm) year=tm[0] print(year) month=tm[1] day=tm[2] hour=tm[4] second=tm[6] min=tm[5] print(month) print(day) print(hour) print(min) print(second) rtc = RTC() rtc.init((year,month,day,2,hour,min,second,0)) return 1 '''
def set_NTP_time(): import time from machine import RTC print("Setting time from NTP") t = get_NTP_time() if t is None: print("Could not set time from NTP") return False tm = time.localtime(t) tm = tm[0:6] offset = machine.nvs_getstr("badge", "time.offset") if not offset: offset = 1 if tm[1] > 3 and tm[1] < 11: offset = 2 tm = time.localtime(t + offset * 3600) tm = tm[0:6] rtc = RTC() rtc.init(tm) #rtc.datetime(tm) return True
def _read1(self, connection, ui): # Download hourly weather forecast for today url = 'http://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&APPID={}&mode=json&units={}&lang={}&exclude={}' fcast = connection.http_get_json( url.format(location[connection.config.location].lat, location[connection.config.location].lon, ui.apikey, ui.units, ui.language, 'minutely,hourly,daily')) # Parse todays forecast try: if not fcast['cod'] == 0: log('Server commu8nication error - can not load forecast!') try: log('Server reported:') log(' ', fcast['message']) log('') log('Go into configuration mode to set server correctly') except: pass play((400, 1000), (200, 1000), (400, 1000), (200, 1000), (400, 1000), (200, 1000)) deepsleep() except: pass current = fcast['current'] try: rain = current['rain']['1h'] except KeyError: rain = 0.0 try: snow = current['snow']['1h'] except KeyError: snow = 0.0 self.time_zone = fcast['timezone_offset'] weather = current['weather'][0] dsc = weather['description'] self.descr = dsc[0].upper() + dsc[1:] # Fix rain icon according to amount of rain def _mk_id(id, rain): return id if id != 500 or rain < 0.5 else 520 self.weather = Forecast.Weather( '{}{}'.format(id2icon[self._mk_id(weather['id'], rain)], weather['icon'][-1]), current['dt'], current['temp'], current['feels_like'], current['humidity'], rain, snow, current['wind_speed'], current['wind_deg']) self.time = Time(self.time_zone) # Set RTC clock according to forecast time rtc = RTC() dt = self.time.get_date_time(self.weather.dt) rtc.init((dt[0], dt[1], dt[2], 0, dt[3], dt[4], dt[5], 0))
def set_NTP_time(): import time from machine import RTC print("Setting time from NTP") t = get_NTP_time() if t is None: print("Could not set time from NTP") return False tz = 0 with database.Database() as db: tz = db.get("timezone", 200) # default to CEST tz_minutes = int(abs(tz) % 100) * (1 if tz >= 0 else -1) tz_hours = int(tz / 100) t += (tz_hours * 3600) + (tz_minutes * 60) tm = time.localtime(t) tm = tm[0:3] + (0, ) + tm[3:6] + (0, ) rtc = RTC() rtc.init() rtc.datetime(tm) return True
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 sync_time(): import urequests from machine import RTC rtc = RTC() print('before sync: ', rtc.datetime()) time = urequests.get('http://www.1zlab.com/api/get-time/').json() # print(time) rtc.init(tuple(time['rtc'])) print('after sync: ', rtc.datetime())
def sync_clock(self, epoc): try: rtc = RTC() rtc.init(utime.gmtime(epoc)) except Exception as ex: print("Exception setting system data/time: {}".format(ex)) return False return True
def set_clock_via_internet(): c = untplib.NTPClient() resp = c.request('0.de.pool.ntp.org', version=3, port=123) print("Offset is ", resp.offset) from machine import RTC import time rtc = RTC() print("Adjusting clock by ", resp.offset, "seconds") rtc.init(time.localtime(time.time() + resp.offset))
def set_time(self): """ set the system time to RTC time """ rtc = RTC() [year, month, day, dotw, hour, minute, second ] = self.driver.getDateTime() # get the date/time from the DS3231 if year > 2019: # check valid data rtc.init((year, month, day, dotw, hour, minute, second, 0)) # set date/time log.debug("Time set: {}".format(rtc.datetime())) else: log.warning("DS3231 date/time not set, not setting RTC")
def _bootService(self, level): if level == 0: c = untplib.NTPClient() resp = c.request('0.uk.pool.ntp.org', version=3, port=123) print("Offset is ", resp.offset) try: from machine import RTC import time rtc = RTC() print("Adjusting clock by ", resp.offset, "seconds") rtc.init(time.localtime(time.time() + resp.offset)) except: pass
def shutoff(self): """ shut off the MCU """ import DS3231tokei import utime from machine import Pin, RTC bus = self.sensor_manager.get_bus_by_sensortype('DS3231') ds = DS3231tokei.DS3231(bus.adapter) interval = self.settings.get( 'main.interval.shutoff', 10) * 60 # convert from minutes to seconds (year, month, day, dotw, hour, minute, second) = ds.getDateTime() # get the current time rtc = RTC() # create RTC if year < 2001: year = 2001 # sanity check, as of mpy 1.12 year must be >= 2001 rtc.init((year, month, day, dotw, hour, minute, second, 0)) # set time # check if its night or winter and adjust interval night_start = self.settings.get('main.interval.night_start', 0) night_end = self.settings.get('main.interval.night_end', 0) winter_start = self.settings.get('main.interval.winter_start', 0) winter_end = self.settings.get('main.interval.winter_end', 0) if night_start > 0 and (hour >= night_start or hour <= night_end ): # double interval for the night interval *= 2 if winter_start > 0 and (month >= winter_start or month <= winter_end ): # double interval for winter interval *= 2 # Compute sleeping duration from measurement interval and elapsed time. elapsed = int(self.duty_chrono.read()) now_secs = utime.mktime(utime.localtime()) wake_at = now_secs - elapsed + interval if (wake_at - now_secs) < 180: # don't shutoff for less than 3 minutes wake_at += interval (year, month, day, hour, minute, second, dotw, doty) = utime.localtime(wake_at) # convert the wake up time # set alarm ds.setAlarm2(day, hour, minute, DS3231tokei.A2_ON_HOUR_MINUTE) # turn off MCU via MOSFET utime.sleep(1) ds.enableAlarm2() ds.resetAlarm2()
def timesync(): timezone = valuestore.load("system", "timezone") if not timezone: timezone = "Europe/Amsterdam" res = urequests.get("http://worldtimeapi.org/api/timezone/" + timezone) if res.status_code == 200: data = res.json() print(data) tm = data["unixtime"] - 946684800 + data["raw_offset"] + data[ "dst_offset"] rtc = RTC() rtc.init(tm)
def UpdateRTC(self): for i in range(self.max_wait): if self.date: break self.read() day = int(self.date) if not day: return False hours = int(float(self.timestamp)) millis = int(float(self.timestamp)*1000)%1000 try: rtc = RTC() rtc.init((2000+(day%100),(day//100)%100,day//10000,hours//10000,(hours//100)%100,hours%100,millis%1000)) except: return False return True
def set_NTP_time(): import time from machine import RTC print("Setting time from NTP") t = get_NTP_time() if t is None: print("Could not set time from NTP") return False tm = time.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) rtc = RTC() rtc.init(tm) return True
class DS3231: def __init__(self): self.ds3231 = I2C(0, I2C.MASTER, baudrate=100000, pins=('GP15', 'GP10')) self.rtc = RTC() def loadTime(self): if DS3231_I2C_ADDR in self.ds3231.scan(): data = self.ds3231.readfrom_mem(DS3231_I2C_ADDR, 0, 7) ss = bcd2dec(data[0] & 0b01111111) mm = bcd2dec(data[1] & 0b01111111) if data[2] & 0b01000000 > 0: hh = bcd2dec(data[2] & 0b00011111) if data[2] & 0b00100000 > 0: hh += 12 else: hh = bcd2dec(data[2] & 0b00111111) DD = bcd2dec(data[4] & 0b00111111) MM = bcd2dec(data[5] & 0b00011111) YY = bcd2dec(data[6]) if data[5] & 0b10000000 > 0: YY = YY + 2000 else: YY = YY + 1900 self.rtc.init((YY, MM, DD, hh, mm, ss)) else: print("DS3231 not found on I2C bus at %d" % DS3231_I2C_ADDR) def saveTime(self): (YY, MM, DD, hh, mm, ss, micro, tz) = self.rtc.now() self.ds3231.writeto_mem(DS3231_I2C_ADDR, 0, dec2bcd(ss)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 1, dec2bcd(mm)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 2, dec2bcd(hh)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 4, dec2bcd(DD)) if YY >= 2000: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, dec2bcd(MM) | 0b10000000) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, dec2bcd(YY - 2000)) else: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, dec2bcd(MM)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, dec2bcd(YY - 1900))
class DS3231: def __init__(self): self.ds3231 = I2C(0, I2C.MASTER, baudrate=100000, pins=('GP15', 'GP10')) self.rtc = RTC() def loadTime(self): if DS3231_I2C_ADDR in self.ds3231.scan(): data = self.ds3231.readfrom_mem(DS3231_I2C_ADDR, 0, 7) ss=bcd2dec(data[0] & 0b01111111) mm=bcd2dec(data[1] & 0b01111111) if data[2] & 0b01000000 > 0: hh=bcd2dec(data[2] & 0b00011111) if data[2] & 0b00100000 >0: hh+=12 else: hh=bcd2dec(data[2] & 0b00111111) DD=bcd2dec(data[4] & 0b00111111) MM=bcd2dec(data[5] & 0b00011111) YY=bcd2dec(data[6]) if data[5] & 0b10000000 > 0: YY=YY+2000 else: YY=YY+1900 self.rtc.init((YY,MM,DD,hh,mm,ss)) else: print("DS3231 not found on I2C bus at %d" % DS3231_I2C_ADDR) def saveTime(self): (YY,MM,DD,hh,mm,ss,micro,tz) = self.rtc.now() self.ds3231.writeto_mem(DS3231_I2C_ADDR, 0,dec2bcd(ss)); self.ds3231.writeto_mem(DS3231_I2C_ADDR, 1,dec2bcd(mm)); self.ds3231.writeto_mem(DS3231_I2C_ADDR, 2,dec2bcd(hh)); self.ds3231.writeto_mem(DS3231_I2C_ADDR, 4,dec2bcd(DD)); if YY >= 2000: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5,dec2bcd(MM) | 0b10000000); self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6,dec2bcd(YY-2000)); else: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5,dec2bcd(MM)); self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6,dec2bcd(YY-1900));
def getNTPTime(): # note that this sets GMT, and does not adapt for local timezone host = "66.199.22.67" #"pool.ntp.org" rtc = RTC() # connect to time server s=socket.socket() s.connect(socket.getaddrinfo(host,13)[0][-1]) msgraw=s.recv(1024) msg = msgraw.decode() s.close() print(msg) year = 2000 + int(msg[6:9]) month = int(msg[10:12]) day = int(msg[13:15]) hour = int(msg[16:18]) min = int(msg[19:21]) sec = int(msg[22:24]) rtc = RTC() rtc.init((year, month, day, hour, min, sec, 0, 0)) return(rtc)
def get_time(): try: py = Pytrack() l76 = L76GNSS(py, timeout=120) timeout = time() + 30 #timeout in 30 seconds from now while timeout > time(): # try until timeout date_time=l76.getUTCDateTime() # get time from L76 # 2080 is default year returned by L76 when no GPS signal detected if date_time[:4] != '2080': # prevents default value from L76 for date_time break sleep(2) # wait before checking L76 time again else: date_time = '2000-01-01T00:00:00+00:00' # set to a vale if timeout occurs print('GPS time not found. Setting clock to 01/01/2000') print(date_time) rtc = RTC() # create real time clock # init RTC with GPS UTC date & time rtc.init((int(date_time[0:4]),int(date_time[5:7]),int(date_time[8:10]),int(date_time[11:13]),int(date_time[14:16]))) except: print('Unable to set time.')
) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v) ADC_3.width( ADC.WIDTH_12BIT) # set 12 bit return values (returned range 0-4095) ADC_4 = ADC(Pin(ANALOG_4)) # create ADC object on ADC pin ADC_4.atten(ADC.ATTN_11DB ) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v) ADC_4.width( ADC.WIDTH_12BIT) # set 12 bit return values (returned range 0-4095) ID = 0 buffer = [] linha = 0 rtc = RTC() rtc.init((0, 0, 0, 0, 0, 0, 0, 0)) microseconds = 500 while True: start = utime.ticks_us() # read value using the newly configured attenuation and width #inertial = accel.gett_values() #dado do tipo dicionario # round() 茅 para delimitar a quantidade de casas decimais In_0 = round(((ADC_0.read()) * 3.3 / 4095), 2) In_1 = round(((ADC_0.read()) * 3.3 / 4095), 2) In_2 = round(((ADC_2.read()) * 3.3 / 4095), 2) #In_3 = round(((ADC_3.read())* 3.3 / 4095),2) #In_4 = round(((ADC_4.read())* 3.3 / 4095),2) #In_5 = 1.0 #In_6 = 1.0 ## In_7 = 1.0
from DRV8833_V2 import * import ENCODEUR from BME280 import * from CORRECTEUR_PID import * from ODOMETRIE import * from BME280 import * from machine import I2C from machine import SD from machine import RTC import os import time #Ini RTC (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) Time_Rtc = RTC() Time_Rtc.init((2019, 11, 16, 15, 14, 0, 0, 0)) #ini carte sd sd = SD() os.mount(sd, "/sd") #ini BME280 bus_i2c = I2C() bus_i2c.init(I2C.MASTER, baudrate = 400000) print(bus_i2c.scan()) Id_BME280 = bus_i2c.readfrom_mem(BME280_I2C_ADR, BME280_CHIP_ID_ADDR, 1) capteur_BME = BME280(BME280_I2C_ADR, bus_i2c) capteur_BME.Calibration_Param_Load()
from machine import RTC rtc = RTC() # for 22nd of June 2017 at 10:30am (TZ 0) rtc.init((2017, 6, 22, 10, 30, 0, 0, 0)) print(rtc.now())
""" Example programme that runs on a Pycom board and prints plantower readings. Daniel Hausner 20/06/2019 Place this file in your main project folder, so that the project structure is as follows: Your-project-folder |-lib |-plantowerpycom |-__init__.py |-logging.py |-plantower.py |-main.py """ from plantowerpycom import Plantower, PlantowerException from machine import RTC plantower = Plantower() # Initialise the time rtc = RTC() rtc.init((2017, 2, 28, 10, 30, 0, 0, 0)) # Pass time tuple (e.g. from GPS) to initialise the time while True: try: recv = plantower.read() print(recv) except PlantowerException as pe: print(pe)
def setRTCClock(self,debug=False): r = RTC() rr = self.getUTCDateTimeTuple(debug=debug) if rr: r.init(rr)
pycom.rgbled(OFF) time.sleep(9) rx, port = s.recvfrom(256) if rx: print('Received: {}, on port: {} ({})'.format( rx, port, lora.stats())) pycom.rgbled(BLUE) time.sleep(1) pycom.rgbled(OFF) # TODO special case for port=224 (set confirmation, ask for LinkCheck, force rejoin) # TODO port=123 (NTP) for setting RTC rtc.init((2017, 2, 28, 10, 30, 0, 0, 0)) # TODO port=?? for setting TX period, Acc threshhold, ... # if port=123, set RTC if port == 123: rtc.init( (rx[0] + 2000, rx[1], rx[2], rx[3], rx[4], rx[5], 0, 0)) print('Set RTC at ', rtc.now()) # if port=200, force to rejoin if port == 200: print('Rejoin in few seconds ...') pycom.rgbled(ORANGE) Cont = False # if port=201, selecting confirmed type of messages if port == 201: # selecting confirmed type of messages print('Select Confirmed') pycom.rgbled(CYAN) s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True)
def main(): try: global duty, nexttime, timestamp, currenttime, energytotal, chargestarttime,\ dayenergy, state dayenergy = 0.0 energytotal = 0.0 duty = 1023 CPvalue = 0 CPerror = False state = 0 # charge state 1=Not connected, 2=EV connected, 3=EV charge, 4= Error lasttime = 0 endday = False relayoff() ControlPilot.duty(CPidle) _, _, timestamp, _ = deltapwr() print(timestamp) rtc = RTC() rtc.init((int(timestamp[0:4]),int(timestamp[4:6]),int(timestamp[6:8]),0, \ int(timestamp[8:10]),int(timestamp[10:12]),int(timestamp[12:14]),0)) sleep_ms(100) try: remove('log.log') except: pass while True: calcduty() currenttime = time() currt = localtime(currenttime) if currt[3] == 23 and currt[4] == 59 and endday == False: endday = True if dayenergy == 0: chargestarttime = currenttime stopcharge() else: endday = False message='CP value={} CP duty={} ChargeI={:.1f} Power={:.1f} Delta={} State={} Temp={} Energy={:.3f} DayEnergy={:.1f}' \ .format(CPvalue,ControlPilot.duty(),ChargeI,ChargeI*VMains/1000.0,int(delta),state, int(readTemp()),energytotal,dayenergy) print(message) log('log', message) for i in range(nexttime * 2): CPvalue = readCP() message='Timestamp {}\nCP value={} CP duty={} ChargeI={:.1f} Power={:.1f} Delta={} State={} Temp={} Energy={:.3f} DayEnergy={:.1f}' \ .format(localtimestamp(),CPvalue,ControlPilot.duty(),ChargeI,ChargeI*VMains/1000.0,int(delta),state,int(readTemp()),energytotal,dayenergy) sendhtml(message) print(CPvalue, end='\r') if checkCPstate(EVnoconnect, CPvalue): relayoff() ControlPilot.duty(1023) CPerror = False dotstar[0] = (100, 100, 150) if state != 1: log('events', 'EV not connected') if state == 3: print('at no connect') stopcharge() state = 1 elif checkCPstate(EVready, CPvalue): relayoff() ControlPilot.duty(duty) CPerror = False dotstar[0] = (0, 0, 150) if state != 2: log('events', 'EV ready') if state == 3: stopcharge() state = 2 elif checkCPstate(EVcharging, CPvalue): relayon() ControlPilot.duty(duty) CPerror = False dotstar[0] = (0, 150, 0) if state != 3: log('events', 'EV charging') lastt = localtime(lasttime) if lastt[0] != currt[0] or lastt[1] != currt[ 1] or lastt[2] != currt[2]: dayenergy = 0.0 state = 3 lasttime = currenttime chargestarttime = lasttime if duty != 1023: charge = 30 * duty / 511 energydelta = charge * VMains * (currenttime - lasttime) / 3600000 energytotal += energydelta dayenergy += energydelta lasttime = currenttime else: #error if CPerror == False: CPerror = True else: relayoff() ControlPilot.duty(1023) dotstar[0] = (150, 0, 0) if state != 4: log('events', "CP error") if state == 3: print('at error') stopcharge() state = 4 sleep_ms(500) except Exception as e: logexception(e) raise
import untplib c=untplib.NTPClient() resp=c.request('0.uk.pool.ntp.org', version=3, port=123) print("Offset is ", resp.offset) from machine import RTC import time rtc = RTC() print("Adjusting clock by ", resp.offset, "seconds") rtc.init(time.localtime(time.time() + resp.offset))
def set_time(): time=get_time() rtc=RTC() rtc.init((time[0], time[1], time[2], 4, time[3], time[4], time[5], 0)) return rtc
def get_ntp_time(): NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1b s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) msg = None try: addr = socket.getaddrinfo("0.0.0.0", 0)[0][-1] s.bind(addr) addr = socket.getaddrinfo(host, port)[0][-1] res = s.sendto(NTP_QUERY, addr) msg = s.recv(48) except: pass s.close() if msg: val = struct.unpack("!I", msg[40:44])[0] return val - NTP_DELTA else: return 0 rtc = RTC() rtc.init(localtime(get_ntp_time())) print(localtime())
import machine from machine import RTC import time rtc = RTC() rtc.init() print(rtc) # make sure that 1 second passes correctly rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) time.sleep_ms(1002) print(rtc.datetime()[:7])
import socket import time import config as c import machine from machine import WDT from machine import RTC from machine import Pin ############################################################################################################################# configuration=c.configuration # configuration 1 : RX ET TX, ON VA CONFIGURER LE RX; il y a x capteur sur le RX; il y a y capteurs sur le TX # configuration 2 : RX ET TX, ON VA CONFIGURER LE TX; il y a x capteurs sur le RX; il y a y capteurs sur le TX debug=c.debug wake=c.wake # pas de deepsleep wake =0, période d'émission selon delai_local, deepsleep -> wake =1, période d'émission selon sleep rtc = RTC() rtc.init(c.date) ############################################################################################################################# def alimCapteurs(etat) :# ferme le relais via les sorties 1 et 2 relais_alim_1_hx711=Pin(c.sortie_relais_1, mode=Pin.OUT) relais_alim_2_hx711=Pin(c.sortie_relais_2, mode=Pin.OUT) if etat: relais_alim_1_hx711.value(1)#mise en tension relais relais_alim_2_hx711.value(1) else: relais_alim_1_hx711.value(0)#mise hors tension relais relais_alim_2_hx711.value(0) return def acquisitionCapteur( capteur) : capteur.power_up()#reveille le HX711 n°'capteur' time.sleep (delai_avant_acquisition)
mch = os.uname().machine if not 'LaunchPad' in mch and not 'WiPy' in mch: raise Exception('Board not supported!') rtc = RTC() print(rtc) print(rtc.now()[:6]) rtc = RTC(datetime=(2015, 8, 29, 9, 0, 0, 0, None)) print(rtc.now()[:6]) rtc.deinit() print(rtc.now()[:6]) rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) print(rtc.now()[:6]) seconds = rtc.now()[5] time.sleep_ms(1000) print(rtc.now()[5] - seconds == 1) seconds = rtc.now()[5] time.sleep_ms(2000) print(rtc.now()[5] - seconds == 2) # initialization with shorter tuples rtc.init((2015, 9, 19, 8, 0, 0, 0)) print(rtc.now()[5]) rtc.init((2015, 9, 19, 8, 0, 0)) print(rtc.now()[5]) rtc.init((2015, 9, 19, 8, 0)) print(rtc.now()[5])
gnss_quality = gnss_data[5] if gnss_quality > 0: print(" done") print("") gnss_year = gnss_data[0][0] gnss_month = gnss_data[0][1] gnss_mday = gnss_data[0][2] gnss_hour = gnss_data[0][3] gnss_minutes = gnss_data[0][4] gnss_seconds = gnss_data[0][5] if RTC_present: rtc.init((gnss_year, gnss_month, gnss_mday, gnss_hour, gnss_minutes, gnss_seconds)) if BME_present: p_sensor = FR_PRESSURE prev_p = 0 else: p_sensor = 'NA' if DebugMode: Serial_writer.write_headers({ 'manufacturer_code': MF_CODE, 'logger_id': uid, 'date': datetime.date(gnss_year, gnss_month, gnss_mday),
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