def __init__(self, inflow, interval=None): """ Initializes rate-limit (for all clients). :param inflow: number of tokens added to bucket :param interval: number of second, every [interval] seconds [inflow] tokens are added to each client's bucket. If it's None, adding should be done manually. Maximum number of tokens in the bucket is set to inflow * rate_limiter_bucket_capacity, which comes from master configuration. """ self.__buckets = {} self.__inflow = inflow self.__max_value = inflow * master_config.getint('rate_limiter_bucket_capacity') if interval: timers.timer(self.add_tokens_all, interval, False)
def __init__(self, inflow, interval=None): """ Initializes rate-limit (for all clients). :param inflow: number of tokens added to bucket :param interval: number of second, every [interval] seconds [inflow] tokens are added to each client's bucket. If it's None, adding should be done manually. Maximum number of tokens in the bucket is set to inflow * rate_limiter_bucket_capacity, which comes from master configuration. """ self.__buckets = {} self.__inflow = inflow self.__max_value = inflow * master_config.getint( 'rate_limiter_bucket_capacity') if interval: timers.timer(self.add_tokens_all, interval, False)
def exitSocketDataMode(): try: #Exit data mode delaySec(11) ##this time is based on esc sequence guard time #Start timeout counter timerA = timers.timer(0) timerA.start(20) #Sending +++ print 'Sending Data Mode escape sequence' res = MDM.send('+++', 10) #Wait for response res = '' while ((res.find("OK")<=-1) and (res != 'timeOut')): MOD.watchdogReset() res = res + MDM.receive(50) pass if timerA.isexpired(): res = 'timeOut' except: print 'Script encountered an exception.' print 'Exception Type: ' + str(sys.exc_type) print 'MODULE -> ATC' print 'METHOD -> exitSocketDataMode()' print res return res
def __init__(self, logger, plugname, table, column): self.__logger = logger self.__plugname = plugname # Get the max epoch for each set. Then get the maximum version for each such set & epoch self.__version_query = ''' SELECT addresses.name, addresses.epoch, MAX(raw_addresses.version) FROM %TABLE% AS raw_addresses JOIN (SELECT %COLUMN% AS name, MAX(epoch) AS epoch FROM %TABLE% GROUP BY %COLUMN%) AS addresses ON raw_addresses.%COLUMN% = addresses.name AND raw_addresses.epoch = addresses.epoch GROUP BY addresses.name, addresses.epoch'''.replace("%TABLE%", table).replace("%COLUMN%", column) self.__diff_query = ''' SELECT %TABLE%.address, add FROM (SELECT address, MAX(version) AS version FROM %TABLE% WHERE %COLUMN% = %s AND epoch = %s AND version > %s AND version <= %s GROUP BY address) AS lasts JOIN %TABLE% ON %TABLE%.address = lasts.address AND %TABLE%.version = lasts.version WHERE %TABLE%.%COLUMN% = %s AND epoch = %s ORDER BY address'''.replace("%TABLE%", table).replace("%COLUMN%", column) self._conf = {} self._addresses = {} self.__cache = {} # Reset whenever the DB contains something new. self.__conf_checker = timers.timer(self.__check_conf, 60, True)
def mdmResponse(theTerminator, timeOut): # This function waits for AT Command response and handles errors and ignores unsolicited responses # Input Parameter Definitions # theTerminator: string or character at the end of a received string that indicates end of a response # timeOut: number of seconds command could take to respond try: print 'Waiting for AT Command Response' #Start timeout counter timerA = timers.timer(0) timerA.start(timeOut) #Wait for response res = '' while ((res.find(theTerminator)<=-1) and (res.find("ERROR")<=-1) and (res != 'timeOut')): MOD.watchdogReset() res = res + MDM.receive(10) pass if timerA.isexpired(): res = 'timeOut' except: printException("mdmResponse()") return res
def __init__(self, plugins, config): plugin.Plugin.__init__(self, plugins) self.__interval = int(config['interval']) self.__aggregate_delay = int(config['aggregate_delay']) self.__downloader = timers.timer(self.__init_download, self.__interval, False) self.__data = {} self.__last = self.__current = int(time.time())
def impostaStatoTre(): print("Passaggio di stato: " + str(state) + " -> 3" ) global state state = 3 pwm.write(Serratura,PERIOD,SERRATURA_SERVO_APERTO,MICROS) timer_porta = timers.timer() timer_porta.start()
def mdmResponse(theTerminator, timeOut): # This function waits for AT Command response and handles errors and ignores unsolicited responses # Input Parameter Definitions # theTerminator: string or character at the end of a received string which indicates end of a response # timeOut: number of seconds command could take to respond try: print 'Waiting for AT Command Response' #Start timeout counter timerA = timers.timer(0) timerA.start(timeOut) #Wait for response res = '' while ((res.find(theTerminator)<=-1) and (res.find("ERROR")<=-1) and (res != 'timeOut')): MOD.watchdogReset() res = res + MDM.receive(10) pass if timerA.isexpired(): res = 'timeOut' except: print 'Script encountered an exception.' print 'Exception Type: ' + str(sys.exc_type) print 'MODULE -> ATC' print 'METHOD -> mdmResponse(' + theTerminator + ',' + timeOut + ')' return res
def isGprsAttached(timeOut): # This function waits until the GPRS attaches exitLoop = -1 try: #Start timeout counter timerA = timers.timer(0) timerA.start(timeOut) #Wait until registered to GSM Network while (exitLoop == -1): MOD.watchdogReset() res = ATC.sendAtCmd('AT+CGREG?',ATC.properties.CMD_TERMINATOR,0,5) if (res[res.rfind(',')+1:len(res)] == '5' or res[res.rfind(',')+1:len(res)] == '1'): exitLoop = 0 break if timerA.isexpired(): break #Exit while except: printException("isGprsAttached()") return exitLoop
def __init__(self, plugins, config): plugin.Plugin.__init__(self, plugins) self.__config = config self.__top_filter_cache = {} diff_addr_store.DiffAddrStore.__init__(self, logger, "flow", "flow_filters", "filter") self.__delayed_config = {} self.__delayed_conf_timer = timers.timer(self.__delayed_config_send, 120) self.__rate_limiter = rate_limit.RateLimiter(int(self.__config['rate_limit_number']), int(self.__config['rate_limit_interval']))
def _read(timeout=2000): t = timers.timer() t.start() while not _ser.available(): if t.get() > timeout: return RESP_TIMEOUT sleep(2) return _ser.readline().strip('\r\n')
def send_CM(inSTR,connId,timeOut): # This function sends a string while in Command Mode # Arguments: # inSTR: String to send # connId: Connection # # timeOut: Amount of time alotted to send # # Returns: # 0: Pass # 1: String argument empty # -1: Exception # -2: Timeout if (len(inSTR)==0): return 1 try: res = MDM.send('AT#SSEND=' + str(connId) + '\r\n', 0) #Start timeout counter timerA = timers.timer(0) timerA.start(timeOut) prompt = '\r\n> ' #Start looking for '\r\n>' while(1): properties.CMD_BUFFER = properties.CMD_BUFFER + MDM.receive(1) pos1 = properties.CMD_BUFFER.find(prompt) #look for prompt characters if (pos1>=0): properties.CMD_BUFFER = properties.CMD_BUFFER[0:pos1] + properties.CMD_BUFFER[pos1+len(prompt):len(properties.CMD_BUFFER)] res = MDM.send(inSTR, 0) res = MDM.sendbyte(0x1a, 0) tempread = '' res = '' while(1): tempread = MDM.read() if (tempread != ''): res = res + tempread if (res.find('OK')>=0): return (0) #Pass if timerA.isexpired(): return (-2) #Expired, can't find OK response if timerA.isexpired(): return (-2) #Expired, no prompt found except: printException("send_CM(" + inSTR + "," + connId + "," + timeOut + ")") JANUS_SER.sendUART("Send CM Exception. \r\n") #Would return with something else before this if it passes without exception return (-1)
def _startTimerMax(self): self._timerMin = None self._timerMax = timers.timer() if self._sequenceLongFunction and self._sequenceStep == 0: self._timerMax.one_shot(self._sequenceTimes[self._sequenceStep][1], self._markTimerMax) else: self._timerMax.one_shot(self._sequenceTimes[self._sequenceStep][1], self._sequenceReset)
def start(self): """ .. method:: start() Sends a keep alive message as soon as the device is connected to the platform and starts a repeating timer to send subsequent keep alive messages every `self.interval` milliseconds """ self.timer = timers.timer() self.timer.interval(self.interval, self.send_keep_alive) self.timer.start()
def __init__(self, plugins, config): plugin.Plugin.__init__(self, plugins) self.__tokens = {} self.__reload_config() self.__receiver = UDPReceiver(self) reactor.listenUDP(self.__port, self.__receiver) self.__check_timer = timers.timer(self.__check, 300, False) self.__sent = None self.__batch = None self.__prefix = None self.__now = None
def impostaStatoDue(): print("Passaggio di stato: " + str(state) + " -> 2" ) global state timer_tastierino.clear() state = 2 #display.display_access(1) pwm.write(Serratura,PERIOD,SERRATURA_SERVO_APERTO,MICROS) timer_serratura = timers.timer() timer_serratura.start() #timer_serratura.one_shot(TEMPO_SERRATURA_CHIUSURA,notifica_tempo_serratura) print('Timer attivato')
def startSampling(self,sampling_times,observation_windows,get_types): self._stopSampling = False self._samplingTimer = timers.timer() self._samplingTimes = sampling_times self._diffTimes = self._samplingTimes[:] self._getTypes = get_types for i in range(0,self._sensorsN): if observation_windows[i]: self._sensors[i].setSamplingTime(sampling_times[i]) self._sensors[i].setObservationWindow(observation_windows[i]) else: self._sensors[i].skipEval = True self._sample()
def __init__(self, frame_rate,callback_fun,interp_fun="LINEAR"): self.frameRate=frame_rate self.period=1000//frame_rate self.interpolator=interp_fun self.timer=timers.timer() self.animation=[] self.totDuration=0 self.pointList=[] self.callback=callback_fun self.currentBlock=0 self.currentStep=0 self.currentValue=0 self.state="IDLE"
def send_CM(inSTR, connId, timeOut): ## TWH - 09/16/2009 ## Need to determine to timeout for this command if len(inSTR) == 0: return 1 try: res = MDM.send("AT#SSEND=" + str(connId) + "\r\n", 0) # Start timeout counter timerA = timers.timer(0) timerA.start(timeOut) prompt = "\r\n> " # Start looking for '\r\n>' while 1: properties.CMD_BUFFER = properties.CMD_BUFFER + MDM.receive(1) pos1 = properties.CMD_BUFFER.find(prompt) # look for prompt characters if pos1 >= 0: properties.CMD_BUFFER = ( properties.CMD_BUFFER[0:pos1] + properties.CMD_BUFFER[pos1 + len(prompt) : len(properties.CMD_BUFFER)] ) res = MDM.send(inSTR, 0) res = MDM.sendbyte(0x1A, 0) res = "" tmpByte = -1 while 1: tmpByte = MDM.readbyte() if tmpByte != -1: res = res + tmpByte if res.find("\r\nOK\r\n") >= 0: return 0 if timerA.isexpired(): return -2 if timerA.isexpired(): return -2 except: printException("send_CM()") return -3
def __start_task(self, task): """ Start a task - send it to some set of routers and queue the others. """ task.running = True self.__last_id += 1 self.__last_id %= 2**32 task_id = self.__last_id task.task_id = task_id self.__active_tasks[task_id] = task logger.info("Starting task %s as id %s", task.name(), task_id) task.starter = timers.timer(lambda: self.__send_to_client(task), self.__start_interval, False) self.__send_to_client(task) self.__check_finished(task) # In case we have no clients connected now, we just finished it.
def delaySec(seconds): try: if(seconds<=0): return timerA = timers.timer(0) timerA.start(seconds) while 1: MOD.watchdogReset() if timerA.isexpired(): break except: printException("delaySec()") return
def __init__(self, plugins, config): plugin.Plugin.__init__(self, plugins) def getTasker(name): (modulename, classname) = name.rsplit('.', 1) module = importlib.import_module(modulename) result = getattr(module, classname)(config) logger.info('Loaded tasker %s from %s', result.code(), name) return result self.__taskers = map(getTasker, re.split('\s+', config['taskers'])) self.__parallel_limit = int(config['parallel_limit']) self.__task_timeout = int(config['task_timeout']) * 60 self.__start_interval = int(config['start_interval']) interval = int(config['interval']) * 60 self.__checker = timers.timer(self.__check_schedules, interval, False) self.__connected = plugins.get_clients # Store function to get list of clients self.__active_tasks = {} self.__last_id = 0
def send_CM(inSTR,connId,timeOut): if (len(inSTR)==0): return 1 try: res = MDM.send('AT#SSEND=' + str(connId) + '\r\n', 0) #Start timeout counter timerA = timers.timer(0) timerA.start(timeOut) prompt = '\r\n> ' #Start looking for '\r\n>' while(1): properties.CMD_BUFFER = properties.CMD_BUFFER + MDM.receive(1) pos1 = properties.CMD_BUFFER.find(prompt) #look for prompt characters if (pos1>=0): properties.CMD_BUFFER = properties.CMD_BUFFER[0:pos1] + properties.CMD_BUFFER[pos1+len(prompt):len(properties.CMD_BUFFER)] res = MDM.send(inSTR, 0) res = MDM.sendbyte(0x1a, 0) res = '' tmpByte = -1 while(1): tmpByte = MDM.readbyte() if (tmpByte != -1): res = res + tmpByte if (res.find('\r\nOK\r\n')>=0): return 0 if timerA.isexpired(): return -2 if timerA.isexpired(): return -2 except: printException("send_CM(" + inSTR + "," + connId + "," + timeOut + ")") return -3
def exitDataMode(): try: #Exit data mode ##Lookup the Escape Sequence Guard Time ## Future Use # Delay to meet Escape Sequence Guard Time ## Remove Hard Coded Escape Sequence Guard Time delaySec(1) #Start timeout counter timerA = timers.timer(0) timerA.start(20) ##Lookup the Escape Sequence ## Future Use #Sending +++ ## Remove Hard Coded Escape Sequence res = MDM.send('+++', 10) #Wait for response res = '' while ((res.find("OK")<=-1) and (res != 'timeOut')): MOD.watchdogReset() res = res + MDM.receive(50) pass if timerA.isexpired(): res = 'timeOut' except: printException("exitDataMode()") print res return res
def __init__(self, plugins, config): plugin.Plugin.__init__(self, plugins) self.__bucket_count = int(config['bucket_count']) self.__hash_count = int(config['hash_count']) def getCriterion(name): (modulename, classname) = name.rsplit('.', 1) module = importlib.import_module(modulename) result = getattr(module, classname)() logger.info('Loaded criterion %s from %s', result.code(), name) return result self.__criteria = map(getCriterion, re.split('\s+', config['criteria'])) self.__history_size = int(config['history_size']) self.__config_version = int(config['config_version']) self.__max_key_count = int(config['max_key_count']) self.__granularity = int(float(config['granularity']) * 1000) self.__max_timeslots = int(float(config['max_timeslots'])) # Just an arbitrary number self.__seed = 872945724987 self.__downloader = timers.timer(self.__init_download, int(config['interval'], False)) # We are just gathering data between these two time stamps self.__lower_time = 0 self.__upper_time = 0 self.__gather_history_max = int(config['gather_history_max']) self.__process_delay = int(config['aggregate_delay']) self.__treshold = float(config['anomaly_threshold']) self.__groups = {} for crit in self.__criteria: self.__groups[crit.code()] = {} self.__clients = {} self.__gathering = False self.__aggregating_keys = False self.__have_keys = False self.__hasher = buckets.rng.Hash( self.__seed, self.__hash_count, 256 * max(map(lambda c: c.item_len(), self.__criteria))) # Do we have keys to commit? self.__background_processing = False
def delaySec(seconds): try: if(seconds<=0): return timerA = timers.timer(0) timerA.start(seconds) while 1: MOD.watchdogReset() if timerA.isexpired(): break except: print 'Script encountered an exception.' print 'Exception Type: ' + str(sys.exc_type) print 'MODULE -> ATC' print 'METHOD -> delaySec(' + seconds + ')' return
def initGPS (speed,format): try: #GPS RESET, GPIO 18 configured as Output, value is Cleared to '0' #GPS held in RESET GPIO.setIOdir(18,1,1) #GPS RESET, GPIO 18 configured as Output, value is Cleared to '0' #GPS is running GPIO.setIOvalue(18, 0) #Init Serial Port Settings res = GSM864QP_SER.init_parameters(speed,format) MOD.sleep(10) res = GSM864QP_SER.send_50PIN('\r\n') #Disable all NMEA output sentences #NMEA GPS sentences will only transmit when polled by CW20.update() method res = GSM864QP_SER.send_50PIN('$PNMRX103,ALL,0\r\n') ## Start timeout timer CW20_timerA = timers.timer(0) CW20_timerA.start(2) # Empty Serial Port Buffer res = "junk" while(res != ""): res = GSM864QP_SER.read_50PIN() if (CW20_timerA.isexpired()): break except: print 'Script encountered an exception.' print 'Exception Type: ' + str(sys.exc_type) print 'MODULE -> CW20' print 'METHOD -> initGPS(' + speed + ',' + format + ')' return
def __init__(self, logger, plugname, table, column): self.__logger = logger self.__plugname = plugname # Get the max epoch for each set. Then get the maximum version for each such set & epoch self.__version_query = ''' SELECT addresses.name, addresses.epoch, MAX(raw_addresses.version) FROM %TABLE% AS raw_addresses JOIN (SELECT %COLUMN% AS name, MAX(epoch) AS epoch FROM %TABLE% GROUP BY %COLUMN%) AS addresses ON raw_addresses.%COLUMN% = addresses.name AND raw_addresses.epoch = addresses.epoch GROUP BY addresses.name, addresses.epoch'''.replace("%TABLE%", table).replace( "%COLUMN%", column) self.__diff_query = ''' SELECT %TABLE%.address, add FROM (SELECT address, MAX(version) AS version FROM %TABLE% WHERE %COLUMN% = %s AND epoch = %s AND version > %s AND version <= %s GROUP BY address) AS lasts JOIN %TABLE% ON %TABLE%.address = lasts.address AND %TABLE%.version = lasts.version WHERE %TABLE%.%COLUMN% = %s AND epoch = %s ORDER BY address'''.replace("%TABLE%", table).replace("%COLUMN%", column) self._conf = {} self._addresses = {} self.__cache = {} # Reset whenever the DB contains something new. self.__conf_checker = timers.timer(self.__check_conf, 60, True)
def getNetworkTime(timeOut): # This function forces the Network to update RTC with GSM Network Time tmpReturn = -1 try: res = ATC.sendAtCmd("AT#NITZ=1",ATC.properties.CMD_TERMINATOR,0,2) #set NITZ command to update Network Time res = ATC.sendAtCmd("AT+COPS=2",ATC.properties.CMD_TERMINATOR,0,2) #set COPS command to force GSM Registration to disconnect #Start timeout counter timerA = timers.timer(0) timerA.start(timeOut) #Wait until GSM module is not registered to Network while (1): MOD.watchdogReset() res = ATC.sendAtCmd('AT+CREG?',ATC.properties.CMD_TERMINATOR,0,5) if (res == "+CREG: 0,0"): break if timerA.isexpired(): return tmpReturn res = ATC.sendAtCmd("AT+COPS=0",ATC.properties.CMD_TERMINATOR,0,2) #set COPS command to force GSM Registration res = isGsmRegistered(timeOut) if (res == 0): tmpReturn = 0 res = ATC.sendAtCmd("AT+CCLK?",ATC.properties.CMD_TERMINATOR,0,2) #Query RTC Clock except: printException("getNetworkTime") return tmpReturn
def startSampling(self,time,observation_window,get_type = "raw",time_unit = MILLIS): """ .. method:: startSampling(time,observation_window,get_type,time_unit) Starts reading samples every _samplingTime. Length of _observationWindowN to evaluate window parameters, type of acquisition and time_unit characterize the acquisition itself. If no observation_window is passed the evaluation of window parameters is skipped. Returns self to allow a compact code (see :ref:`doEverySample <doEverySample>`) """ self._samplingTime = time self._samplingGetType = get_type if type(observation_window) != PNONE: self._observationWindowN = observation_window self._observationWindowT = observation_window * time else: self.skipEval = True if time_unit == MILLIS: self._samplingTimer = timers.timer() self._samplingTimer.interval(self._samplingTime,self._sample) elif time_unit == MICROS: thread(self._microSample) return self
def AutoONControl(inCommand, inSelection): # This function sends a signal to MCU to tell it whether or not to handle Auto On, # waits for response on GPIO1 to verify the MCU is in the proper state. # Arguments: # inCommand - Select what to do, enter 'READ' or 'SET'. # READ - Checks the MCU signal to verify the mode # SET - Utilizes inSelection to change the mode. # inSelection - Select to have the MCU run Auto-On or not, enter 'ON' or 'OFF. # OFF - Auto-On is Disabled # ON - Auto-On is Enabled # # Returns: # InCommand: READ # 0: Pass, Auto-on OFF # 1: Pass, Auto-on ON # -1: Exception # -2: Time out # InCommand: SET # 0: Pass, Auto-on OFF # 1: Pass, Auto-on ON # -1: Exception # -2: Time out tmpReturn = -1 try: #GPIO.getIOvalue(GPIOnumber) #MOD.sleep(20) #Delay # 9 - GPIO1 : Used as MCU signal verification if (inCommand == 'READ'): res = GPIO.getIOvalue(9) return res #GPIO.setIOvalue(GPIOnumber, value) # 6 - Auto ON Control # 9 - GPIO1 : Used as MCU signal verification if (inSelection == 'ON'): res = GPIO.setIOvalue(6, 1) #Set a Timer for a quick loop to verify, we do this because it's a "just in case" breakout as opposed to a simple delay and check. timerA = timers.timer(0) timerA.start(5) #5 seconds is MORE than enough. IoVal = GPIO.getIOvalue(9) #JANUS_SER.sendUART("Value from MCU: " + str(IoVal) + "\r\n") while (IoVal != 1): IoVal = GPIO.getIOvalue(9) if timerA.isexpired(): return (-2) #Time out while finding the signal res = GPIO.setIOvalue(6, 0) #End the HIGH pulse, MCU only toggles on a high signal return IoVal #Return the read value elif (inSelection == 'OFF'): res = GPIO.setIOvalue(6, 1) #Set a Timer for a quick loop to verify, we do this because it's a "just in case" breakout as opposed to a simple delay and check. timerA = timers.timer(0) timerA.start(5) #5 seconds is MORE than enough. IoVal = GPIO.getIOvalue(9) JANUS_SER.sendUART("Value from MCU: " + str(IoVal) + "\r\n") while (IoVal != 0): IoVal = GPIO.getIOvalue(9) if timerA.isexpired(): return (-2) #Time out while finding the signal res = GPIO.setIOvalue(6, 0) #End the HIGH pulse, MCU only toggles on a high signal return IoVal #Return the read value except: printException("SW_IGN Exception") JANUS_SER.sendUART("SW_IGN Exception \r\n") #Return Error value return tmpReturn
def getDHT22data( _receivepin, _receivepinShort ): #expects input like (D3.ICU,D3) [TODO: do some nifty string manipulation to get "D3" from D3.ICU] ### don't execute this more than once every 2s! timer1 = timers.timer() timer1.start() foo = 0 DHT22_temp = 0 DHT22_hum = 0 BinListDHT22 = [] timeListDHT22 = [] #Go into high impedence state to let pull-up raise data line level andstart the reading process. pinMode(_receivepinShort, OUTPUT) digitalWrite(_receivepinShort, HIGH) timer1.reset() while timer1.get() < 10: foo += 1 #First set data line low for 10 milliseconds. digitalWrite(_receivepinShort, LOW) timer1.reset() while timer1.get() < 10: foo += 1 # maybe change this while to one_shot? tmpICU = icu.capture( _receivepin, LOW, 86, 10000, time_unit=MICROS ) #call to ICU seems to take some time, thus call *before* initiation is finished # End the start signal by setting data line high for [40 microseconds]. digitalWrite(_receivepinShort, HIGH) pinMode(_receivepinShort, INPUT_PULLUP) # remove all even entries, they're just "start bits", discard 1st two entries for i in range(3, len(tmpICU), 1): if i % 2 != 0: #these are the odd entries timeListDHT22.append(tmpICU[i]) # convert to list of binaries for i in range(len(timeListDHT22)): if timeListDHT22[ i] < 35: # shouldn't be longer than 28us, but allow some wiggle room here BinListDHT22.append(0) else: BinListDHT22.append(1) # extract hum, temp parts (16bits each) tmp_hum = BinListDHT22[ 0:16] #1st 16 bits are humidity, 2nd 16 bits are temperature tmp_temp = BinListDHT22[16:32] tmp_tempSign = 1 if tmp_temp[0] == 1: tmp_tempSign = -1 # neg temperatures are encoded most significant bit = 1 tmp_temp[0] = 0 tmp_temp = tmp_temp[::-1] #invert the list for conversion to decimal tmp_hum = tmp_hum[::-1] for i in range(16): DHT22_temp += tmp_temp[i] * (2**i) DHT22_hum += tmp_hum[i] * (2**i) DHT22_temp = DHT22_temp / 10 DHT22_hum = DHT22_hum / 10 digitalWrite(_receivepinShort, HIGH) timer1.clear() return (DHT22_hum, DHT22_temp)
DHT22_hum += tmp_hum[i] * (2**i) DHT22_temp = DHT22_temp / 10 DHT22_hum = DHT22_hum / 10 digitalWrite(_receivepinShort, HIGH) timer1.clear() return (DHT22_hum, DHT22_temp) ############################################################################################ ############################################################################################ #test the code sleep(1000) print("starting") sleep(500) global DHT22_temp global DHT22_hum timer2 = timers.timer() timer2.start() while True: if timer2.get() > 2500: DHT22_hum, DHT22_temp = getDHT22data(D3.ICU, D3) print(DHT22_temp, DHT22_hum) timer2.reset()
################################################################################ # Timers Advanced Use # Created by VIPER Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import timers import streams #create a serial port with default parameters streams.serial() #create new timers tsec = timers.timer() tminute = timers.timer() tshoot = timers.timer() seconds = 0 minutes = 0 #define a function to call when the timer for seconds elapse def secondpassed(): global seconds seconds += 1 print(seconds, " seconds") if seconds == 60: seconds = 0
def _startTimerMin(self): self._timerMin = timers.timer() self._timerMin.one_shot(self._sequenceTimes[self._sequenceStep][0], self._startTimerMax) curr_edge = (((self._sequenceStart + self._sequenceStep) % 2) ^ 1) self._onPinEdges[curr_edge](self.pin, self._checkTiming)
import streams import timers #import the ESP32 BLE driver: a BLE capable VM is also needed! from espressif.esp32ble import esp32ble as bledrv # then import the BLE module and beacons from wireless import ble from wireless import ble_beacons as bb streams.serial() adv_content = 0 battery_level = 40 temperature = 23.2 pdu_count = 0 uptime = timers.timer() uptime.start() # create payloads to cycle through payloads = [ bb.eddy_encode_uid("Zerynth", "Python", -69), # UID Eddystone payload bb.eddy_encode_url("https://www.zerynth.com", -69), # URL Eddystone payload bb.eddy_encode_tlm(battery_level, temperature, pdu_count, uptime.get() / 1000) # TLM Eddystone payload ] # this callback will be called at the end of an advertising cycle. # it is used to switch to the next content def adv_stop_cb(data):
def read(self): ### don't execute this more than once every 2s! # print("read") timer1 = timers.timer() timer1.start() foo = 0 self.DHT22_temp = 0 self.DHT22_hum = 0 BinListDHT22 = [] timeListDHT22 = [] #Go into high impedence state to let pull-up raise data line level and start the reading process. pinMode(self.receivepinShort,OUTPUT) digitalWrite(self.receivepinShort, HIGH) #wait 10ms timer1.reset() while timer1.get()<10: # maybe change this while to one_shot? foo+=1 # probably unecessary #First pull data line low for 10 ms. digitalWrite(self.receivepinShort, LOW) timer1.reset() while timer1.get()<10: # maybe change this while to one_shot? foo+=1 # probably unecessary # print("ICU") #get the data stream via ICU #call to ICU seems to take some time, thus call *before* initiation is finished tmpICU = icu.capture(self.receivepin,LOW,86,10000,time_unit=MICROS) # print(tmpICU) # End the start signal by setting data line high. digitalWrite(self.receivepinShort, HIGH) pinMode(self.receivepinShort,INPUT_PULLUP) # print("go to calculus") # remove all even entries, they're just "start bits", discard 1st two entries for i in range(3,len(tmpICU),1): if i%2!=0: #these are the odd entries timeListDHT22.append(tmpICU[i]) # print(timeListDHT22) # convert to list of binaries for i in range(len(timeListDHT22)): if timeListDHT22[i] < 35: # shouldn't be longer than 28us, but allow some wiggle room here BinListDHT22.append(0) else: BinListDHT22.append(1) # extract hum, temp parts (16bits each) tmp_hum = BinListDHT22[0:16] #1st 16 bits are humidity, 2nd 16 bits are temperature tmp_temp = BinListDHT22[16:32] tmp_tempSign = 1 if tmp_temp[0] == 1: tmp_tempSign = -1 # neg temperatures are encoded most significant bit = 1 tmp_temp[0] = 0 tmp_temp = tmp_temp[::-1] #invert the list for conversion to decimal tmp_hum = tmp_hum[::-1] # print(tmp_temp,tmp_hum) DHT22_temp_1 = 0 DHT22_hum_1 = 0 for i in range(16): DHT22_temp_1 += tmp_temp[i]*(2**i) DHT22_hum_1 += tmp_hum[i]*(2**i) # print(DHT22_temp_1/10,DHT22_hum_1/10) self.DHT22_temp = DHT22_temp_1/10 self.DHT22_hum = DHT22_hum_1/10 # print(self.DHT22_temp, self.DHT22_hum) digitalWrite(self.receivepinShort, HIGH) timer1.clear()
#Uncomment if SIM card is provisioned for SMS #ATC.sendSMS("GPSDemo application is running",myApp.SMS,ATC.properties.CMD_TERMINATOR,3,180) #Init GPRS #Pass in: PDP Index, APN ATC.initGPRS('1', myApp.APN, myApp.GPRS_USERID, myApp.GPRS_PASSWORD, RUN_MODE) #Initalize CW20 Receiver DEBUG.sendMsg("Initialize CW20 GPS Module\r\n",RUN_MODE) CW20.initGPS('9600','8N1') #Update Network Information res = ATC.getNetworkInfo() # Start timeout timer timerB = timers.timer(0) timerB.start(1) ping = 1 # <-- Exosite: initialize value # Loop forever, without this loop the script would run once and exit script mode. On reboot or power-on the script would run once more while (1): exitCode = -1 while (exitCode==-1): MOD.watchdogReset() #If interval timer expires then send packet to server if (timerB.isexpired()):
################################################################################ # Timers Advanced Use # Created by VIPER Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import timers import streams #create a serial port with default parameters streams.serial() #create new timers tsec=timers.timer() tminute=timers.timer() tshoot=timers.timer() seconds=0 minutes=0 #define a function to call when the timer for seconds elapse def secondpassed(): global seconds seconds +=1 print(seconds," seconds") if seconds==60: seconds=0 #define a function to call when the timer for minutes elapse def minutepassed():
return map(__process, batch) def __distribute(result): logger.debug("Batch distribute") for (callback, tresult) in result: callback(tresult) def flush(): """ Submit all work to execution, even if it doesn't make a full batch yet. """ global __batch if __batch: logger.debug("Batch flush") deferred = threads.deferToThreadPool(reactor, plugin.pool, __execute, __batch) deferred.addCallback(__distribute) __batch = [] def submit(f, callback, *args): """ Add another function for thread execution. Call calback once finished. """ logger.debug("Batch submit") global __batch global __limit __batch.append((f, args, callback)) if len(__batch) >= __limit: flush() flusher = timers.timer(flush, 2, False)
btn_pin = D2 # set the btn_pin as input with PullUp pinMode(btn_pin, INPUT_PULLUP) # Attach an interrupt on the button pin onPinFall(btn_pin, toogle_oled) # set the led pin as output for pin in air_status_led.values(): pinMode(pin, OUTPUT) # create sensor instance htu = htu21d.HTU21D(I2C0, clk=100000) sgp = sgp30.Adafruit_SGP30(I2C0) ssd = ssd1306.SSD1306(I2C1) # create ubidots iot device instance my_device = iot.Device(ubidots_conf['device_label'], ubidots_conf['user_type'], ubidots_conf['api_token']) # create a publish timer tmp_publish = timers.timer() # create save timer tmp_save = timers.timer() tmp_publish.start() tmp_save.start() init() main()
def update(): # This function receives ALL NMEA sentences and parses out data fields # You might need to add more properties to this class to get more data out of the update method # You MUST have the jumpers on the external header connecting Pin(49 & 47) and Pin(45 & 43) try: #Get NMEA RMC sentence NMEA = '' NMEA_list = '' GPSdata.GPGGA = '' GPSdata.GPGLL = '' GPSdata.GPGSA = '' GPSdata.GPGSV = '' GPSdata.GPRMC = '' GPSdata.GPZDA = '' GPSdata.GPVTG = '' ## Start timeout timer CW20_timerA = timers.timer(0) CW20_timerA.start(10) #Clear Buffer - NMEA Commands are disabled in initReceiver res='' while(res != ''): res = GSM864QP_SER.read_50PIN() if (CW20_timerA.isexpired()): break #Enable NMEA sentence to transmit once every 10 seconds res = GSM864QP_SER.send_50PIN('$PNMRX103,ALL,10\r\n') NMEA = '' while(1): res = GSM864QP_SER.read_50PIN() NMEA = NMEA + res lenNMEA = len(NMEA) pos1 = NMEA.rfind('GPVTG',0) pos2 = NMEA.rfind('\r\n',pos1) if ((pos1 >=0) and (pos2 >= pos1)): #NMEA data is complete break if (CW20_timerA.isexpired()): GPSdata.GPGGA = 'TIMEOUT\r\n' GPSdata.GPGLL = 'TIMEOUT\r\n' GPSdata.GPGSA = 'TIMEOUT\r\n' GPSdata.GPGSV = 'TIMEOUT\r\n' GPSdata.GPRMC = 'TIMEOUT\r\n' GPSdata.GPZDA = 'TIMEOUT\r\n' GPSdata.GPVTG = 'TIMEOUT\r\n' return NMEA_list = NMEA.split('\r\n') for x in NMEA_list: sentence_list = x.split(',') if (sentence_list[0] == '$GPGGA'): GPSdata.GPGGA = str(x) + '\r\n' elif (sentence_list[0] == '$GPGLL'): GPSdata.GPGLL = str(x) + '\r\n' elif (sentence_list[0] == '$GPGSA'): GPSdata.GPGSA = str(x) + '\r\n' elif (sentence_list[0] == '$GPGSV'): GPSdata.GPGSV = GPSdata.GPGSV + str(x) + '\r\n' elif (sentence_list[0] == '$GPRMC'): GPSdata.GPRMC = str(x) + '\r\n' elif (sentence_list[0] == '$GPZDA'): GPSdata.GPZDA = str(x) + '\r\n' elif (sentence_list[0] == '$GPVTG'): GPSdata.GPVTG = str(x) + '\r\n' #Disable all NMEA Sentences res = GSM864QP_SER.send_50PIN('$PNMRX103,ALL,0\r\n') while(res != ''): res = GSM864QP_SER.read_50PIN() if (CW20_timerA.isexpired()): break except: print 'Script encountered an exception.' print 'Exception Type: ' + str(sys.exc_type) print 'MODULE -> CW20' print 'METHOD -> update()' GPSdata.GPGGA = 'EXCEPTION\r\n' GPSdata.GPGLL = 'EXCEPTION\r\n' GPSdata.GPGSA = 'EXCEPTION\r\n' GPSdata.GPGSV = 'EXCEPTION\r\n' GPSdata.GPRMC = 'EXCEPTION\r\n' GPSdata.GPZDA = 'EXCEPTION\r\n' GPSdata.GPVTG = 'EXCEPTION\r\n' return
#Flags access_granted = False lock_requested = False tempo_serratura_finito = False tempo_porta_finito = False #display=lcd.SmartDoorLCD(I2C0) ultrasonic = hcsr04.hcsr04(D15, D2) distanzaUltraSonic = 0.0 avoidance = avoidance.AvoidanceSensor(D0) timer_tastierino = timers.timer() timer_serratura = timers.timer() timer_porta = timers.timer() #Setup tastierino s="" keymap =[ ['1','2','3','A'], ['4','5','6','B'], ['7','8','9','C'], ['*','0','#','D'] ] rows=[D23,D22,D21,D19] columns=[D18,D5,D17,D16]
from espressif.esp32net import esp32wifi as wifi_driver # For driving the esp32 WiFi chip import requests from wireless import wifi import mcu import gc import json import math import rtc import sfw from zdm import zdm sfw.watchdog(0, 120000) number_of_channels = 13 # Total number of channels following the IEEE 802.11 norm in Europe channel_activity_stats = [0] * number_of_channels # A list of channel activity t = timers.timer() # A timer to time the calls to the analysis function SSID = ' ' PASSWORD = '******' DEVICEID = ' ' JWT = ' ' TAG='wifiSniffer' device=None # Initialize serial out & WiFi chip def init(): gc.enable(500) try: # Initialize serial out
and check if the given plugin is to be allowed or not. """ if __update_cache(): __propagate_cache() global __cache p_info = __cache.get(name, set()) candidates = ((proto_ver, md5_hash), (None, md5_hash), (proto_ver, None), (None, None)) return any(candidate in p_info for candidate in candidates) def add_client(client): """ Add a client to be notified when the configuration of which plugins are allowed changes. The client is free to disappear if it seems fit. """ global __cache_clients __cache_clients.add(client) def __time_check(): """ Check repeatedly if the list of allowed plugins changed. """ if __update_cache(): __propagate_now() checker = timers.timer(__time_check, 300, False)
def stringReceived(self, string): if self.__wait_auth: self.__auth_buffer.append(string) return (msg, params) = (string[0], string[1:]) logger.trace("Received from %s: %s", self.cid(), repr(string)) if not self.__logged_in: def login_failure(msg): logger.warn('Login failure from %s: %s', self.cid(), msg) self.sendString('F') self.__challenge = None # Prevent more attempts # Keep the connection open, but idle. Prevents very fast # reconnects. if msg == 'L': # Client wants to log in. # Extract parameters. (version, params) = (params[0], params[1:]) (cid, params) = extract_string(params) (response, params) = extract_string(params) self.__cid = cid if version == 'O': self.__cid = self.__cid.encode('hex') logger.debug('Client %s sent login info', self.cid()) if params != '': login_failure('Protocol violation') return log_info = None if version != 'O': login_failure('Login scheme not implemented') return # A callback once we receive decision if the client is allowed def auth_finished(allowed): self.__wait_auth = False if allowed: self.__authenticated = True # Replay the bufferend messages for message in self.__auth_buffer: self.stringReceived(message) else: login_failure('Incorrect password') self.__auth_buffer = None # Ask the authenticator if self.__challenge: auth.auth(auth_finished, self.__cid, self.__challenge.encode('hex'), response.encode('hex')) self.__wait_auth = True elif msg == 'H': if self.__authenticated: if len(params) >= 1: (self.__proto_version,) = struct.unpack("!B", params[0]) if self.__proto_version >= 1: self.__available_plugins = {} if self.__plugins.register_client(self): if self.__proto_version == 0: # Activate all the clients in the old version. # The new protocol handles activation on plugin-by-plugin basis for p in self.__plugins.get_plugins(): self.__plugins.activate_client(p, self) else: # Please tell me when there're changes to the allowed plugins plugin_versions.add_client(self) self.__logged_in = True self.__pinger = timers.timer(self.__ping, 45 if self.cid() in self.__fastpings else 120, False) activity.log_activity(self.cid(), "login") logger.info('Client %s logged in', self.cid()) else: return else: login_failure('Asked for session before loging in') return elif msg == 'S': if len(params) != 4: logger.warn("Wrong session ID length on client %s: %s", self.cid(), len(params)) return (self.session_id,) = struct.unpack("!I", params) return elif msg == 'P': # Ping. Answer pong. self.sendString('p' + params) elif msg == 'p': # Pong. Reset the watchdog count self.__pings_outstanding = 0 self.last_pong = time.time() elif msg == 'R': # Route data to a plugin (plugin, data) = extract_string(params) self.__plugins.route_to_plugin(plugin, data, self.cid()) # TODO: Handle the possibility the plugin doesn't exist somehow (#2705) elif msg == 'V': # New list of versions of the client if self.__proto_version == 0: self.__available_plugins = {} while len(params) > 0: (name, params) = extract_string(params) (version,) = struct.unpack('!H', params[:2]) self.__available_plugins[name] = version params = params[2:] else: self.__handle_versions(params) else: logger.warn("Unknown message from client %s: %s", self.cid(), msg)
################################################################################ # Timers Basics # # Created by Zerynth Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import timers import streams # create a serial port with default parameters streams.serial() # create a new timer t = timers.timer() # start the timer t.start() minutes = 0 while True: if t.get() >= 60000: #check if 60 seconds are passed t.reset() #timer can be reset minutes += 1 seconds = t.get() // 1000 print( "time is:", minutes, ":", seconds) #just print the current value since timer start or last reset print( "System time is:", timers.now(), "(millis)"
for (callback, tresult) in result: callback(tresult) def flush(): """ Submit all work to execution, even if it doesn't make a full batch yet. """ global __batch if __batch: logger.debug("Batch flush") deferred = threads.deferToThreadPool(reactor, plugin.pool, __execute, __batch) deferred.addCallback(__distribute) __batch = [] def submit(f, callback, *args): """ Add another function for thread execution. Call calback once finished. """ logger.debug("Batch submit") global __batch global __limit __batch.append((f, args, callback)) if len(__batch) >= __limit: flush() flusher = timers.timer(flush, 2, False)
def stringReceived(self, string): if self.__wait_auth: self.__auth_buffer.append(string) return (msg, params) = (string[0], string[1:]) logger.trace("Received from %s: %s", self.cid(), repr(string)) if not self.__logged_in: def login_failure(msg): logger.warn('Login failure from %s: %s', self.cid(), msg) self.sendString('F') self.__challenge = None # Prevent more attempts # Keep the connection open, but idle. Prevents very fast # reconnects. if msg == 'L': # Client wants to log in. # Extract parameters. (version, params) = (params[0], params[1:]) (cid, params) = extract_string(params) (response, params) = extract_string(params) self.__cid = cid if version == 'O': self.__cid = self.__cid.encode('hex') logger.debug('Client %s sent login info', self.cid()) if params != '': login_failure('Protocol violation') return log_info = None if version != 'O': login_failure('Login scheme not implemented') return # A callback once we receive decision if the client is allowed def auth_finished(allowed): self.__wait_auth = False if allowed: self.__authenticated = True # Replay the bufferend messages for message in self.__auth_buffer: self.stringReceived(message) else: login_failure('Incorrect password') self.__auth_buffer = None # Ask the authenticator if self.__challenge: auth.auth(auth_finished, self.__cid, self.__challenge.encode('hex'), response.encode('hex')) self.__wait_auth = True elif msg == 'H': if self.__authenticated: if len(params) >= 1: (self.__proto_version, ) = struct.unpack( "!B", params[0]) if self.__proto_version >= 1: self.__available_plugins = {} if self.__plugins.register_client(self): if self.__proto_version == 0: # Activate all the clients in the old version. # The new protocol handles activation on plugin-by-plugin basis for p in self.__plugins.get_plugins(): self.__plugins.activate_client(p, self) else: # Please tell me when there're changes to the allowed plugins plugin_versions.add_client(self) self.__logged_in = True self.__pinger = timers.timer( self.__ping, 45 if self.cid() in self.__fastpings else 120, False) activity.log_activity(self.cid(), "login") logger.info('Client %s logged in', self.cid()) else: return else: login_failure('Asked for session before loging in') return elif msg == 'S': if len(params) != 4: logger.warn("Wrong session ID length on client %s: %s", self.cid(), len(params)) return (self.session_id, ) = struct.unpack("!I", params) return elif msg == 'P': # Ping. Answer pong. self.sendString('p' + params) elif msg == 'p': # Pong. Reset the watchdog count self.__pings_outstanding = 0 self.last_pong = time.time() elif msg == 'R': # Route data to a plugin (plugin, data) = extract_string(params) self.__plugins.route_to_plugin(plugin, data, self.cid()) # TODO: Handle the possibility the plugin doesn't exist somehow (#2705) elif msg == 'V': # New list of versions of the client if self.__proto_version == 0: self.__available_plugins = {} while len(params) > 0: (name, params) = extract_string(params) (version, ) = struct.unpack('!H', params[:2]) self.__available_plugins[name] = version params = params[2:] else: self.__handle_versions(params) else: logger.warn("Unknown message from client %s: %s", self.cid(), msg)
import threading # set up state machine class States(): def __init__(self): self.INIT = 1 self.CONFIG = 2 self.WIFI_START = 3 self.WIFI_CONFIGURE = 4 self.WIFI_TCP_LINK = 5 self.RUNNING = 6 self.ERROR = 7 # everything should start from INIT :) # moved to main.py # my_state = States.INIT # creating the global variables my_loco = WiDCCLocoDescriptor.LocoDescriptor() my_socket = socket.socket() my_socket.setblocking(False) my_socket_lock = threading.Lock() my_com_timer = timers.timer() my_com_timer_counter = 0 my_config = cfg.Config() msg_queue_in = fifo.Fifo(4) msg_queue_out = fifo.Fifo(2) msg_queue_in_lock = threading.Lock() msg_queue_out_lock = threading.Lock()
################################################################################ # Timers Basics # # Created by VIPER Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import timers import streams #create a serial port with default parameters streams.serial() #create a new timer t=timers.timer() #start the timer t.start() minutes=0 while True: if t.get()>= 60000: #check if 60 seconds are passed t.reset() #timer can be reset minutes +=1 seconds=t.get()//1000 print("time is:", minutes,":",seconds) #just print the current value since timer starts or last reset print("System time is:", timers.now(), "(millis)") #timers.now() gives the system time in milliseconds since program starts print() sleep(500) #run every 500 millisec
def main(): try: # Set Global Watchdog timeout in Seconds MOD.watchdogEnable(300) #Initialize the serial interface @ 115200, we must do this or nothing comes out the serial port res = JANUS_SER.init("115200",'8N1') if (res == -1): return JANUS_SER.sendUART("Beginning the Terminus Tracker Demo Program. \r\n\r\n") #Initialize the configuration, returns 0 for defaults, 1 for normal. ConfigLoad = JANUS_CONFIG.init() #Transpose the configuration list to myApp for usage here #We transpose only the main Config class to handle updates if (ConfigLoad == 0): myApp = JANUS_CONFIG.Config JANUS_SER.sendUART("Defaults Loaded.\r\n") elif (ConfigLoad == 1): myApp = JANUS_CONFIG.Config JANUS_SER.sendUART("Configuration File Loaded.\r\n") else: myApp = JANUS_CONFIG.Config JANUS_SER.sendUART("Configuration ERROR. Defaults Loaded.\r\n") #Initialize the I/O, turn on the stat LED res = JANUS_IO.init(myApp.SLED) if (res == -1): return #Read if Auto-On is active or not, 1 is active, 0 is inactive. res = JANUS_IO.AutoONControl('READ', myApp.AUTOON) JANUS_SER.sendUART("\r\nAuto On: " + myApp.AUTOON + "\r\n") #If Auto-on is OFF and we want it ON, set it. if (res == 0 and myApp.AUTOON == 'ON'): res = JANUS_IO.AutoONControl('SET', myApp.AUTOON) if (res == -1): return #Errored out elif (res == -2): JANUS_SER.sendUART("Timed out while waiting for MCU response. \r\n") elif (res == 1): JANUS_SER.sendUART("Auto ON Enabled. \r\n") #If Auto-on is ON and we want it OFF, set it. if (res == 1 and myApp.AUTOON == 'OFF'): res = JANUS_IO.AutoONControl('SET', myApp.AUTOON) if (res == -1): return #Errored out elif (res == -2): JANUS_SER.sendUART("Timed out while waiting for MCU response. \r\n") elif (res == 0): JANUS_SER.sendUART("Auto ON Disabled. \r\n") #If Auto-on is OFF, and we have it set as OFF. Let's see what caused this wake up and report it. #Although we can read IGN/SW directly, we check the MCU instead because they #May not be active as this point even though the MCU caught it. WakeupCause = '' if (res == 0 and myApp.AUTOON == 'OFF'): res = JANUS_IO.SW_IGN_Status() if (res == -1): return #Errored out elif (res == 0): JANUS_SER.sendUART("Wake up cause: N/O Switch \r\n") WakeupCause = 'Switch' elif (res == 1): JANUS_SER.sendUART("Wake up cause: Ignition \r\n") WakeupCause = 'Ignition' elif (res == 2): JANUS_SER.sendUART("Wake up cause: Both the Ignition and N/O Switch \r\n") WakeupCause = 'Both' elif (res == -2): JANUS_SER.sendUART("Wake up cause: Unknown \r\n") WakeupCause = 'Unknown' JANUS_SER.sendUART("\r\nInitializing Module GPRS. \r\n") #Set Network specific settings, wait for SIM card to be ready res = NETWORK.initGsmNetwork(myApp.NETWORK,myApp.BAND) if (res == -1): return #Init GPRS GPRS.init('1',myApp.APN) JANUS_SER.sendUART("GPRS Initialized. \r\n") ################################################################ #### BEGIN Newly Added Config Stuff ################################################################ #Initalize GPS JANUS_SER.sendUART("\r\nInitializing Module GPS. \r\n") res = JANUS_GPS.init(myApp.LNA) if (res != 0): JANUS_SER.sendUART("Failed to Initialize GPS, ERROR: " + res + "\r\n\r\n") return JANUS_SER.sendUART("GPS Initialized. \r\n\r\n") #Setup SMS if (myApp.SMS_ENABLED == 'TRUE'): JANUS_SER.sendUART("SMS Enabled, Initializing. \r\n") JANUS_SMS.configSMS() JANUS_SER.sendUART("SMS Initialized. \r\n\r\n") ################################################################ #### END Newly Added Config Stuff ################################################################ # Loop forever, without this loop the script would run once and exit script mode. On reboot or power-on the script would run once more while (1): MOD.watchdogReset() JANUS_SER.sendUART("Registering Module. \r\n") #Wait until module is registered to GSM Network res = NETWORK.isGsmRegistered(180) #Wait 180 seconds for module to obtain GSM registration if (res == -1): return #Wait until module is attached to GPRS res = NETWORK.isGprsAttached(180) #Wait 180 seconds for module to obtain GPRS Attachment if (res == -1): return JANUS_SER.sendUART("Module Registered Successfully. \r\n\r\n") ############################################################################################################################# ## Opening Socket Connection to Server ## We are opening in Command Mode to have the best control ############################################################################################################################# #Update Unit information res = ATC.getUnitInfo() # Start timeout timer timerB = timers.timer(0) timerB.start(int(myApp.INTERVAL)) SwitchPos = 'Open' #Default State for Switch IgnPos = 'Inactive' #Default State for Switch FirstTimeThrough = 'TRUE' #Initialize flag for the first time running the connection/loop SENDSTRING = [] #Initialize the string list being sent to the server StringCount = 0 # Loop forever, without this loop the script would run once and exit script mode. On reboot or power-on the script would run once more while (1): while (1): MOD.watchdogReset() #Update NMEA Data #The following are available through the included GPS module: #GPS.getActualPosition(), returns all fields like AT$GPSACP would #GPS.getLastGGA() #GPS.getLastGLL() #GPS.getLastGSA() #GPS.getLastGSV() #GPS.getLastRMC() #GPS.getLastVTG() #GPS.getPosition(), this gives LAT/LONG in numeric format #For the purposes of this demo, RMC will be used #The returned value gives a \r\n at the end so we must strip it for proper usage. GPSPositionTemp = '' GPSPositionTemp = GPS.getLastRMC() GPSPositionTemp = GPSPositionTemp.rstrip() #Update switch and ignition information #We simply clear after the report is sent, so by default it's sent as Open/Inactive until it's read as the opposite. #We're polling the MCU signals and then signaling back "we got the information" so we only read once, giving us one or both events to report # 0: Pass, Switch is triggered # 1: Pass, Ignition is triggered # 2: Pass, BOTH are triggered # -1: Exception # -2: Pass, Neither is triggered EventCheck = JANUS_IO.SW_IGN_Status() if (EventCheck == 0): #Switch has been triggered SwitchPos = 'Closed' #JANUS_SER.sendUART("SwitchPos : " + SwitchPos + "\r\n") elif (EventCheck == 1): #Ignition has been triggered IgnPos = 'Active' #JANUS_SER.sendUART("IgnPos : " + IgnPos + "\r\n") elif (EventCheck == 2): #Both have been triggered SwitchPos = 'Closed' IgnPos = 'Active' #JANUS_SER.sendUART("IgnPos : " + IgnPos + "\r\n") #JANUS_SER.sendUART("SwitchPos : " + SwitchPos + "\r\n") if (myApp.SMS_ENABLED == 'TRUE'): res = JANUS_SMS.CheckNewSMS() #If a new SMS is found and is valid, pass it to the command logic if (res != '0'): #We have received a new SMS, let's find what it wants us to do. #JANUS_SER.sendUART("SMS Data : " + str(res) + "\r\n") res = JANUS_SMS.SMSCommand(str(res)) # 0: Pass, action carried out and SMS sent back # -1: Exception # -2: Pass, Unrecognized change command or AT command received though # -3: Unrecognized SMS # -4: Error sending an SMS to the originating P/N if (res == -1): return #If the STAT LED was updated via SMS, let's adjust it res = JANUS_IO.Cellular_LED(myApp.SLED) #AUTO ON Run time Change. #Read current Auto-On status, 1 is active, 0 is inactive. res = JANUS_IO.AutoONControl('READ', myApp.AUTOON) #The below will be ignored if there is no change #If Auto-on is OFF and we want it ON, set it. if (res == 0 and myApp.AUTOON == 'ON'): res = JANUS_IO.AutoONControl('SET', myApp.AUTOON) if (res == -1): return #Errored out elif (res == -2): JANUS_SER.sendUART("Timed out while waiting for MCU response. \r\n") elif (res == 1): JANUS_SER.sendUART("Auto ON Enabled. \r\n") #If Auto-on is ON and we want it OFF, set it. if (res == 1 and myApp.AUTOON == 'OFF'): res = JANUS_IO.AutoONControl('SET', myApp.AUTOON) if (res == -1): return #Errored out elif (res == -2): JANUS_SER.sendUART("Timed out while waiting for MCU response. \r\n") elif (res == 0): JANUS_SER.sendUART("Auto ON Disabled. \r\n") elif (res == '-1'): #Exception return #If interval timer expires then send packet to server if (timerB.isexpired() or FirstTimeThrough == 'TRUE'): #The first time we drop into this loop we want to send data immediately, after that it's timer based sends. FirstTimeThrough = 'FALSE' #Disable the flag ####################### ##BEGIN BUILDING STRING #If we were woken up by one of the inputs, add it to the string to be sent #This section can be used/altered to perhaps only display the wake up event for a certain amount of sends. if (WakeupCause != ''): WakeupString = WakeupCause #JANUS_SER.sendUART("Wake up Event : " + WakeupCause + "\r\n") #res = GPRS.send_CM("Wake up Event : " + WakeupCause + "\r\n",1,10) #WakeupCause = '' #Clear the cause so it only gets reported the first time else: WakeupString = '' #Build String to send to customer server, adjusts depending on what we want reported. Can only be one of these. #CW Google Earth format #STA = NMEA + ',' + IMEI + ',' + String1 + ',' + String2 + ',' + String3 #Strings 1/2/3 should remain in all sentences sent, but become null ('') when not being sent. #The Strings follow a standard display format for the demo, so only send the actual information based on this format: #String 1 will display in the Demo as "Switch" #String 2 will display in the Demo as "Ignition" #String 3 will display in the Demo as "Wake up Event" if (myApp.NOSWITCH == 'TRUE' and myApp.IGNITION == 'TRUE'): STA = GPSPositionTemp + ',' + ATC.properties.IMEI + ',' + SwitchPos + ',' + IgnPos + ',' + WakeupString elif (myApp.NOSWITCH == 'TRUE' and myApp.IGNITION == 'FALSE'): STA = GPSPositionTemp + ',' + ATC.properties.IMEI + ',' + SwitchPos + ',' + "" + ',' + WakeupString elif (myApp.NOSWITCH == 'FALSE' and myApp.IGNITION == 'TRUE'): STA = GPSPositionTemp + ',' + ATC.properties.IMEI + ',' + "" + ',' + IgnPos + ',' + WakeupString elif (myApp.NOSWITCH == 'FALSE' and myApp.IGNITION == 'FALSE'): STA = GPSPositionTemp + ',' + ATC.properties.IMEI + ',' + "" + ',' + "" + ',' + WakeupString #Concatenate string, this allows store and forward during disconnects. #STA is refreshed every time through, SENDSTRING is only cleared after a successful send #Let's say 100B per string #Max string length is 16kB, giving us (safely) 100 data points to store. #This can be improved upon by utilizing a list, since each element in a list is capable of 16kB #with a possible 4000 elements (keeping in mind overall memory limits) if (StringCount < 100): SENDSTRING.append(STA) StringCount = StringCount+1 else: JANUS_SER.sendUART("Store and forward limit reached (100). \r\n\r\n") ####################### ##END BUILDING STRING ############################################################### ##### Socket Open Check #If socket closed, open it DCD = MDM.getDCD() #Check for a valid SS too res = ATC.sendAtCmd('AT#SS',ATC.properties.CMD_TERMINATOR,0,20) #If there is not a valid DCD OR the socket status shows that there is no socket open. #We check for both because DCD seems to get stuck on 1 under certain conditions and we cannot set it, yet SS works fine. if (DCD == 0 or res == "#SS: 1,0"): JANUS_SER.sendUART("Opening socket to server: " + myApp.IP + ":" + myApp.PORT + "\r\n") #Connect to customer's server res = GPRS.openSocket(myApp.IP,myApp.PORT,1,myApp.USERNAME,myApp.PASSWORD,myApp.PROTOCOL,1) if (res != 0): JANUS_SER.sendUART("Connection failed to open. \r\n") #Turn OFF the LED permanently until we have a valid connection res = JANUS_IO.GPS_LED('OFF', myApp.ULED) elif (res == 0): JANUS_SER.sendUART("Socket opened successfully.\r\n") #Turn ON the LED to show we have a valid connection res = JANUS_IO.GPS_LED('ON', myApp.ULED) JANUS_SER.sendUART("Polling GPS receiver for current location every " + myApp.INTERVAL + " second(s)\r\n") #Do not return, end of this loop will handle the service checking ############################################################### ##### Socket Open Check try: #If socket open upload data DCD = MDM.getDCD() #Check for a valid SS too res = ATC.sendAtCmd('AT#SS',ATC.properties.CMD_TERMINATOR,0,20) #If there is a valid DCD AND the socket status shows that there is a valid socket connection too. #We check for both because DCD seems to get stuck on 1 under certain conditions and we cannot set it, yet SS works fine. if (DCD == 1 and res != "#SS: 1,0"): #Update the GPS LED. This will turn the LED on/off during run time if it has been updated via SMS. #Defaulted to ON res = JANUS_IO.GPS_LED('ON', myApp.ULED) #####Placeholder for built string OLD spot #Strip the last entry of the pipe #Pop the last item out, remove the last byte (the pipe) then append it back to the list. #This covers single sends and block sends ## LastItem = SENDSTRING.pop(StringCount-1) ## ItemLength = len(LastItem) ## LastItem = LastItem[0:ItemLength-1] ## SENDSTRING.append(LastItem) JANUS_SER.sendUART("Sending data: \r\n") res = 0 x = 0 while (res == 0 and x < StringCount): #Send Data JANUS_SER.sendUART(str(SENDSTRING[x]) + "\r\n") res = GPRS.send_CM(SENDSTRING[x],1,10) x = x+1 if (res == 1): JANUS_SER.sendUART("\r\n\r\nData Empty, Error receiving info from GPS module\r\n") return if (res == -2): JANUS_SER.sendUART("\r\n\r\nTimed out while sending data, checking socket connection\r\n") #Do not return, drop to service checks #Add the pipe to the end again since this got disconnected mid-send procedure and will become a store and forward send. ## LastItem = SENDSTRING.pop(StringCount-1) ## LastItem = LastItem + '|' ## SENDSTRING.append(LastItem) else: JANUS_SER.sendUART("\r\n\r\nData Sent Successfully.\r\n\r\n") #Blink OFF the LED to indicate data was sent res = JANUS_IO.GPS_LED('OFF', myApp.ULED) res = JANUS_IO.GPS_LED('ON', myApp.ULED) if (IgnPos == 'Inactive' and myApp.AUTOON == 'OFF' and myApp.IGNITIONFOLLOW == 'TRUE'): #Special Case, auto-on is not active and we want to only be active while the ignition is active. #Inigition has dropped, we've sent the last data packet, now shut the unit down res = ATC.sendAtCmd('AT#SHDN',ATC.properties.CMD_TERMINATOR,0,20) #Put the Switch and Ignition I/O back to default, clear the list and counter SwitchPos = 'Open' IgnPos = 'Inactive' SENDSTRING = [] StringCount = 0 #Exit data mode #DEBUG.sendMsg('Exiting data mode\r\n') #res = ATC.exitSocketDataMode() #Close Socket #Pass in: sockNum #res = ATC.closeSocket('1') #DEBUG.sendMsg('Connection closed\r\n') break else: JANUS_SER.sendUART("\r\nConnection not available, checking status.\r\n") #Wait until module is registered to GSM Network #res = NETWORK.isGsmRegistered(180) #Wait 180 seconds for module to obtain GSM registration #if (res == -1): # ATC.reboot() #Wait until module is attached to GPRS #res = NETWORK.isGprsAttached(180) #Wait 180 seconds for module to obtain GPRS Attachment #if (res == -1): # ATC.reboot() #What is the signal strength? res = ATC.sendAtCmd('AT+CSQ',ATC.properties.CMD_TERMINATOR,0,5) JANUS_SER.sendUART("Signal Strength (AT+CSQ): " + res + "\r\n") #Still registered? res = ATC.sendAtCmd('AT+CREG?',ATC.properties.CMD_TERMINATOR,0,5) JANUS_SER.sendUART("Registration Check (AT+CREG?): " + res + "\r\n") #GPRS Available? res = ATC.sendAtCmd('AT+CGREG?',ATC.properties.CMD_TERMINATOR,0,5) JANUS_SER.sendUART("GPRS Availability (AT+CGREG?): " + res + "\r\n") #Is a PDP context activated? res = ATC.sendAtCmd('AT#SGACT?',ATC.properties.CMD_TERMINATOR,0,20) JANUS_SER.sendUART("PDP Context status (AT#SGACT?): " + res + "\r\n\r\n") break except: JANUS_SER.sendUART("Script encountered an exception while uploading data to server\r\n") JANUS_SER.sendUART("Exception Type: " + str(sys.exc_type) + "\r\n") JANUS_SER.sendUART("MODULE -> LobosTrack\r\n") break ## Re-Start timeout timer timerB = timers.timer(0) timerB.start(int(myApp.INTERVAL)) #DEBUG.CLS() #Clear screen command for VT100 terminals except: print "Script encountered an exception" print "Exception Type: " + str(sys.exc_type) print "MODULE -> TerminusS2E" return