async def get_cfg(self): flag = False def filewriter(): nonlocal flag try: with open(dfl.CONFIG_DIR + self.instrument_config, 'wb') as conf: conf.write(self.data) flag = True except Exception as err: log(self.__qualname__, 'get_cfg', type(err).__name__, err, type='e') self.evt.set() if await self.brk(): await self.swriter.awrite('GA') if await self.reply(): if (self.ack() and await self.verify_checksum(self.data[0:48]) and await self.verify_checksum(self.data[48:272]) and await self.verify_checksum(self.data[272:784])): _thread.start_new_thread(filewriter, ()) await asyncio.sleep_ms(10) await self.evt.wait() self.evt.clear() if flag: return True log(self.__qualname__, 'unable to retreive the instrument configuration', type='e') return False
def _timeout(self, start, expire=0): if not expire: expire = cfg.TIMEOUT if expire > 0 and time.time() - start >= expire: log(self.__qualname__, 'timeout occurred', type='e') return True return False
def ws_vect_avg(self): avg = 0 def samples(): i = 0 while i < len(self.data): yield [ int(self.data[0 + i:4 + i]) * float(self.config['Meteo'][ 'Windspeed_' + self.config['Meteo']['Windspeed_Unit']]), int(self.data[5 + i:9 + i]) / 10 ] i += self.data_length try: x = 0 y = 0 for sample in samples(): direction = sample[1] speed = sample[0] x = x + sin(radians(direction)) * speed y = y + cos(radians(direction)) * speed x = x / self.records y = y / self.records avg = sqrt(pow(x, 2) + pow(y, 2)) except Exception as err: log(self.__qualname__, 'ws_vect_avg ({}): {}'.format(type(err).__name__, err)) return avg
async def set_sample_rate(self): CMD = 'S' if await self.set(CMD + ' {:0d} S'.format(self.sample_rate)): if await self.dis(CMD): log(self.__qualname__, self.data) else: log(self.__qualname__, 'unable to set the sample rate', type='e')
async def verify_checksum(self, data): checksum = int.from_bytes(data[-2:], 'little') calc_checksum = await self.calc_checksum(data) if checksum == calc_checksum: return True log(self.__qualname__, 'invalid checksum calculated: {} got: {}'.format(calc_checksum, checksum)) return False
def create_checkout_session(request, mode, stripePriceId): ctx = 'STRIPE API - create_checkout_session' if request.method == 'GET': domain_url = 'http://127.0.0.1:8000' stripe.api_key = settings.STRIPE_TEST_SECRET_KEY try: # Create new Checkout Session for the order # Other optional params include: # [billing_address_collection] - to display billing address details on the page # [customer] - if you have an existing Stripe Customer ID # [payment_intent_data] - lets capture the payment later # [customer_email] - lets you prefill the email input in the form # For full details see https:#stripe.com/docs/api/checkout/sessions/create # ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param checkout_session = stripe.checkout.Session.create( success_url=domain_url + reverse('users:subscriptions') + '/activated?stripe_session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + reverse('users:subscriptions'), payment_method_types=['card'], mode=mode, #payment o subscription o setup customer=request.user.stripe_cust_id, line_items=[{ 'price': stripePriceId, 'quantity': 1 }]) request.user.plan_current_checkout = None request.user.one_time_current_checkout = None if mode == 'subscription': try: plan = Plan.objects.get(price_id=stripePriceId) request.user.plan_current_checkout = plan except ObjectDoesNotExist as e: log("Plan not found with price_id = " + str(stripePriceId), request.user, ctx, 2) return JsonResponse({ 'error': "Plan not found with price_id = " + str(stripePriceId) }) else: try: prod = OneTimeProduct.objects.get(price_id=stripePriceId) request.user.one_time_current_checkout = prod except ObjectDoesNotExist as e: log( "One Time Product not found with price_id = " + str(stripePriceId), request.user, ctx, 2) return JsonResponse({ 'error': "One Time Product not found with price_id = " + str(stripePriceId) }) request.user.stripe_checkout_session_id = checkout_session['id'] request.user.save() return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)})
async def main(self): try: await asyncio.wait_for(u4_lock.acquire(), self.config['Uart_Timeout']) # Locks down uart4 and rs232 transceiver. except asyncio.TimeoutError: log(self.__qualname__, 'unable to acquire lock on uart', type='e') return False self.on() # in use. self.init_uart() await asyncio.sleep(1) if self.config['Ctd']['Wait_for_Enter'] == 1: await self.swriter.awrite(ENTER) await asyncio.sleep(self.warmup_interval) pyb.LED(3).on() try: self.data = await asyncio.wait_for(self.sreader.readline(), 5) except asyncio.TimeoutError: self.data = b'' log(self.__qualname__, 'no data received', type='e') if self.data: if self.decoded(): await self.log() pyb.LED(3).off() self.uart.deinit() self.off() u4_lock.release() # Releases gps.
def parse_hw_cfg(bs): def decode_hw_cfg(conf): try: return ( 'RECORDER {}'.format('NO' if conf >> 0 & 1 else 'YES'), 'COMPASS {}'.format('NO' if conf >> 1 & 1 else 'YES') ) except Exception as err: log(self.__qualname__, 'decode_hw_cfg', type(err).__name__, err) def decode_hw_status(status): try: return 'VELOCITY RANGE {}'.format('HIGH' if status >> 0 & 1 else 'NORMAL') except Exception as err: log(self.__qualname__, 'decode_hw_status', type(err).__name__, err) try: return ( '{:02x}'.format(bs[0]), # [0] Sync '{:02x}'.format(int.from_bytes(bs[1:2], 'little')), # [1] Id int.from_bytes(bs[2:4], 'little'), # [2] Size bs[4:18].decode('ascii'), # [3] SerialNo decode_hw_cfg(int.from_bytes(bs[18:20], 'little')), # [4] Config int.from_bytes(bs[20:22], 'little'), # [5] Frequency bs[22:24], # [6] PICVersion int.from_bytes(bs[24:26], 'little'), # [7] HWRevision int.from_bytes(bs[26:28], 'little'), # [8] RecSize decode_hw_status(int.from_bytes(bs[28:30], 'little')), # [9] Status bs[30:42], # [10] Spare bs[42:46].decode('ascii') # [11] FWVersion ) except Exception as err: log(self.__qualname__, 'parse_cfg__', type(err).__name__, err)
async def startup(self, **kwargs): try: await asyncio.wait_for(u4_lock.acquire(), self.config['Uart_Timeout']) # Locks down uart4 and rs232 transceiver. except asyncio.TimeoutError: log(self.__qualname__, 'unable to acquire lock on uart', type='e') return False self.on() self.init_uart() await asyncio.sleep(1) # Waits for uart getting ready. if await self.brk(): await self.set('STARTUP NOHEADER') await self.set('STARTUP MONITOR') await self.set_sample_rate() await self.set('SCAN TIME') await self.set('SCAN DATE') await self.set('SCAN DENSITY') await self.set('SCAN SALINITY') await self.set('SCAN SV') await self.zero() await self.set_clock() await self.set_log() await self.set('SCAN LOGGING') log(self.__qualname__, 'successfully initialised') self.uart.deinit() self.off() u4_lock.release()
def fit(self, X, y, X_test=None, y_test=None): X, y = np.array(X), np.array(y) self.params(X) X = self.whiten(X) n = X.shape[1] d = y.shape[1] # if not self.constructed: self.construct(n, d) self.constructed = True if X_test is None or y_test is None: X, X_test, y, y_test = train_test_split(X, y, test_size=.05) history = self.model.fit(X, y, batch_size=self.bsize, epochs=self.epochs, verbose=0, validation_data=(X_test, y_test)) log("Val_loss: " + str(history.history['val_loss'][-1])) log("loss: " + str(history.history['loss'][-1])) else: X_test, y_test = np.array(X_test), np.array(y_test) history = self.model.fit(X, y, batch_size=self.bsize, epochs=self.epochs, verbose=0, validation_data=(X_test, y_test)) return history.history
async def set_clock(self): async def get_clock(): if await self.brk(): await self.swriter.awrite('RC') if await self.reply(): if self.ack(): try: self.data = binascii.hexlify(self.data) return '20{:2s}-{:2s}-{:2s}T{:2s}:{:2s}:{:2s}Z'.format( self.data[8:10], # Year self.data[10:12],# Month self.data[4:6], # Day self.data[6:8], # Hour self.data[0:2], # Minute self.data[2:4]) # Seconds except Exception as err: log(self.__qualname__, 'get_clock', type(err).__name__, err, type='e') return False if await self.brk(): now = time.localtime() await self.swriter.awrite('SC') await self.swriter.awrite( binascii.unhexlify('{:02d}{:02d}{:02d}{:02d}{:02d}{:02d}'.format(now[4], now[5]+1, now[2], now[3], int(str(now[0])[2:]), now[1]))) if await self.reply(): if self.ack(): log(self.__qualname__, 'instrument clock synchronized {}'.format(await get_clock())) return True log(self.__qualname__, 'unable to synchronize the instrument clock', type='e') return False
def set_deployment_start(sampling_interval, avg_interval): # Computes the measurement starting time to be in synch with the scheduler. now = time.time() next_sampling = now - now % sampling_interval + sampling_interval log(self.__qualname__, 'deployment start at {}, measurement interval {}\', average interval {}\''.format(iso8601(next_sampling), sampling_interval, avg_interval)) deployment_start = time.localtime(next_sampling + avg_interval) return binascii.unhexlify('{:02d}{:02d}{:02d}{:02d}{:02d}{:02d}'.format(deployment_start[4], deployment_start[5], deployment_start[2], deployment_start[3], int(str(deployment_start[0])[2:]), deployment_start[1]))
def parse_head_cfg(bs): def decode_head_cfg(conf): try: return ( 'PRESSURE SENSOR {}'.format('YES' if conf >> 0 & 1 else 'NO'), 'MAGNETOMETER SENSOR {}'.format('YES' if conf >> 1 & 1 else 'NO'), 'TILT SENSOR {}'.format('YES' if conf >> 2 & 1 else 'NO'), '{}'.format('DOWN' if conf >> 3 & 1 else 'UP') ) except Exception as err: log(self.__qualname__, 'decode_head_cfg', type(err).__name__, err) try: return ( '{:02x}'.format(bs[0]), # [0] Sync '{:02x}'.format(int.from_bytes(bs[1:2], 'little')), # [1] Id int.from_bytes(bs[2:4], 'little') * 2, # [2] Size decode_head_cfg(int.from_bytes(bs[4:6], 'little')), # [3] Config int.from_bytes(bs[6:8], 'little'), # [4] Frequency bs[8:10], # [5] Type bs[10:22].decode('ascii'), # [6] SerialNo bs[22:198], # [7] System bs[198:220], # [8] Spare int.from_bytes(bs[220:222], 'little') # [9] NBeams ) except Exception as err: log(self.__qualname__, 'parse_head_cfg', type(err).__name__, err)
def decoded(self): try: self.data = self.data.decode('utf-8') return True except UnicodeError: log(self.__qualname__, 'communication error') return False
def wd_vect_avg(self): avg = 0 def samples(): i = 0 while i < len(self.data): yield [ int(self.data[0 + i:4 + i]) * float(self.config['Meteo'][ 'Windspeed_' + self.config['Meteo']['Windspeed_Unit']]), int(self.data[5 + i:9 + i]) / 10 ] i += self.data_length try: x = 0 y = 0 for sample in samples(): direction = sample[1] speed = sample[0] x = x + (sin(radians(direction)) * speed) y = y + (cos(radians(direction)) * speed) x = x / self.records y = y / self.records avg = degrees(atan2(x, y)) if avg < 0: avg += 360 except Exception as err: log(self.__qualname__, 'wd_vect_avg ({}): {}'.format(type(err).__name__, err), type='e') return avg
async def set_log(self): CMD = 'LOG' now = time.localtime() if await self.set(CMD + ' {:04d}{:02d}{:02d}.txt'.format(now[0], now[1], now[2])): if await self.dis(CMD): log(self.__qualname__, self.data) else: log(self.__qualname__, 'unable to create log', type='e')
def filereader(): nonlocal bs try: with open(dfl.CONFIG_DIR + self.deployment_config, 'rb') as pcf: bs = pcf.read() except Exception as err: log(self.__qualname__, 'set_usr_cfg', type(err).__name__, err) self.evt.set()
def decode_hw_cfg(conf): try: return ( 'RECORDER {}'.format('NO' if conf >> 0 & 1 else 'YES'), 'COMPASS {}'.format('NO' if conf >> 1 & 1 else 'YES') ) except Exception as err: log(self.__qualname__, 'decode_hw_cfg', type(err).__name__, err)
async def format_recorder(): if await self.brk(): await self.swriter.awrite(b'\x46\x4F\x12\xD4\x1E\xEF') if await self.reply(): if self.ack(): log(self.__qualname__, 'recorder formatted') return True log(self.__qualname__, 'unable to format the recorder', type='e') return False
async def reply(self): try: self.data = await asyncio.wait_for(self.sreader.readline(), self.timeout) except asyncio.TimeoutError: log(self.__qualname__, 'no answer') return False if self.decoded(): return True return False
async def reply(self, timeout=10): self.data = b'' try: self.data = await asyncio.wait_for(self.sreader.read(1024), timeout) verbose(self.data) except asyncio.TimeoutError: log(self.__qualname__, 'no answer') return False return True
async def log(self): #with open(dfl.DATA_DIR + cfg.RAW_DIR + '/' + dailyfile() + '.prf', 'ab') as raw: # raw.write(self.data) try: cnv = await self.conv_data() fmt = await self.format_data(cnv) await log_data(dfl.DATA_SEPARATOR.join(fmt)) except Exception as err: log(self.__qualname__, 'log', type(err).__name__, err)
def filewriter(): nonlocal flag try: with open(dfl.CONFIG_DIR + self.instrument_config, 'wb') as conf: conf.write(self.data) flag = True except Exception as err: log(self.__qualname__, 'get_cfg', type(err).__name__, err, type='e') self.evt.set()
async def is_ready(self): try: line = await asyncio.wait_for(self.sreader.readline(), 30) except asyncio.TimeoutError: log(self.__qualname__, 'no answer') return False if self.decode(line): return True return False
def set_uart(self): if 'Uart' in self.config: self.uart_bus = dfl.UARTS[dfl.DEVS.index( self.name)] if self.name in dfl.DEVS else dfl.UARTS[ cfg.DEVS.index(self.name)] try: self.uart = pyb.UART(self.uart_bus, int(self.config['Uart']['Baudrate'])) except Exception as err: log(self.__qualname__, type(err).__name__, err, type='e')
def decode_head_cfg(conf): try: return ( 'PRESSURE SENSOR {}'.format('YES' if conf >> 0 & 1 else 'NO'), 'MAGNETOMETER SENSOR {}'.format('YES' if conf >> 1 & 1 else 'NO'), 'TILT SENSOR {}'.format('YES' if conf >> 2 & 1 else 'NO'), '{}'.format('DOWN' if conf >> 3 & 1 else 'UP') ) except Exception as err: log(self.__qualname__, 'decode_head_cfg', type(err).__name__, err)
def ad22103(self, vout, vsupply): try: return (vout * 3.3 / vsupply - 0.25) / 0.028 except Exception as err: log(self.__qualname__, 'ad22103', type(err).__name__, err, type='e') return 0
def filereader(): try: with open(dfl.CONFIG_DIR + self.instrument_config, 'rb') as raw: bs = raw.read() self.hw_cfg = parse_hw_cfg(bs[0:48]) # Hardware config (48 bytes) self.head_cfg = parse_head_cfg(bs[48:272]) # Head config (224 bytes) self.usr_cfg = parse_usr_cfg(bs[272:784]) # Deployment config (512 bytes) except Exception as err: log(self.__qualname__, 'parse_cfg', type(err).__name__, err) self.evt.set()
def init_gpio(self): try: self.gpio = pyb.Pin( dfl.CTRL_PINS[dfl.DEVS.index(self.name) if self.name in dfl.DEVS else cfg.DEVS.index(self.name)], pyb.Pin.OUT, pyb.Pin.PULL_DOWN) except IndexError: pass # device has no gpio except Exception as err: log(self.__qualname__, type(err).__name__, err, type='e')
async def is_ready(self): self.reply_timeout = self.at_timeout t0 = time.time() while time.time() - t0 < self.init_timeout: if await self.cmd('AT\r'): if self.data.startswith(b'OK'): return True await asyncio.sleep_ms(100) log(self.__qualname__, 'not ready') return False