Пример #1
0
 def __init__(self, port, baudrate, callback):
     try:
         self.serial = serial.Serial(port, baudrate, timeout=3, rtscts=0)
         self.radio = xbee.XBee(self.serial, callback=callback)
     except self.serial.serialutil.SerialException as e:
         print("SerialException: " + str(e))
         sys.exit(1)
Пример #2
0
def read_energy():
	xb = xbee.XBee(serial.Serial("/dev/ttyUSB0", 9600))
	packet = xb.wait_read_frame()
	voltagedata = [-1] * (len(packet["samples"]) - 1)
	ampdata = [-1] * (len(packet["samples"]) - 1)
	for i in range(len(voltagedata)):
		voltagedata[i] = packet["samples"][i + 1]["adc-0"]
		ampdata[i] = packet["samples"][i + 1]["adc-0"]
	min_v = 1024
	max_v = 0
	for i in range(len(voltagedata)):
		if (min_v > voltagedata[i]):
			min_v = voltagedata[i]
		if (max_v < voltagedata[i]):
			max_v = voltagedata[i]
	avgv = (max_v + min_v) / 2
	vpp =  max_v - min_v
	for i in range(len(voltagedata)):
		voltagedata[i] -= avgv
		voltagedata[i] = (voltagedata[i] * 340) / vpp
	for i in range(len(ampdata)):
		ampdata[i] -= 470
		ampdata[i] /= 15.5
	wattdata = [0] * len(voltagedata)
	for i in range(len(wattdata)):
		wattdata[i] = voltagedata[i] * ampdata[i]
	avgamp = 0
	for i in range(17):
		avgamp += abs(ampdata[i])
	avgamp /= 17.0
	avgwatt = 0
	for i in range(17):
		avgwatt += abs(wattdata[i])
	avgwatt /= 17.0
	state.energy = avgwatt
Пример #3
0
 def Connect(self):
    if self._getConnected():
       raise XBee_802_15_4_Exception("Module is already connected.")
    self._serial = serial.Serial(self._getSocketDev(self._socket), self._setup[BAUDRATE])
    self._module = xbee.XBee(self._serial, escaped=self._setup[APIMODE2])
    writeChanges = False
    for option in self._setup[ATCMDS]:
       cmd = list(option.keys())[0]
       param = list(option.values())[0]
       cmdEnc = cmd.encode("UTF-8")
       if (cmdEnc == CMDWRITE):
          writeChanges = True
          break
       paramEnc = b"\x00"
       blen = (param.bit_length() + 7) // 8
       if blen != 0:
          paramEnc = param.to_bytes(blen, byteorder="big")
       self._module.send("at", frame_id=b"R", command=cmdEnc, parameter=paramEnc)
       rx = self._module.wait_read_frame()
       if not rx["status"]:
          raise XBee_802_15_4_Exception("Did not receive response from AT command")
       if rx["status"] != b"\x00":
          raise XBee_802_15_4_Exception("Wrong AT command/parameter ({}/{})".format(cmd, param))
    if writeChanges:
       self._module.send("at", frame_id=b"R", command=CMDWRITE)
       rx = self._module.wait_read_frame()
       if not rx["status"]:
          raise XBee_802_15_4_Exception("Did not receive response from AT command")
    self._setConnected(True)
Пример #4
0
def demo_sleep_mode():
    '''
    Demonstrates putting the XBee into sleep mode.
    This is NOT sleep in the creating-a-delay-in-the-time.sleep()-sense;
    it instead puts the XBee into low-power mode.
    Note that if ATSM != 0, you'll get an "EALREADY" OSError exception.
    https://www.digi.com/resources/documentation/digidocs/90002219/#reference/r_sleep_mp.htm
    '''
    from machine import Pin
    import time
    import xbee

    led = Pin("D5", Pin.OUT, value=0)
    xb = xbee.XBee()

    while True:

        # Blink at 5 Hz for 5 seconds.
        for _ in range(50):
            time.sleep_ms(100)
            led.toggle()

        # Start sleep mode.
        SLEEPTIME_ms = 60000  # Sleep for 1 minute.
        xb.sleep_now(SLEEPTIME_ms, pin_wake=False)
Пример #5
0
def main():
    module = xbee.XBee()

    # Idle the radio. While the radio is idled, the radio cannot receive
    # transmissions and current draw is reduced.
    xbee.idle_radio(True)

    # register handle_rx_packet to be called whenever a packet is received.
    xbee.receive_callback(handle_rx_packet)

    # Send transmissions to the address configured by DH/DL
    dest_addr = xbee.atcmd("DH") + xbee.atcmd("DL")

    samples = []
    # Since this application spends most of its time asleep, stopping
    # the application through the UART can be difficult. To make the
    # example easier to work with, it will only run for about a minute
    # instead of indefinitely.
    for _ in range(12):
        # Sleep for 5 seconds
        module.sleep_now(5000)

        # Upon waking, take a sample
        sample = read_sensor()
        samples.append(sample)
        print("  Sample: {}".format(sample))

        if len(samples) == 4:
            # Once we have four samples, Send the samples to
            # the coordinator. Note that we don't have to call
            # xbee.idle_radio(True) to be able to do this--the radio is
            # enabled just long enough to send the transmission.
            print("Transmit samples: {}".format(samples))
            xbee.transmit(dest_addr, str(samples))

            # Clear the stored samples
            samples.clear()

            # If the server is ever going to send transmissions to the
            # end device, the end device needs to enable the radio at
            # some point, and the server needs to know when that is. For
            # this example, that is achieved by leaving the radio on for
            # 1 second after transmitting a sample. If this end device
            # never needs to receive transmissions, this can be left
            # out.
            print("Enable the radio for a bit to receive transmissions...")
            xbee.idle_radio(False)
            # Wait 1 second with the radio enabled. This is the only
            # time the radio can receive transmissions.
            time.sleep(1)
            print("Disable the radio again")
            xbee.idle_radio(True)

    print("Example complete, re-enabling radio")
    xbee.idle_radio(False)
Пример #6
0
 def __init__(self, port, baude_rate, node_identifier):
     try:
         ser = serial.Serial(port, baude_rate)
         self.xbee = xbee.XBee(ser, escaped=True)  #API 2
         self.node_identifier = node_identifier
         self.current_frame_id = 0
         self.end_node_counter = 0
         self.base_end_node_identifier = "END DEVICE"
     except Exception as e:
         logging.critical(e)
         # "\nProgram will now exit"
         exit(2)
Пример #7
0
def main():
    module = xbee.XBee()

    # Wait until the module has joined a network before starting
    ai = xbee.atcmd("AI")
    while ai != 0:
        print("Waiting to join a network, AI=%x" % ai)
        time.sleep(1)
        ai = xbee.atcmd("AI")

    # Put the radio to sleep. Note that by doing so the MicroPython
    # application assumes the responsibility of fequently calling poll_now()
    # or data sent to this device may be lost.
    xbee.idle_radio(True)

    # register handle_rx_packet to be called whenever a packet is received.
    xbee.receive_callback(handle_rx_packet)

    samples = []
    # Since this application spends most of its time asleep, stopping
    # the application through the UART can be difficult. To make the
    # example easier to work with, it will only run for about a minute
    # instead of indefinitely.
    for _ in range(12):
        # Sleep for 5 seconds
        module.sleep_now(5000)

        # Upon waking, take a sample
        sample = read_sensor()
        samples.append(sample)
        print("  Sample: {}".format(sample))

        if len(samples) == 4:
            # Once we have four samples, Send the samples to
            # the coordinator. Note that we don't have to call
            # xbee.idle_radio(True) to be able to do this--the radio is
            # enabled just long enough to send the transmission.
            print("Transmit samples: {}".format(samples))
            xbee.transmit(xbee.ADDR_COORDINATOR, str(samples))

            # Clear the stored samples
            samples.clear()

            # We need to call poll_now() periodically to check for incoming
            # messages, so do that now.
            xbee.poll_now()
            # handle_rx_packet() is registered as the receive callback, so
            # it will be called automatically if the poll comes back with
            # any data.

    print("Example complete, re-enabling radio")
    xbee.idle_radio(False)
Пример #8
0
 def _connect(self):
     ''' Establish XBee serial connection '''
     try:
         self._serial = serial.Serial(self.serial_port, self.baud_rate)
         self._logger.debug('Establish serial connection with XBee'
                            ': {}'.format(self.serial_port))
         try:
             self._xbee = xbee.XBee(self._serial,
                                    callback=self._callback,
                                    escaped=True,
                                    error_callback=self._error_callback)
         except:
             # xbee on pypi does not have error_callback
             self._xbee = xbee.XBee(self._serial,
                                    callback=self._callback,
                                    escaped=True)
             self._logger.exception(
                 'XBee connection established but the xbee library on pypi'
                 ' does not have error_callback. For improved performance,'
                 ' try using http://github.com:neutralio/python-xbee.git')
         self._reconnect_delay = 1
     except:
         self._logger.exception('Failed to establish XBee connection')
         self._reconnect()
Пример #9
0
def main():
    j = js.JS(reactor)
    sdgps_protocol = yield endpoints.TCP4ClientEndpoint(
        reactor, "localhost", 1234).connect(
            deferral.AutoServerFactory(lambda addr: sdgps.SDGPSProtocol()))
    xb = yield xbee.XBee(
        reactor,
        '/dev/serial/by-id/pci-Prolific_Technology_Inc._USB-Serial_Controller_D-if00-port0',
        230400)

    while True:
        #for k in j.state.value[0]:
        #    print k, j.state.value[0][k].value
        #print j.state.value[1]

        if sdgps_protocol.last_imu is not None:
            print sdgps_protocol.last_imu.timestamp
            w = (
                sdgps_protocol.last_imu.angular_velocity[1],
                -sdgps_protocol.last_imu.angular_velocity[0],
                sdgps_protocol.last_imu.angular_velocity[2],
            )
            print w

        if not j.state.value[1][288] or sdgps_protocol.last_imu is None:
            stop = 1
            z, tx, ty, tz = 0, 0, 0, 0
        else:
            stop = 0

            dwx = (j.state.value[0][0].value - 550) / (842 - 550) * 3
            dwy = -(j.state.value[0][1].value - 511) / (873 - 511) * 3
            dwz = -(j.state.value[0][5].value - 130) / (210 - 130) * 3
            tx = 0.5 * (dwx - w[0])
            ty = 0.5 * (dwy - w[1])
            tz = 0.5 * (dwz - w[2])
            print dwx, dwy, dwz
            print tx, ty, tz
            print reactor.seconds()
            print
            z = (j.state.value[0][6].value - 189) / (42 - 189) * (4.6 * 6)

        data = struct.pack('<B4f', stop, z, tx, ty, tz)
        xb.transmit(data)
        yield deferral.sleep(.01 + .00015 * len(data))
Пример #10
0
def setup():
    client_id = "solar-panel-1"
    get_device_id_at_command = "MY"
    print('Initializing')
    device = xbee.XBee()
    print('Created device')
    device_id = device.atcmd(get_device_id_at_command)
    print('Create connection manager')
    connection_manager = Connection()
    print('create cell connection')
    connection_manager.create_cellular_connection()
    print('create mqtt')
    mqtt_connection = connection_manager.create_mqtt_connection(client_id)
    print('create solar panel')
    solar_panel = SolarPanel(device_id, mqtt_connection)
    print('create user interface')
    application = Application(solar_panel, uart)
    print('try start Application')
    application.start()
Пример #11
0
def demo_prohibit_sleep():
    '''
    Prevent the XBee from going into sleep mode using the wake_lock
    Good for protecting critical sections of MicroPython code.
    https://www.digi.com/resources/documentation/digidocs/90002219/#reference/r_sleep_at_cmds.htm
    '''
    print("Starting prohibit sleep demo.")

    from machine import Pin
    import time
    import xbee

    led = Pin("D5", Pin.OUT, value=0)
    xb = xbee.XBee()

    with xb.wake_lock:  # Ensure that we cannot be interrupted with sleep in the middle of this.
        while True:
            time.sleep_ms(100)
            led.toggle()
Пример #12
0
        "?": "^Commands^",
        "Check Can".lower().strip(): "Can Check Complete",
        "Pull Sample 1".lower().strip(): "Done Pulling from solenoid 1",
        "Pull Sample 2".lower().strip(): "Done Pulling from solenoid 2",
        "Reset".lower().strip(): "Resetting Pump system",

    }
    print(switcher.get(string, "Invalid command message"))
    return switcher.get(string, "Invalid command message")
    # This sets up a Dictionary based on {Received message: Sent message, etc.}
    # If the command is a valid command it will send back the 2nd response, but otherwise it will
    # send back "Invalid Command Message"
    # Check if the XBee has received any SMS.


xb = xbee.XBee()  # Initializes an Xbee object that can control internal functions of the Xbee


def shutdown():
    # when a switch (TBD) is hit, put the machine into sleep for 50 secs to that shutdown
    # is safe and the module is not damaged
    xb.sleep_now(50000, True)


def command_list(comm):
    global Pump_time
    global data
    data = t_split(comm)
    print(data)
    if comm.lower().strip() == "?":
        return 0
Пример #13
0
TARGET_64BIT_ADDR = b'\x00\x00\x00\x00\x00\x00\x00\x00'
MESSAGE = ""
sleep_ms = 0
sampleRate = 60000  #milli-seconds
separator = " | "

# XBee hardware managed i2c
i2c1 = I2C(1, freq=400000)
i2c1.scan()

sleep(5)  # delay after boot to allow radio to join network

while True:
    bme = BME280.BME280(i2c=i2c1)

    temp = bme.temperature
    hum = bme.humidity

    voltage = str(xbee.atcmd("%V") / 1000)

    MESSAGE = str(temp) + separator + str(
        hum) + separator + voltage + separator + str(sampleRate / 1000)
    print(MESSAGE)

    try:
        xbee.transmit(TARGET_64BIT_ADDR, MESSAGE)
    except Exception as e:
        print("Transmit failure: %s" % str(e))

    sleep_ms = xbee.XBee().sleep_now(sampleRate, pin_wake=False)
    #sleep(2)
Пример #14
0
#  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
#  on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
#  for the specific language governing permissions and limitations under the License.
#
#  Change History:
#
#    Date        Who            What
#    ----        ---            ----
#    2019-05-21  Daniel Terryn  Original Creation
#
#
import xbee
import time
import binascii
import sys
x = xbee.XBee()  #Create an XBee object
while True:
    voltage = x.atcmd('%V')
    print("Voltage at " + str(voltage))
    tx_req = ("7E" + "00" + "05" + "2D" + "01" + str(voltage))
    try:
        xbee.transmit(xbee.ADDR_COORDINATOR, binascii.unhexlify(tx_req))
    except:
        print(
            "Error occured to send package, probably not connected to ZigBee network"
        )
    print("going to sleep now")
    time.sleep_ms(60000)
    if x.wake_reason() is xbee.PIN_WAKE:
        print("woke early on DTR toggle")
        sys.exit()
Пример #15
0
import xbee
import serial
import time


ser = serial.Serial('/dev/ttyUSB0', 9600)


# data is returned as a list of dictionaries
def handle_message(data):
	"Called whenever the XBee receives data. Async is lit"
	print(data)


# Use an XBee 802.15.4 device
xbeeInst = xbee.XBee(ser, callback=handle_message)



while True:
	try:
		echo = input()
		xbeeInst.send(echo, frame='A', command='MY', parameter=None)
		time.sleep(0.01)
	except KeyboardInterrupt:
		break


xbeeInst.halt()
ser.close()
Пример #16
0
import serial


class Serial(serial.Serial):
    def write(self, *kwargs):
        print kwargs
        print "wrote to serial"
        super(Serial, self).write(*kwargs)


import xbee
import sys

if __name__ == "__main__":
    ser = Serial(sys.argv[1], timeout=0, baudrate=230400)
    xb = xbee.XBee(ser)
    xb.tx(dest_addr='\x00\x15', data="HELLO")
Пример #17
0
def main():
    xb = yield xbee.XBee(reactor, '/dev/ttyO0', 230400)

    polar = lambda r, theta: r * numpy.array(
        [math.cos(theta), math.sin(theta), 0])
    thrusters = [
        Thruster(Motor('/sys/devices/ocp.2/pwm_test_P8_13.11'),
                 polar(.319, math.radians(30 + 60 * 0)), numpy.array([0, 0,
                                                                      1]),
                 numpy.array([0, 0, -0.1])),
        Thruster(Motor('/sys/devices/ocp.2/pwm_test_P8_19.12'),
                 polar(.319, math.radians(30 + 60 * 1)), numpy.array([0, 0,
                                                                      1]),
                 numpy.array([0, 0, +0.1])),
        Thruster(Motor('/sys/devices/ocp.2/pwm_test_P9_14.13'),
                 polar(.319, math.radians(30 + 60 * 2)), numpy.array([0, 0,
                                                                      1]),
                 numpy.array([0, 0, -0.1])),
        Thruster(Motor('/sys/devices/ocp.2/pwm_test_P9_16.14'),
                 polar(.319, math.radians(30 + 60 * 3)), numpy.array([0, 0,
                                                                      1]),
                 numpy.array([0, 0, +0.1])),
        Thruster(Motor('/sys/devices/ocp.2/pwm_test_P9_29.15'),
                 polar(.319, math.radians(30 + 60 * 4)), numpy.array([0, 0,
                                                                      1]),
                 numpy.array([0, 0, -0.1])),
        Thruster(Motor('/sys/devices/ocp.2/pwm_test_P9_31.16'),
                 polar(.319, math.radians(30 + 60 * 5)), numpy.array([0, 0,
                                                                      1]),
                 numpy.array([0, 0, +0.1])),
    ]

    wrench_from_forces = numpy.array([
        numpy.concatenate([
            thruster.direction,  # force = direction * effort
            numpy.cross(thruster.position, thruster.direction) + thruster.
            torque_per_force,  # torque = (position X direction + torque_per_force) * effort
        ]) for thruster in thrusters
    ]).T

    semiwrench_from_forces = wrench_from_forces[2:6]
    forces_from_semiwrench = numpy.linalg.pinv(semiwrench_from_forces)

    while True:
        try:
            packet, = yield deferral.wrap_timeout(
                xb.packet_received.get_deferred(), .1)
        except deferral.TimeoutError:
            stop = True
        else:
            stop, z, tx, ty, tz = struct.unpack('<B4f', packet['data'])

        if stop:
            for thruster in thrusters:
                thruster.motor.set_pwm(STOP_PWM)
            continue

        forces = map(float, forces_from_semiwrench.dot([z, tx, ty, tz]))
        for thruster, force in zip(thrusters, forces):
            force = min(max(force, MIN_FORCE), MAX_FORCE)
            pwm = math.sqrt(
                (force - MIN_FORCE) /
                (MAX_FORCE - MIN_FORCE)) * (MAX_PWM - MIN_PWM) + MIN_PWM
            thruster.motor.set_pwm(pwm)
Пример #18
0
try:
    print('Scanning sensors...')
    i2c = machine.I2C(1)
    i2c.scan()
    WHO_AM_I = i2c.readfrom_mem(104, 0, 1)
    TEMP_DIS = i2c.readfrom_mem(12, 3, 1)
    i2c.writeto_mem(104, 6, b'\x01')
    sensor = True
except:
    print('Sensor is not available')

while registration_loaded:
    try:
        if reconnect:
            x = xbee.XBee()
            x.atcmd('NR')  # will experiment with this later
            c = network.Cellular()
            c.active()
            networkcount = 0
            while not c.isconnected():
                time.sleep(10)
                networkcount = networkcount + 1
                print('Waiting for cellular network.. ' + str(networkcount))

            print('Connected to network')
            imei_number = c.config('imei')
            print('IMEI: ' + str(imei_number))

            # start load creds
            if creds_fn not in os.listdir():
            # Evaluate ambient light in area
            light_average += light_sensor.read()

        sw_bit_0 = Pin("P0", Pin.OUT)
        sw_bit_1 = Pin("P1", Pin.OUT)

        # Sleep duration evaluation
    sleep = SLEEP_DURATION
    if ambiance > LOW_LIGHT_THRESH or battery < LOW_VOLT_THRESH:
        sleep = SLEEP_DURATION * SLEEP_MULTIPLIER
        print("Sleep duration increased to {}ms".format(sleep))

        # Deep sleep or wait if sleep switch is closed
    tilt_switch = Pin("D8", Pin.OUT)
    if sleep_enable.value():
        print("Goodnight!")
        sleep_enable = Pin("P2", Pin.OUT)
        xbee.XBee().sleep_now(sleep, pin_wake=False)
        while xbee.atcmd("AI") != 0:
            time.sleep_ms(100)

    else:
        print("Waiting...")
        sleep_enable = Pin("P2", Pin.OUT)
        time.sleep_ms(sleep)
        while xbee.atcmd("AI") != 0:
            time.sleep_ms(100)

    tilt_switch = Pin("D8", Pin.IN, Pin.PULL_DOWN)
    sleep_enable = Pin("P2", Pin.IN, Pin.PULL_DOWN)
Пример #20
0
def power_test():
    '''
    Puts the XBee3 into sleep mode for a short amount of time, sends an HTTP request, then puts the device back to sleep.
    Then we can hook up some hardware instrumentation in order to measure both the quiescent power consumption (sleeping)
    as well as maximum power consumption (cellular transmitting).
    '''

    print("Launching power test.")

    from machine import Pin
    import network
    import time
    import urequests
    import xbee

    cell = network.Cellular()
    led = Pin("D5", Pin.OUT, value=0)
    xb = xbee.XBee()

    while True:

        # Put the XBee to sleep. Turn off the LED first to indicate that we're going to sleep.
        led.value(0)
        SLEEPTIME_ms = 30000
        print("Going to sleep for %s seconds." % str(SLEEPTIME_ms / 1000.0))
        xb.sleep_now(
            SLEEPTIME_ms, pin_wake=False
        )  # Execution blocks here for the specified time. Device goes into low power mode (NOT the same as time.sleep() which sleeps the thread!)

        # Now the device is awake.
        with xb.wake_lock:

            # Blink the LEDs for 2 seconds to indicate that we've woken up.
            print("Woke up!")
            for _ in range(20):
                led.toggle()
                time.sleep_ms(100)

            # Hold on the LED to indicate we're getting ready to transmit.
            led.value(1)
            time.sleep_ms(1000)

            # Attempt to establish cell connection.
            print("Checking for cell connection.")
            print("Is active (not airplane mode)? %s" % cell.active())
            for _ in range(600):
                print(".", end="")
                if cell.isconnected():
                    break
                time.sleep_ms(100)

            if not cell.isconnected():
                print("Unable to get cell connection.")
                for _ in range(8):
                    led.toggle()
                    time.sleep_ms(500)
                continue

            # Cell connection was successful!
            print("Got cell connection!")
            print(cell.ifconfig())
            print("SIM:", cell.config('iccid'))
            print("IMEI:", cell.config('imei'))
            print("Provider:", cell.config('operator'))
            print("Phone #:", cell.config('phone'))
            print("Cell signal strength: %s" % xbee.atcmd('DB'))

            # Transmit an HTTP request.
            try:
                r = urequests.get("http://api.ipify.org/")
                print("HTTP response: %s, %s" % (r.status_code, r.text))
            except Exception as ex:
                print("HTTP request failed. Exception: %s" % ex)
Пример #21
0
# including any location comparisons.  These are out of scope
# for this device.
#

# configuration
sleep_in_minutes = 1
gps_reads = 10

# TODO:
#   - possibly wake to a low-powered/airplane mode? then enable
#     the cellular modem when ready to send. this can save bat
#     time as the GPS can take some time to get a stable lock.
#

# to keep things on the heap, we'll define vars globally
xb = xbee.XBee()
readings = {}
location = {}

while True:
    global readings
    global location

    with xb.wake_lock:
        readings = sensors.read(xb)
        print("readings: " + readings)

        #location = gps.read(xb, gps_reads)
        #print("location: " + location)

        #modem.send(xb, location, readings)
Пример #22
0
 def start(self):
     self.xbee = xbee.XBee(self.ser, callback=self.recv_data)