diff --git a/README.md b/README.md index e9b5a28..908a36c 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,6 @@ Open-Source Ship Setup -------- -All the required modules are in bootstap.sh I'm using a raspberry model B and B+ Libraries @@ -19,7 +18,7 @@ Hardware - Bmp180 (Barometric pressure sensor) - PI Camera (normal version) - Ultimate GPS Breakout v3 (GPS) - - Standard Size - High Torque - Metal Gear Servo + - Standard Size - High Torque - Metal Gear Servo - Mtroniks Viper Marine 20 - Aluminum Double Rudder - 2.5:1 gearbox motor, 4.5-15V 540 motor diff --git a/cli/__init__.py b/cli/__init__.py deleted file mode 100644 index 8b13789..0000000 --- a/cli/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/cli/command.py b/cli/command.py deleted file mode 100644 index b81e6bb..0000000 --- a/cli/command.py +++ /dev/null @@ -1,76 +0,0 @@ -import sys -import logging -import os -import threading - -class Command: - def __init__(self, kernel): - logging.info("CLI:\tcommand init.") - self._kernel = kernel - - def update(self): - self._kernel.update() - - def halt(self): - self._kernel.halt() - - def throttle(self): - var = raw_input("How much throttle [0-100]: ").strip() - self._kernel.set_throttle(var) - - def steering(self): - var = raw_input("which angle [-180-180]: ").strip() - self._kernel.set_steering(var) - - def enable_nav(self): - #enable the automatic navigation of the boat - logging.info("CLI:\tnav started.") - threading.Thread(target=self._kernel.run_navigation).start() - - def disable_nav(self): - logging.info("CLI:\tnav stopping.") - self._kernel._navigationCanRun = False #fuck threading joins - - def add_point(self): - lat = raw_input("Latitude: ").strip() - lon = raw_input("Longitude: ").strip() - self._kernel.add_point(lat, lon) - logging.info("CLI:\tPoint added.") - - def thread_info(self): - print "Active Threads : " + str(threading.activeCount()) - -def help(): - #we want it to look nice hu? - print "-------------------|>---------------" - print "-------------------|----------------" - print "~~~~~~~~~~~~\INVENAVI/~~~~~~~~~~~~~~" - print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" - print "update : reads all the sensors" - print "halt : stop all motors/servo's" - print "throttle : set motor" - print "steering : set servo angle" - print "add point : add waypoint for nav" - print "enablenav : enable navigation" - print "disablenav : disable navigation" - print "threadinfo : show info about threads" - print "takepicture: take a picture" - print "____________________________________" - print "to exit press ctrl+c" - print "" - -# This will be to handle input for a function we don't have -def fail(): - print "You gave a bad function name , type help!" - -def run(kernel): - comd = Command(kernel) - #dictonary - funcs = {"threadinfo" : comd.thread_info, "addpoint" : comd.add_point, "update": comd.update, "throttle": comd.throttle, "steering": comd.steering, "halt": comd.halt, "enablenav": comd.enable_nav, "disablenav": comd.disable_nav, "help": help} - - while 1: - try: - var = raw_input("Command: ").strip() - funcs.get(var, fail)() - except KeyboardInterrupt: - break \ No newline at end of file diff --git a/command.js b/command.js index b56cd8a..47844c4 100644 --- a/command.js +++ b/command.js @@ -21,6 +21,10 @@ var Command = function (kernel) { this.startComponents(); } else if (data == 'stop') { this.stopComponents(); + } else if (data == 'steering') { + this.steering(); + } else if (data == 'throttle') { + this.throttle(); } else if (data == 'update') { this.update(); } else if (data == 'config') { @@ -30,7 +34,6 @@ var Command = function (kernel) { } else if ( data == '\u0003' || data == 'quit' || data == 'exit') { this.exit(); } else { - console.warn('Error: Command not found'); this.complete(); } @@ -96,6 +99,36 @@ var Command = function (kernel) { this.complete(); }; + this.throttle = function (level) { + this.ask("Throttle level -100 to 100: ",function (data){ + if (this.kernel.components.driver) { + this.kernel.components.driver.setThrottle(data); + } else { + console.log("driver is not initialized yet"); + } + + this.complete(); + }.bind(this)); + }; + + this.steering = function (angle) { + this.ask("Steering angle -100 to 100: ",function (data){ + if (this.kernel.components.driver) { + this.kernel.components.driver.setSteering(data); + } else { + console.log("driver is not initialized yet"); + } + + this.complete(); + }.bind(this)); + }; + + this.halt = function () { + this.components.driver.halt(); + + this.complete(); + }; + this.exit = function () { console.log('exiting program'); process.exit(); @@ -107,8 +140,6 @@ var Command = function (kernel) { data = data.toString().trim(); callback(data); }); - - this.complete(); }; } diff --git a/config.py b/config.py deleted file mode 100644 index c01073f..0000000 --- a/config.py +++ /dev/null @@ -1,211 +0,0 @@ -import logging -import logging.handlers - -import os -import time -import platform -import subprocess -import threading - -from gps import * -from dummy_devices import ( - DummyCameraController, - DummyCompassSensor, - DummyDriveController, - DummyGPSSensor) - -class InvenaviConfig(object): - _devices = [] - _root_dir = os.path.join(os.getenv("HOME"), "invenavi") - - def __init__(self): - logger = logging.getLogger() - logger.setLevel(logging.DEBUG) - console = logging.StreamHandler() - logger.addHandler(console) - - # create directory - if not os.path.exists(self.logs_path): - os.makedirs(self.logs_path) - - # add file logging - log_file_stem = os.path.join(self.logs_path, 'invenavi_%s.log' % time.strftime('%Y%m%d_%H%M%S')) - handler = logging.handlers.RotatingFileHandler(log_file_stem, backupCount=50) - formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') - handler.setFormatter(formatter) - logger.addHandler(handler) - - # default attachments to None - self.gps_sensor = None - self.compass_sensor = None - self.barometer_sensor = None - self.drive_controller = None - self.camera_controller = None - - # RPC config - self._rpc_port = None - - # - # RPC config - # - - @property - def rpc_port(self): - return self._rpc_port - - @rpc_port.setter - def rpc_port(self, value): - self._rpc_port = value - - # - # file / paths section - # - @property - def logs_path(self): - return os.path.join(self._root_dir, "logs") - - def configure_devices(self, debug=False): - """ Configures i2c devices when running in appropriate environment. """ - - # running as root on linux so can scan for devices and configure them - # although inline imports normally not encouraged - # enables me to load dependencies only when I know I can (eg linux, i2c, root, etc...) - import raspberrypi - - # i2c devices - try: - logging.info("CFG:\tConfiguring i2c devices...") - # scan for connected devices - i2c_addresses = self.scan_i2c(debug=debug) - - # lookup available device drivers by address - for addr, in_use in i2c_addresses: - device_name, device_driver = self.lookup(addr, debug=debug) - self._devices.append([addr, device_name, device_driver, in_use]) - - except Exception as ex: - logging.exception("CFG:\tError scanning i2c devices - %s" % ex) - - #GPS init - try: - from sensor.GPS_serial import GPSSensor - self.gps_sensor = GPSSensor() - except Exception as ex: - logging.warning("CFG:\tError setting up GPS over serial - %s" % ex) - - #camera unit - try: - from sensor.Camera import CameraController - self.camera_controller = CameraController() - except Exception as ex: - logging.warning("CFG:\tError setting up Camera - %s" % ex) - - # Add dummies for devices that are still missing. - self._set_dummy_devices() - - - def lookup(self, addr, debug=False): - """ lookup available device drivers by hex address, - import and create driver class, - setup particular devices so easily retrieved by consumers. """ - if(debug): - logging.debug("CFG:\tChecking for driver for device at i2c %s" % addr) - - # note: i2c addresses can conflict - # could scan registers etc to confirm count etc? - import raspberrypi - - if addr == 0x19: - try: - from sensor.Adafruit_LSM303DLHC import LSM303DLHC - self.compass_sensor = LSM303DLHC(0x19, 0x1E, debug) - self.compass_sensor.set_temp_enabled(True) - except Exception as ex: - logging.warning("CFG:\tError setting up COMPASS over i2c - %s" % ex) - return "COMPASS", self.barometer_sensor - - elif addr == 0x40: - try: - from vehicle.drive_controller import AdafruitDriveController - self.drive_controller = AdafruitDriveController(i2c_addr=addr, debug=debug) - except Exception as ex: - logging.info("CFG:\tError setting up DRIVECONTROLLER over i2c - %s" % ex) - return "DRIVECONTROLLER", self.drive_controller - - elif addr == 0x77: - try: - from sensor.Adafruit_BMP085 import BMP085 - self.barometer_sensor = BMP085(debug=debug) - except Exception as ex: - logging.warning("CFG:\tError setting up BAROMETER over i2c - %s" % ex) - return "BAROMETER", self.barometer_sensor - - else: - return "unknown", None - - def scan_i2c(self, debug=False): - """scans i2c port returning a list of detected addresses. - Requires sudo access. - Returns True for in use by a device already (ie UU observed)""" - - import raspberrypi - - proc = subprocess.Popen(['sudo', 'i2cdetect', '-y', raspberrypi.i2c_bus_num()], - stdout = subprocess.PIPE, - close_fds = True) - std_out_txt, std_err_txt = proc.communicate() - - if debug: - logging.debug(std_out_txt) - logging.debug(std_err_txt) - - # i2c returns - # -- for unused addresses - # UU for addresses n use by a device - # 0x03 to 0x77 for detected addresses - # need to keep columns if care about UU devices - addr = [] - lines = std_out_txt.rstrip().split("\n") - - if lines[0] in "command not found": - raise RuntimeError("i2cdetect not found") - - for i in range(0,8): - for j in range(0,16): - idx_i = i+1 - idx_j = j*3+4 - cell = lines[idx_i][idx_j:idx_j+2].strip() - if cell and cell != "--": - logging.info(" ...device at: %s %s", hex(16*i+j), cell) - hexAddr = 16*i+j - if cell == "UU": - addr.append([hexAddr, True]) - else: - addr.append([hexAddr, False]) - - return addr - - def _set_dummy_devices(self): - """ Goes through the list of devices and adds a dummy for every - missing device """ - - # We do not set dummy devices for Magnetometer or Accelerometer. - # Later this should be handled differently - - if not self.gps_sensor: - self.gps_sensor = DummyGPSSensor(fix=3, lat=90) - logging.info("CFG:\tLoaded dummy GPS driver") - # set dummy gps here. - - if not self.compass_sensor: - self.compass_sensor = DummyCompassSensor() - logging.info("CFG:\tLoaded dummy compass driver") - # set dummy compass here. - - if not self.drive_controller: - self.drive_controller = DummyDriveController() - logging.info("CFG:\tLoaded dummy drive controller") - - if not self.camera_controller: - self.camera_controller = DummyCameraController() - logging.info("CFG:\tLoaded dummy camera driver") diff --git a/drivedummy.js b/drivedummy.js new file mode 100644 index 0000000..a26689c --- /dev/null +++ b/drivedummy.js @@ -0,0 +1,22 @@ +// Constructor +var DriveDummy = function (kernel) { + this.kernel = kernel; + + this.setThrottle = function(level) { + console.log("Set throttle to " + level); + this.kernel.data.throttle = level; + } + + this.setSteering= function(angle) { + console.log("Set steering angle to " + angle); + this.kernel.data.steering = angle; + } + + this.halt = function () { + console.log("Halting drive controller"); + this.kernel.data.steering = 0; + this.kernel.data.throttle = 0; + } +} + +module.exports = DriveDummy; diff --git a/dummy_devices.py b/dummy_devices.py deleted file mode 100644 index 16dfe5f..0000000 --- a/dummy_devices.py +++ /dev/null @@ -1,67 +0,0 @@ -import os -import logging - - -class DummyCameraController(object): - """ 'Dummy' camera controller that just logs. """ - - @property - def last_img(self): - return self._last_img - - -class DummyDriveController(object): - """ 'Dummy' drive controller that just logs. """ - - # current state - throttle_level = 0.0 - steering_angle = 0.0 - - def __init__(self): - pass - - def set_throttle(self, throttle_level): - logging.debug("DRIVE:\tThrottle set to: %s" % throttle_level) - self.throttle_level = throttle_level - - def set_steering(self, angle): - logging.debug("DRIVE:\tSteering set to: %s" % angle) - self.steering_angle = angle - - def halt(self): - logging.debug("DRIVE:\tDrive halting.") - self.throttle_level = 0.0 - self.steering_angle = 0.0 - - -class DummyCompassSensor(object): - """ 'Dummy' compass sensor that outputs a static heading value. """ - - def __init__(self, interface="", hw_interface="-1", debug=False,heading=0.0, pitch=0.0, roll=0.0): - self.debug = debug - if self.debug: - logging.basicConfig(level=logging.DEBUG) - self.heading = heading - self.pitch = pitch - self.roll = roll - - def read_sensor(self): - return self.heading, self.pitch, self.roll - - def read_magnetic_heading(self): - return self.heading - -class DummyGPSSensor(object): - """ 'Dummy' GPS sensor that outputs static GPS data. """ - def __init__(self, interface="", hw_interface="", debug=False,fix=1, lat=0.0, lon=0.0, head=0.0, speed=0.0, alt=0.0,sat=0, time="", date=""): - self.gps_data = ( - fix, # fix - lat, # lat - lon, # lon - alt, # altitude - sat, # num_sat - time, # timestamp - ) # datestamp - - def read_sensor(self): - return self.gps_data \ No newline at end of file diff --git a/index.js b/index.js index eba073a..183e553 100644 --- a/index.js +++ b/index.js @@ -1,8 +1,5 @@ "use strict"; -var Webserver = require("./webserver"); -var Command = require("./command"); -var IMUDummy = require("./imudummy"); var argv = require('minimist')(process.argv.slice(2)); var kernel = { @@ -21,12 +18,14 @@ var kernel = { gps_speed: false, gps_alt: false, gps_num_sat: false, + throttle: 0, + steering: 0, }, components: { webserver: false, command: false, imu: false, - pwm: false, + driver: false, gps: false, }, update: function() { @@ -39,30 +38,51 @@ var kernel = { //starting imu if (this.components.imu == false) { if (this.config.dummy) { - console.log("starting IMU"); + console.log("starting dummy IMU"); + + var IMUDummy = require("./imudummy"); this.components.imu = new IMUDummy(kernel); } else { console.warn("can't implement imu yet"); } } else { - console.warn("IMU already implemented"); + console.warn("IMU already running"); + } + + //starting drive controller + if (this.components.driver == false) { + if (this.config.dummy) { + console.log("starting dummy driver"); + + var DriveDummy = require("./drivedummy"); + this.components.driver = new DriveDummy(kernel); + } else { + console.warn("can't implement driver yet"); + } + } else { + console.warn("Driver already running"); } }, stopComponents: function() { console.log("stopping IMU"); this.components.imu == false; + + console.log("stopping driver"); + this.components.driver == false; } } +//set dummy if (argv["dummy"] == true) { kernel.config.dummy = true; } if (argv["runmode"] == "cli" || typeof argv["runmode"] == "undefined") { + var Command = require("./command"); kernel.components.command = new Command(kernel).start(); } else if (argv["runmode"] == "web") { - console.log('starting web mode'); + var Webserver = require("./webserver"); kernel.components.webserver = new Webserver(kernel).start(); } else if (argv["runmode"] == "headless") { console.log('starting headless'); diff --git a/invenavi.py b/invenavi.py deleted file mode 100644 index 8f806b1..0000000 --- a/invenavi.py +++ /dev/null @@ -1,95 +0,0 @@ -import logging -import sys -import argparse - -from config import InvenaviConfig -from kernel import InvenaviKernel - -class InvenaviRunMode: - #this class is bad , and I should feel bad! - - def __init__(self): - pass - - Cli = "cli" - Manual = "manual" - Remote = "remote" - Auto = "auto" - Modes = [Manual, Remote, Auto, Cli] - -class Invenavi: - """first setup""" - sys.path.append("/home/pi/invenavi") - config = InvenaviConfig() - - def __init__(self): - parser = argparse.ArgumentParser(description='invenavi') - parser.add_argument("-m", "--mode", help="Operational Mode to run" , choices=InvenaviRunMode.Modes , default=InvenaviRunMode.Manual,action='store') - parser.add_argument("-d", "--debug", help="Increase debugging information output" ,action='store_true') - parser.add_argument("-s", "--server", help="Server for remote device", default="raspberrypi.local", type=str, action='store') - parser.add_argument("-dp", "--devport", help="port for device rpc", default=8080, type=int, action='store') - - # and parse - selected_args = parser.parse_args() - self.debug = selected_args.debug - self.selected_mode = selected_args.mode - self.config.server_name = selected_args.server - self.config.rpc_port = selected_args.devport - - #say we're launching - logging.info("invenavi:\tinvenavi ready to initialize..") - - def configure_devices(self): - """ Configures eg i2c and other attached devices.""" - self.config.configure_devices(self.debug) - - def run(self): - """Run the selected mode""" - logging.info("invenavi:\tStarting invenavi in mode {0}:".format(self.selected_mode)) - - if self.selected_mode == InvenaviRunMode.Manual: - return self.run_headless() - elif self.selected_mode == InvenaviRunMode.Cli: - return self.run_cli() - else: - logging.error("invenavi:\t Invalid mode! exiting") - return 1 - - def run_headless(self): - - # configure - self.configure_devices() - - # create controller - kernel = InvenaviKernel(self.config, debug=self.debug) - - # run internal webhost - import web.webhost - web.webhost.run_main_host(kernel, self.config.rpc_port) - logging.info("invenavi:\tProgram complete - exiting.") - - #done - return 0 - - def run_cli(self): - - # configure - self.configure_devices() - - # create controller - kernel = InvenaviKernel(self.config, debug=self.debug) - - #run the cli mode - import cli.command - cli.command.run(kernel) - - #done - return 0 - -def main(): - invenavi = Invenavi() - return invenavi.run() - -if __name__ == "__main__": - status = main() - sys.exit(status) diff --git a/kernel.py b/kernel.py deleted file mode 100644 index a0ff79f..0000000 --- a/kernel.py +++ /dev/null @@ -1,117 +0,0 @@ -#invenvi core file - -import logging -import os -import time - -from model_data import ModelData -from navigation.Navigation import Navigation - -class InvenaviKernel: - def __init__(self, config, debug=False): - self.config = config - self.debug = debug - - # sensors - self._gps_sensor = config.gps_sensor - self._compass_sensor = config.compass_sensor - self._barometer_sensor = config.barometer_sensor - - # vehicle - self._drive_controller = config.drive_controller - - # camera - self._camera_controller = config.camera_controller - - # navigation - self._navigation_controller = Navigation(self) - self._navigationCanRun = False - - # data class - self.data = ModelData() - - #Navigation - def run_navigation(self): - self._navigation_controller.run() - - def add_point(self,lat,lon): - self._navigation_controller.add_point(lat,lon) - - def clear_points(self): - self._navigation_controller.clear_points() - - def cur_waypoint(self): - return self._navigation_controller.current() - - def navigation_running(self): - if self._navigationCanRun: - return False - else: - return True - - #DriveControlle - def set_throttle(self, throttle_level): - self._drive_controller.set_throttle(throttle_level) - - def set_steering(self, angle): - self._drive_controller.set_steering(angle) - - def get_throttle(self,): - return self._drive_controller.throttle_level - - def get_steering(self): - return self._drive_controller.steering_angle - - #GPS - def read_gps(self): - if self._gps_sensor: - (fix, lat, lon, altitude, num_sat, timestamp) = self._gps_sensor.read_sensor() - self.data.lat = lat - self.data.lon = lon - self.data.altitude = altitude - self.data.has_GPS = True - else: - self.data.has_GPS = False - - - #Sensors - def read_barometer(self): - if self._barometer_sensor: - self.data.temperature = self._barometer_sensor.read_temperature() - self.data.pressure = self._barometer_sensor.read_pressure() - self.data.has_temperature = True - self.data.has_pressure = True - else: - self.data.has_temperature = False - self.data.has_pressure = False - - def read_compass(self): - if self._compass_sensor: - self.data.compass_heading = self._compass_sensor.read_magnetic_heading() - self.data.has_compass = True - else: - self.data.has_compass = False - - #General - def update(self): - try: - self.read_gps() - except Exception as ex: - self.data.has_GPS = False - logging.exception("CORE:\tError in update loop (GPS) - %s" % ex) - - try: - self.read_barometer() - except Exception as ex: - self.data.has_pressure = False - self.data.has_temperature = False - logging.exception("CORE:\tError in update loop (BAROMETER) - %s" % ex) - - try: - self.read_compass() - except Exception as ex: - self.data.has_compass = False - logging.exception("CORE:\tError in update loop (COMPASS) - %s" % ex) - - def halt(self): - self._drive_controller.halt() diff --git a/model_data.py b/model_data.py deleted file mode 100644 index 7f86156..0000000 --- a/model_data.py +++ /dev/null @@ -1,39 +0,0 @@ -# ModelData -# - Internal model containing invenavi state - -class ModelData: - """ Internal model containing invenavi state. """ - - def __init__(self): - # GPS - self.has_GPS = False - self.fix = 0 - self.lat = 0.0 - self.lon = 0.0 - self.gps_heading = 0.0 - self.speed = 0.0 - self.altitude = 0.0 - self.num_sat = 0 - - # time - self.has_time = False - self.timestamp = '' - self.datestamp = '' - - # compass - self.has_compass = False - self.compass_heading = 0.0 - self.compass_pitch = 0.0 - self.compass_roll = 0.0 - - # gyro - self.has_gyro = False - - # accelerometer - self.has_accelerometer = False - - # temperature - self.has_temperature = False - self.has_pressure = False - self.temperature = 0.0 - self.pressure = 0.0 diff --git a/navigation/__init__.py b/navigation/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/raspberrypi.py b/raspberrypi.py deleted file mode 100644 index f001cb3..0000000 --- a/raspberrypi.py +++ /dev/null @@ -1,12 +0,0 @@ -import os -import smbus -import subprocess - -def i2c_bus(): - return smbus.SMBus(1) - -def i2c_bus_num(): - return '1' - -def serial_bus(): - return "/dev/ttyAMA0" \ No newline at end of file diff --git a/sensor/Adafruit_I2C.py b/sensor/Adafruit_I2C.py deleted file mode 100644 index 175c492..0000000 --- a/sensor/Adafruit_I2C.py +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/python - -import smbus - -# =========================================================================== -# Adafruit_I2C Class -# =========================================================================== - -class Adafruit_I2C(object): - - @staticmethod - def getPiRevision(): - """Gets the version number of the Raspberry Pi board""" - # Courtesy quick2wire-python-api - # https://github.com/quick2wire/quick2wire-python-api - # Updated revision info from: http://elinux.org/RPi_HardwareHistory#Board_Revision_History - try: - with open('/proc/cpuinfo','r') as f: - for line in f: - if line.startswith('Revision'): - return 1 if line.rstrip()[-1] in ['2','3'] else 2 - except: - return 0 - - @staticmethod - def getPiI2CBusNumber(): - # Gets the I2C bus number /dev/i2c# - return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 - - def __init__(self, address, busnum=-1, debug=False): - self.address = address - # By default, the correct I2C bus is auto-detected using /proc/cpuinfo - # Alternatively, you can hard-code the bus version below: - # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) - # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) - self.bus = smbus.SMBus(busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) - self.debug = debug - - def reverseByteOrder(self, data): - """Reverses the byte order of an int (16-bit) or long (32-bit) value""" - # Courtesy Vishal Sapre - byteCount = len(hex(data)[2:].replace('L','')[::2]) - val = 0 - for i in range(byteCount): - val = (val << 8) | (data & 0xff) - data >>= 8 - return val - - def errMsg(self): - print "Error accessing 0x%02X: Check your I2C address" % self.address - return -1 - - def write8(self, reg, value): - """Writes an 8-bit value to the specified register/address""" - try: - self.bus.write_byte_data(self.address, reg, value) - if self.debug: - print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg) - except IOError, err: - return self.errMsg() - - def write16(self, reg, value): - """Writes a 16-bit value to the specified register/address pair""" - try: - self.bus.write_word_data(self.address, reg, value) - if self.debug: - print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % - (value, reg, reg+1)) - except IOError, err: - return self.errMsg() - - def writeRaw8(self, value): - """Writes an 8-bit value on the bus""" - try: - self.bus.write_byte(self.address, value) - if self.debug: - print "I2C: Wrote 0x%02X" % value - except IOError, err: - return self.errMsg() - - def writeList(self, reg, list): - """Writes an array of bytes using I2C format""" - try: - if self.debug: - print "I2C: Writing list to register 0x%02X:" % reg - print list - self.bus.write_i2c_block_data(self.address, reg, list) - except IOError, err: - return self.errMsg() - - def readList(self, reg, length): - """Read a list of bytes from the I2C device""" - try: - results = self.bus.read_i2c_block_data(self.address, reg, length) - if self.debug: - print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % - (self.address, reg)) - print results - return results - except IOError, err: - return self.errMsg() - - def readU8(self, reg): - """Read an unsigned byte from the I2C device""" - try: - result = self.bus.read_byte_data(self.address, reg) - if self.debug: - print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % - (self.address, result & 0xFF, reg)) - return result - except IOError, err: - return self.errMsg() - - def readS8(self, reg): - """Reads a signed byte from the I2C device""" - try: - result = self.bus.read_byte_data(self.address, reg) - if result > 127: result -= 256 - if self.debug: - print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % - (self.address, result & 0xFF, reg)) - return result - except IOError, err: - return self.errMsg() - - def readU16(self, reg, little_endian=True): - """Reads an unsigned 16-bit value from the I2C device""" - try: - result = self.bus.read_word_data(self.address,reg) - # Swap bytes if using big endian because read_word_data assumes little - # endian on ARM (little endian) systems. - if not little_endian: - result = ((result << 8) & 0xFF00) + (result >> 8) - if (self.debug): - print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) - return result - except IOError, err: - return self.errMsg() - - def readS16(self, reg, little_endian=True): - """Reads a signed 16-bit value from the I2C device""" - try: - result = self.readU16(reg,little_endian) - if result > 32767: result -= 65536 - return result - except IOError, err: - return self.errMsg() - -if __name__ == '__main__': - try: - bus = Adafruit_I2C(address=0) - print "Default I2C bus is accessible" - except: - print "Error accessing default I2C bus" \ No newline at end of file diff --git a/sensor/__init__.py b/sensor/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/startup.sh b/startup.sh index d4ebda2..bd3d22d 100644 --- a/startup.sh +++ b/startup.sh @@ -1,2 +1,2 @@ #!/bin/bash -screen -S invenavi python invenavi.py \ No newline at end of file +screen -S invenavi node index.js diff --git a/tests/LSM303_test.py b/tests/LSM303_test.py deleted file mode 100644 index 9e643e5..0000000 --- a/tests/LSM303_test.py +++ /dev/null @@ -1,17 +0,0 @@ -import sys -import time - -sys.path.append("/home/pi/invenavi") -from sensor.Adafruit_LSM303DLHC import LSM303DLHC - -debug = False - -compass_sensor = LSM303DLHC(0x19, 0x1E, debug) -compass_sensor.set_temp_enabled(True) -compass_sensor.set_accelerometer_low_power_mode(False) -compass_sensor.set_accelerometer_high_resolution(True) - - -while True: - print compass_sensor.read_magnetic_heading() - time.sleep(1000) \ No newline at end of file diff --git a/vehicle/__init__.py b/vehicle/__init__.py deleted file mode 100644 index 8b13789..0000000 --- a/vehicle/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vehicle/calibrateESC.py b/vehicle/calibrateESC.py deleted file mode 100644 index db008c2..0000000 --- a/vehicle/calibrateESC.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/python - -# -# Calibrate ESC through PWM controller -# - -import raspberrypi - -from time import sleep -from drive_controller import DriveController -from drive_controller import AdafruitDriveController - -if __name__ == "__main__": - print "Calibrating ESC" - drive = AdafruitDriveController(debug=True, i2c_bus=raspberrypi.i2c_bus()) - - raw_input("Power on ESC and enter calibration mode... Then press ...") - - print "run full ahead for 5 sec..." - drive.set_throttle(1.0) - sleep(5) - - print "returning to neutral for 5 sec" - drive.set_throttle(0.0) - sleep(5) - - print "run full reverse for 5 sec" - drive.set_throttle(-1.0) - sleep(5) - - print "returning to neutral" - drive.set_throttle(0.0) - sleep(5) - - print "calibration should be complete!" diff --git a/web/__init__.py b/web/__init__.py deleted file mode 100644 index 8b13789..0000000 --- a/web/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/web/webhost.py b/web/webhost.py deleted file mode 100644 index ef10141..0000000 --- a/web/webhost.py +++ /dev/null @@ -1,86 +0,0 @@ -import sys -import logging -import threading -import json - -from twisted.python import log -from twisted.internet import reactor, defer -from twisted.web.server import Site -from twisted.web.static import File - -from autobahn.twisted.websocket import listenWS -from autobahn.wamp1.protocol import exportRpc, \ - WampServerFactory, \ - WampServerProtocol -class RPCProtos: - def __init__(self, kernel): - logging.info("RPC:\tprotos init.") - self._kernel = kernel - - @exportRpc - def set_throttle(self, throttle): - self._kernel.set_throttle(throttle) - return self.data() - - @exportRpc - def set_steering(self, steering): - self._kernel.set_steering(steering) - return self.data() - - @exportRpc - def data(self): - self._kernel.update() - return { - 'lat': self._kernel.data.lat, - 'lon': self._kernel.data.lon, - 'press' : self._kernel.data.pressure , - 'heading' : self._kernel.data.compass_heading, - 'nav_cur_lat' : self._kernel.cur_waypoint().lat_radians, - 'nav_cur_lon' : self._kernel.cur_waypoint().long_radians, - 'nav_enabled' : self._kernel.navigation_running, - 'temp_int' : self._kernel.data.temperature, - 'temp_ext' : 0, - 'throttle' : self._kernel.get_throttle(), - 'steering' : self._kernel.get_steering() - } - - @exportRpc - def enable_nav(self): - threading.Thread(target=self._kernel.run_navigation()).start() - return self.data() - - @exportRpc - def waypoints(self, data): - waypoints = json.loads(data) - self._kernel.clear_points() - - for waypoint in waypoints: - self._kernel.add_point(waypoint[0],waypoint[1]) - return self.data() - - @exportRpc - def disable_nav(self): - self._kernel._navigationCanRun = False - return self.data() - -class RPCProtocol(WampServerProtocol): - def onClose(self, wasClean, code, reason): - logging.info("RPC:\t"+str(reason)) - - def onSessionOpen(self): - self.registerForRpc(self.protos, "http://10.0.0.142/ws/protos#") - logging.info("RPC:\tnew connection.") - -def run_main_host(kernel, rpc_port): - log.startLogging(sys.stdout) - factory = WampServerFactory("ws://localhost:9000", debugWamp = True) - factory.protocol = RPCProtocol - factory.protocol.protos = RPCProtos(kernel) - factory.setProtocolOptions(allowHixie76 = True) - listenWS(factory) - - webdir = File(".") - web = Site(webdir) - reactor.listenTCP(8080, web) - - reactor.run() diff --git a/webclient/index.html b/webclient/index.html index 9ea6133..5c5377a 100644 --- a/webclient/index.html +++ b/webclient/index.html @@ -6,8 +6,6 @@ - - @@ -50,7 +48,6 @@