async def doTest(loop): dali = simpleDali.SocketDataLink(host, port) #dali = simpleDali.WebSocketDataLink(uri) serverId = yield from dali.id(programname, username, processid, architecture) print("Resp: {}".format(serverId)) #serverInfo = yield from dali.info("STATUS") #print("Info: {} ".format(serverInfo.message)) #serverInfo = yield from dali.info("STREAMS") #print("Info: {} ".format(serverInfo.message)) network = "YY" station = "TEST" location = "00" channel = "HNZ" dutyOfficer = "Philip" trigtime = simpleDali.utcnowWithTz() streamid = "{}.{}.{}.{}/MTRIG".format(network, station, location, channel) hpdatastart = int(trigtime.timestamp() * simpleDali.MICROS) hpdataend = int(trigtime.timestamp() * simpleDali.MICROS) trigInfo = { "type": "manual", "dutyOfficer": dutyOfficer, "time": trigtime.isoformat(), "creation": trigtime.isoformat(), "override": { "modtime": trigtime.isoformat(), "value": "enable" } } trigBytes = json.dumps(trigInfo).encode('UTF-8') r = yield from dali.writeAck(streamid, hpdatastart, hpdataend, trigBytes) print("writem trigger resp {}".format(r)) dali.close()
def sendOldRecords(self): now = simpleDali.utcnowWithTz() # check to see if time to start all over again if self.duration is not None and now - self.initTime > self.duration: if verbose: print("restart after duration {}".format(self.duration)) self.initTime = now self.deltaTime = self.initTime - self.startTime for of in self.openFiles: if of.openFile is not None: of.openFile.close() self.openFiles = [] self.prevSend = None trigTask = loop.create_task(self.doDurationTrigger()) loop.run_until_complete(trigTask) sendNow = now - self.deltaTime if self.prevSend is None or self.prevSend.hour != sendNow.hour: self.openFiles = self.openFiles + self.findHourFiles(sendNow) for msFile in self.openFiles: msrList = msFile.recordsBefore(sendNow) for msr in msrList: modMsr = self.modifyRecord(msr) if self.verbose: print("send {} {} -> {} {}".format(msr.codes(), msr.starttime(), modMsr.codes(), modMsr.starttime())) self.pushMSR(modMsr) self.prevSend = sendNow
def doTest(loop, token): #dali = simpleDali.SocketDataLink(host, port) dali = simpleDali.WebSocketDataLink(uri, verbose=True) idTask = loop.create_task( dali.id(programname, username, processid, architecture)) loop.run_until_complete(idTask) serverId = idTask.result() #serverId = await dali.id(programname, username, processid, architecture) print("Resp: {}".format(serverId)) #serverInfo = yield from dali.info("STATUS") #print("Info: {} ".format(serverInfo.message)) #serverInfo = yield from dali.info("STREAMS") #print("Info: {} ".format(serverInfo.message)) # hptime = "1551313181711158" # print("Position after: {} {:d}".format(hptime, int(hptime))) # pafter = yield from dali.positionAfterHPTime(hptime) # print("PacketId after: {} {}".format(pafter.type, pafter.value)) # nextPacket = yield from dali.read(pafter.value) # print("next after: {} {} {}".format(nextPacket.type, nextPacket.dataStartTime, nextPacket.dataEndTime)) # print("hptime round trip: {} {}".format(hptime, simpleDali.datetimeToHPTime(simpleDali.hptimeToDatetime(int(hptime))))) # nowTime = simpleDali.utcnowWithTz() # print("hptime now: {} {}".format(hptime, simpleDali.datetimeToHPTime(simpleDali.hptimeToDatetime(int(hptime))))) # test auth if True: authTask = loop.create_task(dali.auth(token)) loop.run_until_complete(authTask) print("Auth Resp: {}".format(authTask.result())) if True: network = "XX" station = "TEST" location = "00" channel = "HNZ" starttime = simpleDali.utcnowWithTz() numsamples = 100 sampleRate = 200 shortData = array("h") # shorts for i in range(numsamples): shortData.append(i) msh = simpleMiniseed.MiniseedHeader(network, station, location, channel, starttime, numsamples, sampleRate) msr = simpleMiniseed.MiniseedRecord(msh, shortData) print("before writeMSeed") sendTask = loop.create_task(dali.writeMSeed(msr)) loop.run_until_complete(sendTask) print("writemseed resp {}".format(sendTask.result())) closeTask = loop.create_task(dali.close()) loop.run_until_complete(closeTask)
async def getConfig(): # FIX... only gets one packet and then stops listening configDali = initDali(daliUri) await configDali.match("/ZMAXCFG") await configDali.positionAfter(simpleDali.utcnowWithTz()-timedelta(seconds=90)) await configDali.stream() while(True): print("wait for packets") peakPacket = await configDali.parseResponse() print("got a packet: {}".format(peakPacket.streamId,)) if peakPacket.streamId.endswith("ZMAXCFG"): config = json.loads(peakPacket.data.decode("'UTF-8'")) await configDali.close() return config
def __init__(self, daliUpload, dataDir, netGlob, staGlob, locGlob, chanGlob, startTime, duration=None): self.dali = daliUpload self.dataDir=dataDir self.netGlob = netGlob self.staGlob = staGlob self.locGlob = locGlob self.chanGlob = chanGlob self.duration = duration self.initTime = simpleDali.utcnowWithTz() self.startTime = startTime self.deltaTime = self.initTime - self.startTime #self.pattern = "{net}/{sta}/{year}/{yday}/{net}.{sta}.{loc}.{chan}.{year}.{yday}.{hour}" self.pattern = "Day_{yday}/{sta}.{chan}_{yday}_{hour}.mseed" self.openFiles = [] self.prevSend = None
def __init__(self, dataDir, netGlob, staGlob, locGlob, chanGlob, startTime, staRemap, duration=None): super().__init__() self.data_rate = self.adafruit_mma8451.DATARATE_50HZ # 400Hz self.range = self.adafruit_mma8451.RANGE_2G # +/- 2G self.msrBuffer = [] self.dataDir=dataDir self.netGlob = netGlob self.staGlob = staGlob self.locGlob = locGlob self.chanGlob = chanGlob self.staRemap= staRemap self.duration = duration self.initTime = simpleDali.utcnowWithTz() self.startTime = startTime self.deltaTime = self.initTime - self.startTime #self.pattern = "{net}/{sta}/{year}/{yday}/{net}.{sta}.{loc}.{chan}.{year}.{yday}.{hour}" self.pattern = "Day_{yday}/{sta}.{chan}_{yday}_{hour}.mseed" self.openFiles = [] self.prevSend = None
async def doDurationTrigger(self): dutyOfficer="Re"+str(self.duration) streamid = "REPLAY/MTRIG" hpdatastart = int(self.startTime.timestamp() * simpleDali.MICROS) hpdataend = int(self.startTime.timestamp() * simpleDali.MICROS) trigInfo= { "type": "manual", "dutyOfficer": dutyOfficer, "time": self.initTime.isoformat(), "creation": self.startTime.isoformat(), "override": { "modtime": simpleDali.utcnowWithTz().isoformat(), "value": "enable" } } trigBytes = json.dumps(trigInfo).encode('UTF-8') r = await self.dali.writeAck(streamid, hpdatastart, hpdataend, trigBytes) print("writem trigger resp {}".format(r));
async def doSingleLapAroundTheTrack(self): if self.token is not None and simpleDali.timeUntilExpireToken( self.token) < timedelta(0): # maybe someone gave us a new one? if self.verbose: print("token expired, reloading") self.reloadToken() if self.token is not None and simpleDali.timeUntilExpireToken( self.token) < timedelta(0): raise Exception("Expired token in {}...".format( self.tokenFilename)) if self.daliUpload is None: # first time or maybe something bad happened print(" sendMyIP while loop {} closed={}".format( self.daliUpload is not None, self.daliUpload is not None and self.daliUpload.isClosed())) self.daliUpload = await self.initConnections(self.daliUpload) myIPaddr = self.getIPAddr() starttime = simpleDali.utcnowWithTz() jsonMessage = { "station": self.sta, "time": starttime.isoformat(), "ip": myIPaddr } streamid = "{}_{}/IP".format(self.net, self.sta) hpdatastart = simpleDali.datetimeToHPTime(starttime) hpdataend = simpleDali.datetimeToHPTime(starttime) response = await self.daliUpload.writeJSON(streamid, hpdatastart, hpdataend, jsonMessage) if self.verbose: print("send ip as {} ip = {} as json, {}".format( streamid, myIPaddr, response)) if response.type == 'ERROR' and response.message.startswith( simpleDali.NO_SOUP): print("AUTHORIZATION failed, quiting...") self.keepGoing = False
def ProcessHoldingPen(): global maxAccPacket_list global trig_HoldingPen tooYoungTriggers = [] trig = trig_HoldingPen.get() logging.info("got a trigger: {} {} end: {}".format(trig["class"], trig["heat"], trig["endTime"])) while trig["endTime"] > simpleDali.utcnowWithTz(): time.sleep(1) FL_acc = [0] NL_acc = [0] CT_acc = [0] NR_acc = [0] FR_acc = [0] FL0_acc = [0] FL4G_acc = [0] FL60_acc = [0] FL330_acc = [0] FL660_acc = [0] FL1K_acc = [0] count = 0 for maxAccJson in maxAccPacket_list: if maxAccJson["start_time"] > trig["startTime"] and maxAccJson["end_time"] < trig["endTime"]: count = count + 1 if maxAccJson["station"] == "FL": FL_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "NL": NL_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "CT": CT_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "NR": NR_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "FR": FR_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "FL0": FL0_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "FL60": FL60_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "FL330": FL330_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "FL660": FL660_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "FL1K": FL1K_acc.append(maxAccJson["maxacc"]) elif maxAccJson["station"] == "FL4G": FL4G_acc.append(maxAccJson["maxacc"]) else: #logging.info("maxACC Packet doesn't contain a station: {}".format(maxAccJson)) pass d = datetime.now(timezone.utc) edt = timezone(timedelta(hours=-4), name="EDT") d_edt = d.astimezone(tz=edt) weekday = date.isoweekday(d_edt) if weekday == 1: dayName = "Monday" if weekday == 2: dayName = "Tuesday" if weekday == 3: dayName = "Wednesday" if weekday == 4: dayName = "Thursday" if weekday == 5: dayName = "Friday" if weekday == 6: dayName = "Saturday" if weekday == 7: dayName = "Sunday" trig["startTime"] = trig["startTime"].strftime("%Y-%m-%dT%H:%M:%SZ") trig["endTime"] = trig["endTime"].strftime("%Y-%m-%dT%H:%M:%SZ") ResultsJson = { "Day_Name": dayName, "Trigger_Info": trig, "peakACC": { "FL": max(FL_acc), "NL": max(NL_acc), # "CT": max(CT_acc), # "NR": max(NR_acc), # "FR": max(FR_acc), "FL0": max(FL0_acc), "FL60": max(FL60_acc), "FL330": max(FL330_acc), "FL660": max(FL660_acc), "FL1K": max(FL1K_acc), "FL4G": max(FL4G_acc), } } SendResultsJson(ResultsJson) MostRecentResult = { "class": trig["class"], "heat": trig["heat"], "day": dayName } with open("mseed/www/results/MostRecentResult.json","w") as f: if f is not None: json.dump(MostRecentResult,f) else: logging.warning("can't save results to mseed/www/results/MostRecentResult.json for {}".format(MostRecentResult))
maxJson["end_time"] = e return out if __name__ == "__main__": # execute only if run directly as a script, ignore if imported # note: each element of x,y,z makes one vector! array_x = [1, 2, 3, 4, 500, 15, 25] array_y = [5, 6, 7, 8, 32, 69, 70] array_z = [9, 10, 11, 12, 47, 100, 0] gain = 2 theta = 20.0 alpha = 0 station = 'PI01' start_time = simpleDali.utcnowWithTz().replace(hour=0, minute=0, second=0, microsecond=0) time_diff = timedelta(seconds=0.10) end_time = start_time + time_diff maxWindow = timedelta(seconds=0.25) # print('---') # print(sendPeakAccel(newJson)) # timedelta should be about 0.25-0.5 s establishedJson = peakAccelerationCalculation(array_x, array_y, array_z, theta, alpha, station, start_time, end_time, gain) print("first: " + jsonToString(establishedJson)) start_time = start_time + timedelta(seconds=0.10)
import configChecker import filecmp import shutil import simpleDali configDirectory = "./ConfigFiles" oldfile = configDirectory + "/config_deployed" newfile = configDirectory + "/config_new" if (filecmp.cmp(oldfile, newfile)): print("files are the same") else: print("files differ") if (filecmp.cmp(oldfile, newfile)): # Files are the same, no action required noChange = True else: # Files are different, process the new one noChange = False json_file = open(newfile) goodConfig = configChecker.configSanityCheck(json_file) if (not goodConfig): print("Config file fails") else: print("Config file passes") starttime = simpleDali.utcnowWithTz() shutil.move(oldfile, oldfile + "_" + str(starttime)) shutil.copy2(newfile, oldfile)
def run(self): loop = asyncio.get_event_loop() loop.set_exception_handler(self.exceptionHandler) repeatException = False while self.keepGoing: try: if self.token is not None and simpleDali.timeUntilExpireToken( self.token) < timedelta(0): # maybe someone gave us a new one? if self.verbose: print("token expired, reloading") self.reloadToken() if self.token is not None and simpleDali.timeUntilExpireToken( self.token) < timedelta(0): raise Exception("Expired token in {}...".format( self.tokenFilename)) if self.daliUpload is None or self.daliUpload.isClosed(): # first time or maybe something bad happened initTask = loop.create_task( self.initConnections(self.daliUpload)) loop.run_until_complete(initTask) if initTask.exception() is not None: raise initTask.exception() self.daliUpload = initTask.result() starttime = simpleDali.utcnowWithTz() jsonMessage = { "Loc": { "PI01": "FR", "PI02": "FL", "PI03": "NO", "PI04": "NO", "PI05": "FR", "PI06": "NO", "PI07": "NL", "PI99": "NR" }, "LocInfo": { "FL": { "Angles": { "Theta": 70.0, "Alpha": 0.0 }, "Name": "Far Left Wall" }, "NL": { "Angles": { "Theta": 90.0, "Alpha": 0.0 }, "Name": "Left Starters Area" }, "CT": { "Angles": { "Theta": 0.0, "Alpha": 0.0 }, "Name": "Center Wall End" }, "NR": { "Angles": { "Theta": -90.0, "Alpha": 180.0 }, "Name": "Right Starters Area" }, "FR": { "Angles": { "Theta": -110.0, "Alpha": 180.0 }, "Name": "Far Right Wall" }, "FK": { "Angles": { "Theta": 45.0, "Alpha": 0.0 }, "Name": "Fake Loc, PI99" } } } streamid = "{}.{}/ZMAXCFG".format(self.net, 'ZMAX') hpdatastart = simpleDali.datetimeToHPTime(starttime) hpdataend = simpleDali.datetimeToHPTime(starttime) jsonSendTask = loop.create_task( self.daliUpload.writeJSON(streamid, hpdatastart, hpdataend, jsonMessage)) loop.run_until_complete(jsonSendTask) if jsonSendTask.exception() is not None: self.daliUpload.close() if self.verbose: print("Exception sending json: {}".format( jsonSendTask.exception())) raise jsonSendTask.exception() else: response = jsonSendTask.result() if self.verbose: print("send config as {} as json, {}".format( streamid, response)) if response.type == 'ERROR' and response.message.startswith( simpleDali.NO_SOUP): print("AUTHORIZATION failed, quiting...") self.keepGoing = False #keepGoing = False if repeatException: if self.verbose: print("Recovered from repeat exception") repeatException = False except Exception: if self.daliUpload is not None: self.daliUpload.close() if not repeatException: print(traceback.format_exc()) repeatException = True for tempSleep in range(self.interval): # sleep for interval seconds, but check to see if we should # quit once a second if self.keepGoing: time.sleep(1) loop.run_until_complete(loop.create_task(self.daliUpload.close())) loop.close()
sineArg = 0 sineStep = 2 * math.pi / sineFreq / sps gain = 1000 numPackets = numSeconds * sps / samplesAvail sta = "SINE".upper() net = "XX" loc = "00" chanList = ["HNZ"] miniseedBuffers = dict() for chan in chanList: miniseedBuffers[chan] = dataBuffer.DataBuffer( net, sta, loc, chan, sps, encoding=simpleMiniseed.ENC_SHORT) nextStart = simpleDali.utcnowWithTz() for i in range(int(numPackets)): packetDeltaTime = timedelta(seconds=1.0 * (samplesAvail - 1) / sps) start = nextStart - packetDeltaTime chan = chanList[0] chanData = [] for i in range(samplesAvail): chanData.append(int(gain * math.sin(sineArg))) sineArg += sineStep miniseedBuffers[chan].push(start, chanData) nextStart = nextStart + timedelta(seconds=1.0 * (samplesAvail) / sps) for chan in chanList: miniseedBuffers[chan].flush()