def write(self): f = open("arquivo" +'.txt', 'a') am = tos.AM() while True: p = am.read() f.write(str(p))
def main(): tx_pckt = tos.Packet([('data', 'int', 2)], []) AM_ID = 6 serial_port = tos.Serial("/dev/ttyUSB0", 115200) am = tos.AM(serial_port) #for i in xrange(10): while 1: raw_input("Press enter to send serial packet\n") am.write(tx_pckt, AM_ID)
def __init__(self, port, baudrate, am_channel): self.rx_queue = Queue.Queue() self.tx_queue = Queue.Queue() self.port = port self.baudrate = baudrate self.am_channel = am_channel try: self.serial = tos.Serial(self.port, self.baudrate) self.am = tos.AM(self.serial) except: print('Error: ', sys.exc_info()[1]) sys.exit(1) rcv_thread = threading.Thread(target=receiver, args=(self.rx_queue,)) rcv_thread.setDaemon(True) rcv_thread.start() snd_thread = threading.Thread(target=transmitter, args=(self.tx_queue,)) snd_thread.setDaemon(True) snd_thread.start()
def main(args): global logger if '-h' in args or len(args) < 4: ''' If you are wondering where is the first parameter (e.g. serial@/dev/ttyUSB0:57600) parsed, it is inside tos (when you import it). ''' print "Usage: python %s serial@/dev/ttyUSB1:57600 {message_type (e.g. 0xee)} {mote_type (micaz/iris)} [ignore list]" % ( args[0]) sys.exit() global AM_ID AM_ID = int(args[2], 16) global mote_type mote_type = args[3].strip() if not mote_type in RECOGNIZED_MOTES: print 'Unrecognized mote "%s"' % mote_type exit() motes_to_ignore = [] if len(args) >= 5: motes_to_ignore = map(int, args[4].split(',')) exp_start = datetime.datetime.now().strftime("%d_%m_%y_%Hh%Mm%Ss") file_samples = open("Output/samples_%s.agg" % exp_start, "w") logger = create_logger("Output/Log/log_%s.txt" % (exp_start)) ''' Contains a list of every mote. ''' motes = set() try: am = tos.AM() logger.warning("Starting...") while True: p = am.read() # get a packet if p and p.type == AM_ID: # it is a MultihopSensing packet now = time.time() ctp = CtpData(p.data) samples = Samples(ctp.data) if samples.source not in motes_to_ignore: if samples.readingTemperature != 0: save_reading(now, samples, file_samples) # print_ctp_header_info(ctp) ''' Detect new motes as they appear on the network ''' last_len = len(motes) motes.add(samples.source) curr_len = len(motes) if last_len < curr_len: logger.warning("Mote %d entered the network!" % samples.source) else: if p and p.type == CTPDebugMsg.AM_ID: msg = CTPDebugMsg(p.data) msg.process() else: logger.warning("Skipping packet %s" % p) except KeyboardInterrupt: # print_database() #to test persistence in to database logger.warning("Aborting...") except SystemExit: pass # nothing to say about system exit except: logger.exception("An unhandled exception occurred.") finally: file_samples.close() logger.warning("Done...")
class OscilloscopeMsg(tos.Packet): def __init__(self, packet=None): tos.Packet.__init__(self, [ ('srcID', 'int', 2), ('seqNo', 'int', 2), ('ch1', 'int', 2), ('ch2', 'int', 2), ], packet) if '-h' in sys.argv: print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600" sys.exit() am = tos.AM() while True: p = am.read() msg = OscilloscopeMsg(p.data) print p ####### ZLeak Sensor Logic ############ print "ID:", msg.srcID, "seqNo:", msg.seqNo, "ch1:", msg.ch1, "ch2:", msg.ch2 if (msg.ch1 > 4000): val1 = 0 else: val1 = 1 print "CH1 LEAK!!!" if (msg.ch2 > 4000): val2 = 0
events = [] arial = pygame.font.SysFont("arial", 12) defaultLocs = {} with open("location.cfg") as f: mapImage = loadMapImage(f.readline()[:-1]) for line in f: line = line.split(":") sensorId = int(line[0].strip()) locs = line[1].split(",") sensorPos = (int(locs[0].strip()), int(locs[1].strip())) defaultLocs[sensorId] = sensorPos source = None handler = None if not args.d: source = tos.getSource("serial@/dev/ttyUSB1:57600") handler = PacketHandler(sensors, tos.AM(source), defaultLocs) handler.start() screen.fill((255, 255, 255)) def drawText(surface, text, location): textSur = arial.render(str(text), True, (0, 0, 0)) surface.blit(textSur, location) step = 0 graphRect = pygame.Rect(0, 0, 400, 500) sidebarRect = pygame.Rect(400, 0, 200, 500) mapRect = pygame.Rect(600, 0, 400, 500)
except ImportError: import posix, os sys.path = [ os.path.join(posix.environ['TOSROOT'], 'support', 'sdk', 'python') ] + sys.path import tos if len(sys.argv) < 2: print "no device specified" print "example:" print " syncedRadioStats.py /dev/ttyUSB5" else: try: # ser = tos.Serial(sys.argv[1], 115200, flush=True, debug=False) ser = tos.Serial(sys.argv[1], 115200) am = tos.AM(ser) except: print "ERROR: Unable to initialize serial port connection to", sys.argv[ 1] sys.exit(-1) AM_HOST_CONTROLLED_TIMING_MSG = 0x7F wpacket = tos.Packet([('msg', 'int', 1)]) #1 byte integer (i.e. uint8_t) wpacket.msg = ord('s') am.write(wpacket, AM_HOST_CONTROLLED_TIMING_MSG) num_received = [] senders_seen = [] num_missed = [] last_count = [] packet_size = []
#!/usr/bin/env python import sys import tos if len(sys.argv) < 3: print "Usage:", sys.argv[0], "/dev/ttyUSB0 115200" sys.exit() s = tos.Serial(sys.argv[1], int(sys.argv[2]), debug=False) am = tos.AM(s) while True: p = am.read()
#!/usr/bin/env python import sys import tos #application defined messages tx_pckt = tos.Packet([('type', 'int', 1)],[]) AM_BLINKTORADIO=6 serial_port = tos.Serial("/dev/ttyUSB0",115200) am = tos.AM(serial_port) for i in xrange(10): am.write(tx_pckt,AM_BLINKTORADIO) pckt = am.read(timeout=0.5) if pckt is not None: print pckt.type print pckt.data
def start_serial(): am = tos.AM() while True: p = am.read() try: while True: data = control_queue.get_nowait() msg = ControlMsg() msg.frequency = data[0] am.write(msg, AM_CONTROLMSG) print('Sent: ' + str(msg)) except Empty: pass if p and p.type == AM_RECORDMSG: msg = RecordMsg(p.data) with open('result.txt', 'a') as f: f.write('\t'.join([ str(i) for i in [ msg.nodeid, msg.count, msg.temperature, msg.humidity, msg.light, msg.time ] ]) + '\n') print('Received: ' + str(msg)) nodes_data_lock.acquire() data = nodes_data.get(msg.nodeid) now = time.time() if data is None: temperature = -39.6 + 0.01 * msg.temperature temperature = (temperature - 32) / 1.8 humidity = -4 + 0.0405 * msg.humidity + (-2.8 * 1e-6) * ( msg.humidity**2) data = { 'count': msg.count, 'time_delta': now - msg.time / 1e3, 'duplicated': 0, 'lost': 0, 'reset': 0, 'time_data': [datetime.datetime.fromtimestamp(now)], 'temperature_data': [temperature], 'humidity_data': [humidity], 'light_data': [0.625 * 10 * msg.light * 1.5 / 4.096], 'sample_rate': None, 'time_sync': False } nodes_data[msg.nodeid] = data else: ahead = (msg.count + 0x10000 - data['count']) % 0x10000 behind = (data['count'] + 0x10000 - msg.count) % 0x10000 if 0 <= behind < PACKET_DUPLICATED_THRESHOLD: data['duplicated'] += 1 else: if 0 < ahead < PACKET_LOST_THRESHOLD: data['lost'] += ahead - 1 if data['time_sync']: print('sync') data['time_delta'] = now - msg.time / 1e3 data['time_data'].append( datetime.datetime.fromtimestamp(now)) data['time_sync'] = False else: data['time_data'].append( datetime.datetime.fromtimestamp( data['time_delta'] + msg.time / 1e3)) sample_rate = data['sample_rate'] new_sample_rate = ( data['time_data'][-1] - data['time_data'][-2]).total_seconds() / ahead if sample_rate is None: data['sample_rate'] = new_sample_rate else: data[ 'sample_rate'] = new_sample_rate * MOVING_AVERAGE_R + sample_rate * ( 1 - MOVING_AVERAGE_R) else: data['reset'] += 1 data['time_delta'] = now - msg.time / 1e3 data['time_data'].append( datetime.datetime.fromtimestamp(now)) data['sample_rate'] = None data['count'] = msg.count temperature = -39.6 + 0.01 * msg.temperature temperature = (temperature - 32) / 1.8 humidity = -4 + 0.0405 * msg.humidity + (-2.8 * 1e-6) * ( msg.humidity**2) data['temperature_data'].append(temperature) data['humidity_data'].append(humidity) data['light_data'].append(0.625 * 10 * msg.light * 1.5 / 4.096) nodes_data_lock.release()
def main(args): global logger if '-h' in args or len(args) < 4: ''' If you are wondering where is the first parameter (e.g. serial@/dev/ttyUSB0:57600) parsed, it is inside tos (when you import it). ''' print "Usage: python %s serial@/dev/ttyUSB1:57600 {message_type (e.g. 0x95)} {mote_type (micaz/iris)} [ignore list]" % ( args[0]) sys.exit() MultihopSensingMsg.AM_ID = int(args[2], 16) mote_type = args[3].strip() if not mote_type in RECOGNIZED_MOTES: print 'Unrecognized mote "%s"' % mote_type exit() motes_to_ignore = [] if len(args) >= 5: motes_to_ignore = map(int, args[4].split(',')) exp_start = datetime.datetime.now().strftime("%d_%m_%y_%Hh%Mm%Ss") f_temp = open("../output/temps_%s.txt" % exp_start, "w") f_batt = open("../output/batts_%s.txt" % exp_start, "w") f_light = open("../output/light_%s.txt" % exp_start, "w") logger = create_logger("../output/log/log_%s.txt" % (exp_start)) ''' Contains a list of every mote. ''' motes = set() try: am = tos.AM() logger.warning("Starting...") while True: p = am.read() # get a packet if p and p.type == MultihopSensingMsg.AM_ID: # it is a MultihopSensing packet now = time.time() msg = new_multihopsensing_packet(p.data, mote_type) if msg and msg.id not in motes_to_ignore: value = msg.get_value() save_reading(value, msg, now, f_temp, f_batt, f_light) ''' Detect new motes as they appear on the network ''' last_len = len(motes) motes.add(msg.id) curr_len = len(motes) if last_len < curr_len: logger.warning("Mote %d entered the network!" % msg.id) else: if p and p.type == CTPDebugMsg.AM_ID: msg = CTPDebugMsg(p.data) msg.process() else: logger.warning("Skipping packet %s" % p) except KeyboardInterrupt: logger.warning("Aborting...") except SystemExit: pass # nothing to say about system exit except: logger.exception("An unhandled exception occurred.") finally: if f_temp: f_temp.close() if f_batt: f_batt.close() if f_light: f_light.close() logger.warning("Done...")