Ejemplo n.º 1
0
def main(name):
   global socket_map, gps_lock, font, caution_written
   socket_map = generate_map(name)
   gps_lock = Lock()

   t1 = Thread(target = cpuavg)
   t1.daemon = True
   t1.start()

   t2 = Thread(target = pmreader)
   t2.daemon = True
   t2.start()

   t3 = Thread(target = gps)
   t3.daemon = True
   t3.start()

   socket = generate_map('aircomm_app')['out']
   packer = Packer(use_single_float = True)
   while True:
      try:
         data = [BCAST_NOFW, HEARTBEAT, int(voltage * 10), int(current * 10), int(load), mem_used(), critical]
         with gps_lock:
            try:
               if gps_data.fix >= 2:
                  data += [gps_data.lon, gps_data.lat]
            except:
               pass
         socket.send(packer.pack(data))
      except Exception, e:
         pass
      sleep(1.0)
Ejemplo n.º 2
0
def main(name):
   global socket_map, font, caution_written
   socket_map = generate_map(name)
   t1 = Thread(target = cpu_reader)
   t1.daemon = True
   t1.start()

   t2 = Thread(target = pm_reader)
   t2.daemon = True
   t2.start()

   t3 = Thread(target = gps_reader)
   t3.daemon = True
   t3.start()

   socket = generate_map('aircomm_app')['aircomm_in']
   while True:
      try:
         data = [BCAST_NOFW, HEARTBEAT, int(voltage * 10), int(current * 10), int(load), mem_used(), critical]
         try:
            data += [gps[LAT], gps[LON]]
         except:
            pass
         socket.send(dumps(data))
      except Exception, e:
         print e
      sleep(1.0)
Ejemplo n.º 3
0
def main(name):
   global socket_map, font, caution_written
   socket_map = generate_map(name)
   t1 = Thread(target = cpu_reader)
   t1.daemon = True
   t1.start()

   t2 = Thread(target = pm_reader)
   t2.daemon = True
   t2.start()

   t3 = Thread(target = gps_reader)
   t3.daemon = True
   t3.start()

   socket = generate_map('aircomm_app')['aircomm_in']
   while True:
      try:
         data = [BCAST_NOFW, HEARTBEAT, int(voltage * 10), int(current * 10), int(load), mem_used(), critical]
         try:
            data += [gps[LAT], gps[LON]]
         except:
            pass
         socket.send(dumps(data))
      except Exception, e:
         print e
      sleep(1.0)
Ejemplo n.º 4
0
def optimize(rate, samples, prefix, names, mse_indices):
    gates = generate_map('optimizer')
    opcd = OPCD_Interface(gates['opcd_ctrl'])
    bb = gates['blackbox']
    vec_best = [opcd.get(prefix + n) for n in names]
    vec = vec_best
    mse_min = sys.float_info.max
    best_log = []
    try:
        for _ in range(5):
            vec = map(lambda x: x * uniform(1.0 - rate, 1.0 + rate), vec)
            # send new params to opcd:
            for i, n in zip(range(len(names)), names):
                opcd.set(prefix + n, vec[i])
            # read data from autopilot and compute fitness:
            mse = 0.0
            for _ in range(samples):
                array = loads(bb.recv())
                for i in mse_indices:
                    mse += array[i]**2
            mse /= samples
            # evaluate mse:
            if mse < mse_min:
                best_log.append(mse)
                opcd.persist()
                mse_min = mse
                vec_best = copy(vec)
            else:
                # we did not improve;
                # use best vector as search starting point
                vec = copy(vec_best)
    except:
        for i, n in zip(range(len(names)), names):
            opcd.set(prefix + n, vec_best[i])
    return best_log
Ejemplo n.º 5
0
def main(name):
   sm = generate_map(name)
   opcd = OPCD_Interface(sm['opcd_ctrl'], name)
   global THIS_SYS_ID
   THIS_SYS_ID = opcd.get('id')
   key = opcd.get('psk')
   crypt.init(key)
   mhist = MessageHistory(60)

   out_socket = sm['out']
   in_socket = sm['in']

   aci = Interface('/dev/ttyACM0')
   acr = ACIReader(aci, out_socket, mhist)
   acr.start()

   # read from SCL in socket and send data via NRF
   while True:
      data = loads(in_socket.recv())
      if len(data) == 2:
         msg = [data[0], THIS_SYS_ID, data[1]]
      elif len(data) > 2:
         msg = [data[0], THIS_SYS_ID] + data[1:]
      else:
         continue
      crypt_data = crypt.encrypt(dumps(msg))
      mhist.append(crypt_data)
      aci.send(crypt_data)
Ejemplo n.º 6
0
def main(name):
    context = zmq.Context()
    zmq_socket = context.socket(zmq.PUB)
    zmq_socket.bind('tcp://*:5555')
    socket = generate_map(name)['blackbox']
    prefix = user_data_dir + sep + 'log' + sep
    try:
        now = datetime.today().isoformat().replace(':', '')
        symlink_file = prefix + 'blackbox_last.msgpack'
        try:
            unlink(symlink_file)
        except:
            pass
        if len(argv) > 1:
            new_file = prefix + 'blackbox_%s_%s.msgpack' % (now, argv[1])
        else:
            new_file = prefix + 'blackbox_%s.msgpack' % now
        symlink(new_file, symlink_file)
        f = open(new_file, "wb")
        rt = RateTimer(20)
        while True:
            data = socket.recv()
            f.write(data)
            if rt.expired():
                zmq_socket.send(data)
    finally:
        try:
            f.close()
        except:
            pass
Ejemplo n.º 7
0
   def __init__(self, name):
      # set-up logger:
      logfile = user_data_dir() + sep + 'PowerMan.log'
      log_config(filename = logfile, level = DEBUG,
                 format = '%(asctime)s - %(levelname)s: %(message)s')
      # initialized and load config:
      log_info('powerman starting up')
      map = generate_map(name)
      self.ctrl_socket = map['ctrl']
      self.monitor_socket = map['mon']
      self.opcd = OPCD_Interface(map['opcd_ctrl'], 'powerman')
      bus = SMBus(self.opcd.get('gpio_i2c_bus'))
      self.gpio_mosfet = GPIO_Bank(bus, self.opcd.get('gpio_i2c_address'))
      self.power_pin = self.opcd.get('gpio_power_pin')
      self.cells = self.opcd.get('battery_cells')
      self.low_cell_voltage = self.opcd.get('battery_low_cell_voltage')
      self.capacity = self.opcd.get('battery_capacity')
      self.low_battery_voltage = self.cells * self.low_cell_voltage
      self.critical = False
      self.gpio_mosfet.write()
      self.warning_started = False

      # start threads:
      self.standing = True
      self.adc_thread = start_daemon_thread(self.adc_reader)
      self.emitter_thread = start_daemon_thread(self.power_state_emitter)
      self.request_thread = start_daemon_thread(self.request_handler)
      log_info('powerman running')
Ejemplo n.º 8
0
def main(name):
   context = zmq.Context()
   zmq_socket = context.socket(zmq.PUB)
   zmq_socket.bind('tcp://*:5555')
   socket = generate_map(name)['blackbox']
   prefix = user_data_dir + sep + 'log' + sep
   try:
      now = datetime.today().isoformat().replace(':', '')
      symlink_file = prefix + 'blackbox_last.msgpack'
      try:
         unlink(symlink_file)
      except:
         pass
      if len(argv) > 1:
         new_file = prefix + 'blackbox_%s_%s.msgpack' % (now, argv[1])
      else:
         new_file = prefix + 'blackbox_%s.msgpack' % now
      symlink(new_file, symlink_file)
      f = open(new_file, "wb")
      rt = RateTimer(20)
      while True:
         data = socket.recv()
         f.write(data)
         if rt.expired():
            zmq_socket.send(data)
   finally:
      try:
         f.close()
      except:
         pass
Ejemplo n.º 9
0
def main(name):
   map = generate_map(name)
   socket_in = map['log_data']
   socket_out = map['log_data_pub']
   while True:
      data = socket_in.recv()
      socket_out.send(data)
Ejemplo n.º 10
0
def main(name):
   map = generate_map(name)
   context = Context()
   pub_socket = context.socket(PUB)
   pub_socket.bind('tcp://0.0.0.0:20000')
   map['pub_server'] = pub_socket
   rep_socket = context.socket(REP)
   rep_socket.bind('tcp://0.0.0.0:20001')
   map['rep_server'] = rep_socket
   manager = MissionManager()
   rep_socket = map['rep_server']
   manager.start_mission(LocMission(map, None))
   return
   while True:
      req = MissionMessage()
      req.ParseFromString(rep_socket.recv())
      if req.type == 6:
         req.type = 7
         try:
            if req.missionType == MissionMessage.CONNECTION:
               manager.start_mission(PlaceMission(map, (0.0, 0.0), req))
            elif req.missionType == MissionMessage.LOCALIZATION:
               manager.start_mission(LocMission(map, req))
            else:
               raise ValueError('unknown mission type')
            req.status = MissionMessage.ACTIVE
         except RuntimeError:
            req.status = MissionMessage.REJECTED
         rep_socket.send(req.SerializeToString())
Ejemplo n.º 11
0
def main(name):
   sm = generate_map(name)
   
   opcd = OPCD_Interface(sm['opcd_ctrl'])
   platform = opcd.get('platform')
   device = opcd.get(platform + '.nrf_serial')
   
   global THIS_SYS_ID
   THIS_SYS_ID = opcd.get('aircomm.id')
   key = opcd.get('aircomm.psk')
   crypt.init(key)
   mhist = MessageHistory(60)

   out_socket = sm['aircomm_out']
   in_socket = sm['aircomm_in']

   aci = Interface(device)
   acr = ACIReader(aci, out_socket, mhist)
   acr.start()

   # read from SCL in socket and send data via NRF
   while True:
      data = loads(in_socket.recv())
      if len(data) == 2:
         msg = [data[0], THIS_SYS_ID, data[1]]
      elif len(data) > 2:
         msg = [data[0], THIS_SYS_ID] + data[1:]
      else:
         continue
      crypt_data = crypt.encrypt(dumps(msg))
      mhist.append(crypt_data)
      aci.send(crypt_data)
Ejemplo n.º 12
0
def main(name):
   global socket_map
   socket_map = generate_map(name)

   t2 = Thread(target = pm_reader)
   t2.daemon = True
   t2.start()

   t3 = Thread(target = gps_reader)
   t3.daemon = True
   t3.start()
   
   ser = serialport_t()
   CSTOPB = 0000100
   serial_open(ser, "/dev/ttyO0", 100000, os.O_WRONLY, CSTOPB)
   while True:
      try:
         serial_write_str(ser, "H %d %d\n" % (int(current * 100), int(voltage * 100)))
         if fix(gps) >= 2:
            serial_write_str(ser, "G2 %d %d %d\n" % (int(gps[LAT] * 10000000.0), int(gps[LON] * 10000000.0), int(gps[SPEED] * 10.0)))
         if fix(gps) == 3:
            serial_write_str(ser, "G3 %d %d\n" % (int(gps[ALT] * 1000), 0))
      except:
         pass
      sleep(0.1)
Ejemplo n.º 13
0
    def __init__(self, name):
        map = generate_map(name)
        self.ctrl_socket = map['ctrl']
        self.monitor_socket = map['mon']
        self.opcd = OPCD_Interface(map['opcd_ctrl'], 'powerman')
        bus = SMBus(self.opcd.get('gpio_i2c_bus'))
        self.gpio_mosfet = GPIO_Bank(bus, self.opcd.get('gpio_i2c_address'))
        self.power_pin = self.opcd.get('gpio_power_pin')
        self.cells = self.opcd.get('battery_cells')
        self.low_cell_voltage_idle = self.opcd.get(
            'battery_low_cell_voltage_idle')
        self.low_cell_voltage_load = self.opcd.get(
            'battery_low_cell_voltage_load')
        self.battery_current_treshold = self.opcd.get(
            'battery_current_treshold')
        self.capacity = self.opcd.get('battery_capacity')
        self.low_battery_voltage_idle = self.cells * self.low_cell_voltage_idle
        self.low_battery_voltage_load = self.cells * self.low_cell_voltage_load
        self.critical = False
        #self.gpio_mosfet.write()
        self.warning_started = False

        # start threads:
        self.standing = True
        self.adc_thread = start_daemon_thread(self.adc_reader)
        self.request_thread = start_daemon_thread(self.request_handler)
Ejemplo n.º 14
0
def main(name):
   global data
   print 'initializing data'
   for i in range(36):
      for j in range(72):
         for k in range(72):
            data[i, j, k, 0] = 0
            data[i, j, k, 1] = 0
            data[i, j, k, 2] = 9.806650
   print 'loading data'
   for line in file('/root/.PenguPilot/config/gvfa_state.txt'):
      n, e, u = map(float, line.split(' ')[3:6])
      i, j, k = map(int, line.split(' ')[0:3])
      data[i, j, k, 0] = n
      data[i, j, k, 1] = e
      data[i, j, k, 2] = u
   
   print 'starting'
   socket = generate_map(name)['gvfa']
   c = 0
   while True:
      n, e, u, i, j, k = loads(socket.recv())
      data[i, j, k, 0] = n
      data[i, j, k, 1] = e
      data[i, j, k, 2] = u
      if (c % 5000) == 0 and not writing:
         t = Thread(target = write_file)
         t.start()
      c += 1
Ejemplo n.º 15
0
def main(name):
    socket = generate_map(name)['data']
    prefix = user_data_dir + sep + 'log' + sep
    try:
        now = datetime.today().isoformat().replace(':', '')
        symlink_file = prefix + 'blackbox_last.msgpack'
        try:
            unlink(symlink_file)
        except:
            pass
        if len(argv) > 1:
            new_file = prefix + 'blackbox_%s_%s.msgpack' % (now, argv[1])
        else:
            new_file = prefix + 'blackbox_%s.msgpack' % now
        symlink(new_file, symlink_file)
        f = open(new_file, "wb")
        while True:
            f.write(socket.recv())
            #f.flush()
            #fsync(f.fileno())
    finally:
        try:
            f.close()
        except:
            pass
Ejemplo n.º 16
0
    def tuneRadio(self, freq):
        print "Tune Radio"
        map = scl.generate_map("pySysMoCo")
        radioconfigcontrol = map["radioconfcontrol"]

        #Create request for radio reconfiguration
        request = radioconfig_pb2.RadioConfigControl()
        request.type = radioconfig_pb2.REQUEST
        request.command = radioconfig_pb2.SET_RADIO_CONFIG

        # add engine and component to message
        engine = request.radioconf.engines.add()
        engine.name = str(self.engineName)
        component = engine.components.add()
        component.name = str(self.componentName)
        
        # add parameters
        txfreq = component.parameters.add()
        txfreq.name = str(self.parameterName)
        txfreq.value = str(freq)
        
        #send request
        string = request.SerializeToString()
        radioconfigcontrol.send(string)
        print "Reconfig request sent, waiting for reply .."
        #wait for reply, fixme: check result
        string = radioconfigcontrol.recv()
        print "Got reply from radio"
Ejemplo n.º 17
0
def optimize(rate, samples, prefix, names, mse_indices):
   gates = generate_map('optimizer')
   opcd = OPCD_Interface(gates['opcd_ctrl'])
   bb = gates['blackbox']
   vec_best = [ opcd.get(prefix + n) for n in names]
   vec = vec_best
   mse_min = sys.float_info.max
   best_log = []
   try:
      for _ in range(5):
         vec = map(lambda x: x * uniform(1.0 - rate, 1.0 + rate), vec)
         # send new params to opcd:
         for i, n in zip(range(len(names)), names):
            opcd.set(prefix + n, vec[i])
         # read data from autopilot and compute fitness:
         mse = 0.0
         for _ in range(samples):
            array = loads(bb.recv())
            for i in mse_indices:
               mse += array[i] ** 2
         mse /= samples
         # evaluate mse:
         if mse < mse_min:
            best_log.append(mse)
            opcd.persist()
            mse_min = mse
            vec_best = copy(vec)
         else:
            # we did not improve;
            # use best vector as search starting point
            vec = copy(vec_best)
   except:
      for i, n in zip(range(len(names)), names):
         opcd.set(prefix + n, vec_best[i])
   return best_log
Ejemplo n.º 18
0
def main(name):
   sm = generate_map(name)
   
   opcd = OPCD_Interface(sm['opcd_ctrl'])
   platform = opcd.get('platform')
   device = opcd.get(platform + '.nrf_serial')
   
   global THIS_SYS_ID
   THIS_SYS_ID = opcd.get('aircomm.id')
   key = opcd.get('aircomm.psk')
   crypt.init(key)
   mhist = MessageHistory(60)

   out_socket = sm['aircomm_out']
   in_socket = sm['aircomm_in']

   aci = ZMQ_Interface()
   acr = ACIReader(aci, out_socket, mhist)
   acr.start()

   # read from SCL in socket and send data via NRF
   while True:
      data = loads(in_socket.recv())
      if len(data) == 2:
         msg = [data[0], THIS_SYS_ID, data[1]]
      elif len(data) > 2:
         msg = [data[0], THIS_SYS_ID] + data[1:]
      else:
         continue
      crypt_data = crypt.encrypt(dumps(msg))
      mhist.append(crypt_data)
      aci.send(crypt_data)
Ejemplo n.º 19
0
 def __init__(self, name):
    map = generate_map(name)
    self.ctrl_socket = map['opcd_ctrl']
    self.event_socket = map['opcd_event']
    logger_init('opcd', map['log_data'])
    self.conf = Config()
    self.map = {str: 'str_val', int: 'int_val', float: 'dbl_val', bool: 'bool_val'}
Ejemplo n.º 20
0
def main(name):
    map = generate_map(name)
    socket_in = map['log_data']
    socket_out = map['log_data_pub']
    while True:
        data = socket_in.recv()
        socket_out.send(data)
Ejemplo n.º 21
0
    def getRadio(self):

        map = scl.generate_map("pySysMoCo")
        radioconfigcontrol = map["radioconfcontrol"]

        #Create request for getting ratio
        request = radioconfig_pb2.RadioConfigControl()
        request.type = radioconfig_pb2.REQUEST
        request.command = radioconfig_pb2.GET_RADIO_CONFIG
        string = request.SerializeToString()
        radioconfigcontrol.send(string)

        #Create Reply
        reply = radioconfig_pb2.RadioConfigControl()
        string = radioconfigcontrol.recv()
        reply.ParseFromString(string)
        # set radioconfig for later reference
        self.radioConfig = reply.radioconf

        # FIXME: change to tree view and add engines too
        # update component list
        self.ui.componentList.clear()
        for i in self.radioConfig.engines:
            for k in i.components:
                self.ui.componentList.addItem(str(k.name))

        # make first item active
        self.ui.componentList.setCurrentItem(self.ui.componentList.item(0))
Ejemplo n.º 22
0
 def __init__(self, name):
    map = generate_map(name)
    self.ctrl_socket = map['opcd_ctrl']
    self.event_socket = map['opcd_event']
    logger_init('opcd', map['log_data'])
    self.conf = Config()
    self.map = {str: 'str_val', int: 'int_val', float: 'dbl_val', bool: 'bool_val'}
Ejemplo n.º 23
0
    def tuneRadio(self, freq):
        print "Tune Radio"
        map = scl.generate_map("pySysMoCo")
        radioconfigcontrol = map["radioconfcontrol"]

        #Create request for radio reconfiguration
        request = radioconfig_pb2.RadioConfigControl()
        request.type = radioconfig_pb2.REQUEST
        request.command = radioconfig_pb2.SET_RADIO_CONFIG

        # add engine and component to message
        engine = request.radioconf.engines.add()
        engine.name = str(self.engineName)
        component = engine.components.add()
        component.name = str(self.componentName)

        # add parameters
        txfreq = component.parameters.add()
        txfreq.name = str(self.parameterName)
        txfreq.value = str(freq)

        #send request
        string = request.SerializeToString()
        radioconfigcontrol.send(string)
        print "Reconfig request sent, waiting for reply .."
        #wait for reply, fixme: check result
        string = radioconfigcontrol.recv()
        print "Got reply from radio"
Ejemplo n.º 24
0
def main(name):
   socket = generate_map(name)['data']
   prefix = user_data_dir + sep + 'log' + sep
   try:
      now = datetime.today().isoformat().replace(':', '')
      symlink_file = prefix + 'blackbox_last.msgpack'
      try:
         unlink(symlink_file)
      except:
         pass
      if len(argv) > 1:
         new_file = prefix + 'blackbox_%s_%s.msgpack' % (now, argv[1])
      else:
         new_file = prefix + 'blackbox_%s.msgpack' % now
      symlink(new_file, symlink_file)
      f = open(new_file, "wb")
      while True:
         f.write(socket.recv())
         #f.flush()
         #fsync(f.fileno())
   finally:
      try:
         f.close()
      except:
         pass
Ejemplo n.º 25
0
    def getRadio(self):

        map = scl.generate_map("pySysMoCo")
        radioconfigcontrol = map["radioconfcontrol"]

        #Create request for getting ratio
        request = radioconfig_pb2.RadioConfigControl()
        request.type = radioconfig_pb2.REQUEST
        request.command = radioconfig_pb2.GET_RADIO_CONFIG
        string = request.SerializeToString()
        radioconfigcontrol.send(string)

        #Create Reply
        reply = radioconfig_pb2.RadioConfigControl()
        string = radioconfigcontrol.recv()
        reply.ParseFromString(string)
        # set radioconfig for later reference
        self.radioConfig = reply.radioconf

        # FIXME: change to tree view and add engines too
        # update component list
        self.ui.componentList.clear()
        for i in self.radioConfig.engines:
            for k in i.components:
                self.ui.componentList.addItem(str(k.name))

        # make first item active
        self.ui.componentList.setCurrentItem(self.ui.componentList.item(0))
Ejemplo n.º 26
0
def main(name):
    global socket_map, gps_lock, font, caution_written
    socket_map = generate_map('aircomm_app')
    socket = socket_map['in']
    while True:
        data = loads(socket.recv())
        if data[0] == 'js':
            print map(lambda x: x * 1.0 / (2**15), data[1:])
Ejemplo n.º 27
0
def main(name):
   global socket_map, gps_lock, font, caution_written
   socket_map = generate_map('aircomm_app')
   socket = socket_map['in']
   while True:
      data = loads(socket.recv())
      if data[0] == 'js':
         print map(lambda x : x * 1.0 / (2 ** 15), data[1:])
Ejemplo n.º 28
0
def main(name):
   global socket_map, gps_lock, font, spinning, caution_written
   socket_map = generate_map(name)

   gps_lock = Lock()
   font = ImageFont.truetype(getenv('PENGUPILOT_PATH') + '/display/service/verdana.ttf', 11)
   
   t = Thread(target = spinning_reader)
   t.daemon = True
   t.start()

   t1 = Thread(target = cpuavg)
   t1.daemon = True
   t1.start()

   t2 = Thread(target = pmreader)
   t2.daemon = True
   t2.start()

   t3 = Thread(target = gps)
   t3.daemon = True
   t3.start()

   screens = [(draw_health, 10),
              (draw_gps, 10),
              (draw_gps2, 10)]

   screen = 0
   oled.init('/dev/i2c-3', W, H)
   sleep(5)
   try:
      while True:
         try:
            if not spinning:
               caution_written = False
               oled.invert(False)
               t = time()
               while time() < t + screens[screen][1]:
                  image = Image.new("1", (W, H), BLACK)
                  draw = ImageDraw.Draw(image)
                  screens[screen][0](draw)
                  show_image(image)
                  sleep(1)
                  if critical:
                     alert = Alert(1.0, 0.1, 1, batt_low, True)
                     alert.start()
                     alert.join()
            else:
               caution()
               sleep(0.2)
         except Exception, e:
            print e
         screen = (screen + 1) % len(screens)
   except:
      oled.invert(False)
      oled.clear()
      oled.update()
Ejemplo n.º 29
0
def main(name):
    global socket_map, gps_lock, font, spinning, caution_written
    socket_map = generate_map(name)

    gps_lock = Lock()
    font = ImageFont.truetype(
        getenv('PENGUPILOT_PATH') + '/display/service/verdana.ttf', 11)

    t = Thread(target=spinning_reader)
    t.daemon = True
    t.start()

    t1 = Thread(target=cpuavg)
    t1.daemon = True
    t1.start()

    t2 = Thread(target=pmreader)
    t2.daemon = True
    t2.start()

    t3 = Thread(target=gps)
    t3.daemon = True
    t3.start()

    screens = [(draw_health, 10), (draw_gps, 10), (draw_gps2, 10)]

    screen = 0
    oled.init('/dev/i2c-3', W, H)
    sleep(5)
    try:
        while True:
            try:
                if not spinning:
                    caution_written = False
                    oled.invert(False)
                    t = time()
                    while time() < t + screens[screen][1]:
                        image = Image.new("1", (W, H), BLACK)
                        draw = ImageDraw.Draw(image)
                        screens[screen][0](draw)
                        show_image(image)
                        sleep(1)
                        if critical:
                            alert = Alert(1.0, 0.1, 1, batt_low, True)
                            alert.start()
                            alert.join()
                else:
                    caution()
                    sleep(0.2)
            except Exception, e:
                print e
            screen = (screen + 1) % len(screens)
    except:
        oled.invert(False)
        oled.clear()
        oled.update()
Ejemplo n.º 30
0
def main(name):
    map = generate_map(name)
    socket = map['log_data_pub']
    prefix = user_data_dir + sep + 'log' + sep
    new_file = prefix + 'session.log'
    f = open(new_file, "wb")
    while True:
        data = socket_in.recv()
        f.write(data)
        f.flush()
Ejemplo n.º 31
0
def main(name):
   map = generate_map(name)
   socket = map['log_data_pub']
   prefix = user_data_dir + sep + 'log' + sep
   new_file = prefix + 'session.log'
   f = open(new_file, "wb")
   while True:
      data = socket_in.recv()
      f.write(data)
      f.flush()
Ejemplo n.º 32
0
 def __init__(self, name):
     map = generate_map(name)
     self.ctrl_socket = map['ctrl']
     self.event_socket = map['event']
     self.conf = Config()
     self.map = {
         str: 'str_val',
         int: 'int_val',
         float: 'dbl_val',
         bool: 'bool_val'
     }
Ejemplo n.º 33
0
def main(name):
   socket = generate_map(name)['networks']
   while True:
      pipe = Popen(['iwlist', 'wlan0', 'scan'], stdout = PIPE).stdout
      cells = parse_cells(pipe.readlines())
      for cell in cells:
         pair = [cell['Address'] + '_' + cell['Name'], int(cell['Signal'][0:-3])]
         print pair
         socket.send(dumps(pair))
      print 
      sleep(0.5)
Ejemplo n.º 34
0
def main(name):
    elev_map = SrtmElevMap()
    socket_map = generate_map(name)
    gps_socket = socket_map['gps']
    elev_socket = socket_map['elev']
    while True:
        gps = loads(gps_socket.recv())
        try:
            elev = elev_map.lookup((gps[LON], gps[LAT]))
            elev_socket.send(dumps([elev]))
        except:
            pass
Ejemplo n.º 35
0
def main(name):
   elev_map = SrtmElevMap()
   socket_map = generate_map(name)
   gps_socket = socket_map['gps']
   elev_socket = socket_map['elev']
   while True:
      gps = loads(gps_socket.recv())
      try:
         elev = elev_map.lookup((gps[LON], gps[LAT]))
         elev_socket.send(dumps([elev]))
      except:
         pass
Ejemplo n.º 36
0
def main(name):
   global socket_map, gps_lock, font, caution_written
   socket_map = generate_map('aircomm_app')
   socket = socket_map['in']
   while True:
      try:
         data = loads(socket.recv())
	 if data[0] == 'EMERGENCY-KILL':
	    print 'emergency kill requested'
      except Exception, e:
         print e
      sleep(1.0)
Ejemplo n.º 37
0
def main(name):
   socket = generate_map(name)['networks']
   while True:
      pipe = Popen(['iwlist', 'wlan0', 'scan'], stdout = PIPE).stdout
      cells = parse_cells(pipe.readlines())
      for cell in cells:
         try:
            sig = int(cell['Signal'][0:-3])
         except:
            sig = int(cell['Signal'][0:-4])
         pair = [cell['Address'] + '_' + cell['Name'], sig]
         socket.send(dumps(pair))
      sleep(1.0)
Ejemplo n.º 38
0
def main(name):
    socket = generate_map(name)['networks']
    while True:
        pipe = Popen(['iwlist', 'wlan0', 'scan'], stdout=PIPE).stdout
        cells = parse_cells(pipe.readlines())
        for cell in cells:
            pair = [
                cell['Address'] + '_' + cell['Name'],
                int(cell['Signal'][0:-3])
            ]
            print pair
            socket.send(dumps(pair))
        print
        sleep(0.5)
Ejemplo n.º 39
0
def main(name):
   map = generate_map(name)
   gps_reader = GPS_Reader(map['gps'])
   gps_reader.start()
   wifi_socket = map['networks']
   f = file("/tmp/wifi.log", "w")
   while True:
      try:
         measure = loads(wifi_socket.recv())
         gps = gps_reader.data
         f.write('%f %f %s %d\n' % (gps[LAT], gps[LON], measure[0], measure[1]))
         f.flush()
      except:
         pass
Ejemplo n.º 40
0
def main(name):
    map = generate_map(name)
    gps_socket = map['gps']
    ts_socket = map['time_set']
    while not loads(ts_socket.recv()):
        pass
    now = datetime.today().isoformat().replace(':', '')
    prefix = user_data_dir + sep + 'log' + sep
    new_file = prefix + 'gps_' + now + '.log'
    f = open(new_file, "wb")
    while True:
        data = gps_socket.recv()
        f.write(data)
        f.flush()
Ejemplo n.º 41
0
def main(name):
   map = generate_map(name)
   gps_socket = map['gps']
   ts_socket = map['time_set']
   while not loads(ts_socket.recv()):
      pass
   now = datetime.today().isoformat().replace(':', '')
   prefix = user_data_dir + sep + 'log' + sep
   new_file = prefix + 'gps_' + now + '.log'
   f = open(new_file, "wb")
   while True:
      data = gps_socket.recv()
      f.write(data)
      f.flush()
Ejemplo n.º 42
0
def main(name):
   elev_map = SrtmElevMap()
   socket_map = generate_map(name)
   gps_socket = socket_map['gps']
   elev_socket = socket_map['elev']
   start_elev = None
   while True:
      gps = loads(gps_socket.recv())
      try:
         elev = float(elev_map.lookup((gps[LON], gps[LAT])))
         if not start_elev:
            start_elev = elev
         elev_socket.send(dumps([elev, start_elev]))
      except:
         pass
Ejemplo n.º 43
0
def main(name):
    elev_map = SrtmElevMap()
    socket_map = generate_map(name)
    gps_socket = socket_map['gps']
    elev_socket = socket_map['elev']
    rt = RateTimer(1.0)
    while True:
        raw = gps_socket.recv()
        if rt.expired():
            try:
                gps = loads(gps_socket.recv())
                elev = elev_map.lookup((gps[LON], gps[LAT]))
                elev_socket.send(dumps([elev]))
            except:
                pass
Ejemplo n.º 44
0
def main(name):
    map = generate_map(name)
    gps_reader = GPS_Reader(map['gps'])
    gps_reader.start()
    wifi_socket = map['wifi']
    f = file("/tmp/wifi.log", "w")
    while True:
        try:
            measure = loads(wifi_socket.recv())
            gps = gps_reader.data
            f.write('%f %f %s %d\n' %
                    (gps.lat, gps.lon, measure[0], measure[1]))
            f.flush()
        except:
            pass
Ejemplo n.º 45
0
def main(name):
   elev_map = SrtmElevMap()
   socket_map = generate_map(name)
   gps_socket = socket_map['gps']
   elev_socket = socket_map['elev']
   rt = RateTimer(1.0)
   while True:
      raw = gps_socket.recv()
      if rt.expired():
         try:
            gps = loads(gps_socket.recv())
            elev = elev_map.lookup((gps[LON], gps[LAT]))
            elev_socket.send(dumps([elev]))
         except:
            pass
Ejemplo n.º 46
0
def main(name):
   map = generate_map(name)
   socket = map['power']
   opcd = OPCD_Interface(map['opcd_ctrl'], 'pi_quad')
   voltage_adc = ADS1x15_ADC(opcd.get('voltage_channel'))
   #current_adc = ADS1x15_ADC(opcd.get('current_channel'))
   voltage_lambda = eval(opcd.get('adc_to_voltage'))
   #current_lambda = eval(opcd.get('adc_to_current'))
   while True:
      sleep(0.2)
      voltage = voltage_lambda(voltage_adc.read())  
      #current = current_lambda(current_adc.read())
      state = [voltage,  # 0 [V]
               0.4]      # 1 [A]
      socket.send(dumps(state))
Ejemplo n.º 47
0
def main(name):
    socket = generate_map(name)['networks']
    while True:
        try:
            pipe = Popen(['iwlist', 'wlan0', 'scan'], stdout=PIPE).stdout
            cells = parse_cells(pipe.readlines())
            for cell in cells:
                try:
                    sig = int(cell['Signal'][0:-3])
                except:
                    sig = int(cell['Signal'][0:-4])
                pair = [cell['Address'] + '_' + cell['Name'], sig]
                socket.send(dumps(pair))
            sleep(1.0)
        except:
            pass
Ejemplo n.º 48
0
def main(name):
   map = generate_map(name)
   mon_reader = MonReader(map['mon'])
   networks_reader = NetworksReader(map['networks'])
   mon_reader.start()
   networks_reader.start()
   
   netfile = open('/tmp/netfile.txt', 'w')
   mon_reader.event.wait()
   while True:
      networks_reader.event.wait()
      networks_reader.event.clear()
      measure = networks_reader.data
      tstamp = time()
      netfile.write('%f; %f; %f; %f; %s; %s\n' % (tstamp, mon_reader.data.x, mon_reader.data.y, mon_reader.data.z, measure.mac, measure.rssi))
      netfile.flush()
Ejemplo n.º 49
0
def main(name):
   dev = 'wlan1'
   call(['ifconfig', dev, 'down'])
   call(['iwconfig', dev, 'mode', 'monitor'])
   call(['iwconfig', dev, 'channel', '1'])
   call(['ifconfig', dev, 'up'])
   socket = generate_map(name)['networks']
   p = Popen(['tcpdump', '-l', '-e', '-i', dev], stdout = PIPE, stderr = PIPE)
   while True:
      line = p.stdout.readline()
      list = line.split(' ')
      if len(list) == 46:
         measure = Measurement()
         measure.mac = list[11][3:]
         measure.rssi = int(list[6][0:-2])
         print measure
         socket.send(measure.SerializeToString())
Ejemplo n.º 50
0
def main(name):
    script_path = os.path.dirname(os.path.abspath(__file__))
    gm = GeoMag(script_path + os.sep + 'geomag' + os.sep + 'WMM.COF')
    socket_map = generate_map(name)
    gps_socket = socket_map['gps']
    decl_socket = socket_map['decl']
    rt = RateTimer(1)
    while True:
        raw = gps_socket.recv()
        if rt.expired():
            gps = loads(raw)
            try:
                date = datetime.strptime(gps[TIME], '%Y-%m-%d %H:%M:%S').date()
                decl = gm.GeoMag(gps[LAT], gps[LON], time=date).dec
                decl_socket.send('%f' % decl)
            except:
                pass
Ejemplo n.º 51
0
def main(name):
   script_path = os.path.dirname(os.path.abspath(__file__))
   gm = GeoMag(script_path + os.sep + 'geomag' + os.sep + 'WMM.COF')
   socket_map = generate_map(name)
   gps_socket = socket_map['gps']
   decl_socket = socket_map['decl']
   rt = RateTimer(1)
   while True:
      raw = gps_socket.recv()
      if rt.expired():
         gps = loads(raw)
         try:
            date = datetime.strptime(gps[TIME], '%Y-%m-%d %H:%M:%S').date()
            decl = gm.GeoMag(gps[LAT], gps[LON], time = date).dec
            decl_socket.send('%f' % decl)
         except:
            pass
Ejemplo n.º 52
0
def main(name):
   map = generate_map(name)
   socket = map['power']
   opcd = OPCD_Interface(map['opcd_ctrl'], 'overo_quad')
   voltage_adc = TWL4030_MADC(opcd.get('voltage_channel'))
   current_adc = TWL4030_MADC(opcd.get('current_channel'))
   voltage_lambda = eval(opcd.get('adc_to_voltage'))
   current_lambda = eval(opcd.get('adc_to_current'))
   while True:
      try:
         sleep(0.2)
         voltage = voltage_lambda(voltage_adc.read())  
         current = current_lambda(current_adc.read())
         state = [voltage,  # 0 [V]
                  current]  # 1 [A]
         socket.send(dumps(state))
      except:
         pass
Ejemplo n.º 53
0
def main(name):
   script_path = os.path.dirname(os.path.abspath(__file__))
   gm = GeoMag(script_path + os.sep + 'geomag' + os.sep + 'WMM.COF')
   socket_map = generate_map(name)
   gps_socket = socket_map['gps']
   decl_socket = socket_map['decl']
   i = 0
   while True:
      data = gps_socket.recv()
      if i == 20:
         i = 0
         gps_data = GpsData()
         gps_data.ParseFromString(data)
         if gps_data.time and gps_data.fix >= 2:
            date = datetime.strptime(gps_data.time, '%Y-%m-%d %H:%M:%S').date()
            decl = gm.GeoMag(gps_data.lat, gps_data.lon, time = date).dec
            print time(), decl
            decl_socket.send('%f' % decl)
      i += 1
Ejemplo n.º 54
0
 def __init__(self, dispatcher):
     Thread.__init__(self)
     self.dispatcher = dispatcher
     self.opcd_interface = OPCD_Interface(
         generate_map('mavlink')['opcd_ctrl'])
     self.param_map = {}
     self.param_name_map = {}
     list = self.opcd_interface.get('')
     c = 0
     type_map = {float: MAVLINK_TYPE_FLOAT_T, long: MAVLINK_TYPE_INT32_T}
     cast_map = {float: float, long: int}
     for name, val in list:
         try:
             type = type_map[val.__class__]
             self.param_map[c] = name, type, cast_map[val.__class__]
             self.param_name_map[c] = c, type, cast_map[val.__class__]
             c += 1
         except Exception, e:
             print str(e)
Ejemplo n.º 55
0
    def reconfigRadio(self):
        print "reconfigRadio called"
        map = scl.generate_map("pySysMoCo")
        radioconfigcontrol = map["radioconfcontrol"]

        #Create request for radio reconfiguration
        request = radioconfig_pb2.RadioConfigControl()
        request.type = radioconfig_pb2.REQUEST
        request.command = radioconfig_pb2.SET_RADIO_CONFIG

        # get selected component and add to reconf request
        currentComponent = self.ui.componentList.currentItem()
        print currentComponent.text()

        # add engine and just use name of first
        newEngine = request.radioconf.engines.add()

        # find the engine the component lives in and set name
        for engine in self.radioConfig.engines:
            for component in engine.components:
                if component.name == currentComponent.text():
                    # create new engine in request object
                    newEngine.name = engine.name

        newComponent = newEngine.components.add()
        newComponent.name = str(currentComponent.text())

        # add all parameter that have changed
        # FIXME: compare with self.radioConfig and really just update if changes
        numRows = self.ui.parameterTable.rowCount()
        for row in xrange(0, numRows):
            newParameter = newComponent.parameters.add()
            # name is column 0
            newParameter.name = str(self.ui.parameterTable.item(row, 0).text())
            # value is column 1
            newParameter.value = str(
                self.ui.parameterTable.item(row, 1).text())

        #send request
        string = request.SerializeToString()
        radioconfigcontrol.send(string)
        #wait for reply, fixme: check result
        string = radioconfigcontrol.recv()
Ejemplo n.º 56
0
def main(name):
    map = generate_map(name)
    socket = map['power']
    opcd = OPCD_Interface(map['opcd_ctrl'], 'overo_quad')
    voltage_adc = TWL4030_MADC(opcd.get('voltage_channel'))
    current_adc = TWL4030_MADC(opcd.get('current_channel'))
    voltage_lambda = eval(opcd.get('adc_to_voltage'))
    current_lambda = eval(opcd.get('adc_to_current'))
    while True:
        try:
            sleep(0.2)
            voltage = voltage_lambda(voltage_adc.read())
            current = current_lambda(current_adc.read())
            state = [
                voltage,  # 0 [V]
                current
            ]  # 1 [A]
            socket.send(dumps(state))
        except:
            pass
Ejemplo n.º 57
0
    def run(self):
        """ server routine """
        print self.component + ": " + self.gate + ": listener thread startet"

        # Prepare our context and Sockets
        map = scl.generate_map(self.component)
        socket = map[self.gate]

        while not self.stopped():
            # non-blocking recv to allow app to shutdown
            try:
                string = socket.recv(zmq.NOBLOCK)
                self.string = string  # store received string
                self.recvSignal.emit()
            except zmq.ZMQError, e:
                if e.errno == zmq.EAGAIN:
                    pass
                else:
                    raise
            time.sleep(0.1)