262 Commits
Author SHA1 Message Date
Kevin O'Connor fc0e016a6d docs: Note version 0.5.0 release
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-25 11:27:20 -04:00
Kevin O'Connor f5c0148665 config: Warn Beaglebone PRU users that pinmux settings are not updated
The Beaglebone hardware prevents the PRU from updating the pinmux
board settings.  As a result, the PRU can't directly change the pin
direction or change the pullup resistor settings.  Warn the Beaglebone
users of this limitation.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-25 11:01:36 -04:00
Kevin O'Connor 3d78a99758 docs: Update Installation document to recommend latest octoprint version
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-25 10:44:49 -04:00
Kevin O'Connor 03e97c2d95 linux: Remove unneeded includes from timer.c
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-23 22:20:53 -04:00
Kevin O'Connor eaacb928fc pru: Force load the ADC module during PRU startup
Make sure the ADC module gets loaded during startup - it's normally
loaded by the cape manager eeprom, but there's no harm in requesting
it explicitly.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-18 13:23:10 -04:00
Kevin O'Connor 75ba375b8a pru: Don't reset the ADC reset complete flag if a shutdown occurs
Only set the have_done_reset flag if the reset completes successfully.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-18 13:05:36 -04:00
Kevin O'Connor cbd06f1433 linux: Fix typo causing config_reset to not fully restart
A typo in the code caused the wrong config_reset code to be run.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-15 21:05:08 -04:00
Kevin O'Connor 1c59a0d30a linux: Open watchdog device after console
Only open the watchdog device after the console has been opened.  The
machine should not reboot in the unlikely event the console can't be
opened.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-15 21:05:08 -04:00
Kevin O'Connor d222ec1024 linux: Make sure to close fd on analog/pca9685 init failure
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-14 00:22:21 -04:00
Kevin O'Connor 674f584190 pca9685: Fix missing devices_count increment
The devices_count was not being incremented on each device add.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-13 22:05:19 -04:00
Kevin O'Connor 77fea562c4 clocksync: Start with adjusted_freq of 1.0
Avoid setting adjusted_freq to 0.0 as that can cause divide by zero
failures at startup.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-13 21:07:32 -04:00
Kevin O'Connor e0f275cddf serialhdl: Don't open port at 1200 baud
The 1200 baud trick on the Arduino Due does both a reset and an
erase.  The erase is not desired.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 21:46:09 -04:00
Kevin O'Connor 07a69df62f mcu: Fix command restart
Fix omission in commit f8750b14 that broke restarts via Klipper
command.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 21:43:33 -04:00
Kevin O'Connor f8750b142f klippy: Rework shutdown handling
If an MCU signals a shutdown from the background thread, notify the
main thread and handle the shutdown there.  Dispatch shutdown handling
from the main Printer() class instead of from the Toolhead class.
This simplifies the shutdown logic.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 16:28:53 -04:00
Kevin O'Connor 3033b03789 config: Add generic-melzi.cfg file for Melzi boards
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 12:43:13 -04:00
Kevin O'Connor 3506d1e994 fan: Enable heater_fan objects on an MCU shutdown event
Should the MCU go into an error state, set the heater_fan to
max_power.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 11:59:27 -04:00
Kevin O'Connor 3c4d14bfa9 pca9685: Support default values
Allow the pwm pin to have a non-zero default value.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 11:59:27 -04:00
Kevin O'Connor db97f36631 gpiocmds: Allow the start value for a pin to differ from the default_value
Allow the start value to be different from the default/shutdown value
for the pin.  This will be useful for "heater fans" that should
startup in the off state, and transition to full on in a shutdown
state.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 11:59:27 -04:00
Kevin O'Connor d03cf2b83f adccmds: Continue to query analog inputs after a shutdown
Continue to sample the ADC input pins even if the MCU goes into a
shutdown state.  This enables the printer to continue reporting
temperatures even on an mcu error.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 11:59:27 -04:00
Kevin O'Connor 744c6d114e sched: Don't shutdown on a "timer in the past" if already shutdown
A shutdown will not help if the mcu is already in a shutdown state.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 11:59:27 -04:00
Kevin O'Connor 3b9b4e4d6f endstop: Eliminate end_stop_set_oversample command
Pass the sample_ticks and sample_count parameters directly in the
end_stop_home command instead.  This simplifies the code.

Also, simplify calculation of next wakeup time in
end_stop_oversample_event().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 11:59:27 -04:00
Kevin O'Connor 78ba7064a7 clocksync: Initialize clock_est in connect_file()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 11:59:27 -04:00
Kevin O'Connor cc7c99a4a4 cartesian: Fix min_stop_interval calculation error
It is possible to have an acceleration greater than max_z_accel on
XY+Z moves.  That needs to be taken into account when calculating the
min_stop_interval.  This prevents spurious "No next step" MCU errors.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-12 01:16:11 -04:00
Kevin O'Connor d3eb148cfa docs: Point to beaglebone.md from the main installation document
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-11 21:03:13 -04:00
Kevin O'Connor 00d541b767 docs: Octoprint should not run at a higher priority than Klipper on beaglebone
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-11 20:23:58 -04:00
Kevin O'Connor ecf2596469 gcode: Don't warn on fan not present if input is from a file
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-11 14:28:19 -04:00
Kevin O'Connor 6a2eaeae40 docs: Add mailing list to Contact.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-10 14:24:04 -04:00
Kevin O'Connor ce7cc798dc docs: Add Contact.md file with developer contact information
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-10 12:43:44 -04:00
Kevin O'Connor 0ec7eda11b pins: Add pin mapping for atmega1284p
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-05 16:57:44 -04:00
Kevin O'Connor fb0f344346 avr: Add support for atmega1284p
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-05 13:51:05 -04:00
Kevin O'Connor afac81c161 pru: Update start script to always unbind the PRU before binding it
It appears some versions of Debian will load the PRU with firmware on
boot, so make sure to always deactivate the PRU before attempting to
activate it with new firmware.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-05 13:50:12 -04:00
Kevin O'Connor 5c982c90f3 docs: Add a notch to the default square.stl test object
Place a small notch on one side of the square.  The notch provides
interesting information on the extruder performance, and it makes it
easier to compare with previous prints of the object.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-03 22:08:36 -04:00
Kevin O'Connor 381304aa6f stepper: If homing_endstop_phase is configured, make 0.0 be at a full step
If the stepper phases are known then it is possible to arrange for the
0.0 position to occur at a full step.  On cartesian style printer,
this makes it possible for the Z levels to occur at full steps (which
may help reduce "Z ribbing").

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-03 22:06:51 -04:00
Kevin O'Connor ce9523fb90 gcode: Report the raw MCU position from the M114 command
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-03 22:03:52 -04:00
Kevin O'Connor 06420b0ddf gcode: Carry over #original and #command in get_extended_params()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-02 22:06:43 -04:00
Kevin O'Connor c2e1c53356 clocksync: Implement a floor on the prediction filter
Don't discard samples that are less than 500us from the prediction
regardless of the prediction variance.  Also, don't use the prediction
variance in the external time estimate.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-02 11:00:24 -04:00
Kevin O'Connor eaeb831107 endstop: Fix typo in comment
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-02 11:00:23 -04:00
Kevin O'Connor 459695e9d7 docs: Remove items from Todo.md
Several items were recently implemented.  Remove the "cubic vs
quadratic" item as investigations into cubic compression weren't
promising.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-01 19:34:00 -04:00
Kevin O'Connor ece1f71c64 endstop: Support oversampling of the endstop
Some printers can show occasional noise on the endstop pin.  Support
sampling the endstop pin multiple times to attempt to filter out this
noise.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-10-01 19:15:55 -04:00
Kevin O'Connor 776d8f9f79 clocksync: Update clock synchronization code to use a linear regression
Implement a "moving" linear regression between the reported mcu clock
and the sent_time of the get_status message that generated that
report.  Use this linear regression to make predictions on the
relationship between the system time and the mcu clock.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-30 19:37:37 -04:00
Kevin O'Connor 61ee63f358 serialqueue: Don't report sent_time on responses that are retransmitted
On a retransmit, the sent_time of the command associated with the
given response message isn't accurate.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-30 19:37:20 -04:00
Kevin O'Connor 6f65ba9214 clocksync: Don't update prev_est on min rtt updates
Average frequency changes over the longer interval on a sample that
causes a minimum rtt update.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-28 01:09:18 -04:00
Kevin O'Connor ba837c2641 clocksync: Fix serialqueue.set_clock_est() - don't track min_freq
Revert commit f37fc775.  It is not valid to pass a conservative
frequency to serialqueue.set_clock_est() as that function may not be
called for extended periods - a too low frequency would eventually
lead to "Timer too close" mcu errors.

Instead, increase the 1ms time offset to 5ms to avoid corner cases
that could lead to a message arriving too soon.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-28 00:51:48 -04:00
Kevin O'Connor 1518032606 clocksync: Default mcu_freq to 1 instead of 0
This prevents divide by zero errors during stats output if the stats
are generated before a connection completes.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 20:07:46 -04:00
Kevin O'Connor 6469cce2bc toolhead: Make sure reset_print_time() doesn't go backwards in time
Update the homing code to pass in the start of the homing operation to
toolhead.reset_print_time().  This prevents an error when batch
processing gcode files that contain multiple homing operations.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 19:21:26 -04:00
Kevin O'Connor 4c40b50fb5 docs: Add a section on time handling to Code_Overview.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 15:11:15 -04:00
Kevin O'Connor a0f0911a95 docs: Reword performance paragraph in Features.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 13:59:47 -04:00
Kevin O'Connor f658819862 clocksync: Add support for dumping internal state for debugging
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 13:13:38 -04:00
Kevin O'Connor 8d5a9143bb klippy: Avoid using '%' syntax when calling logging module
The logging module can build strings directly from printf syntax - no
need to build the string first.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 12:38:20 -04:00
Kevin O'Connor 8f8951b4c1 serialhdl: Make dump_debug() output atomic
Build a single (very large) logging message with the debug state.
This prevents the output from being fragmented.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 12:38:20 -04:00
Kevin O'Connor 6e5bcc69bc gcode: Make dump_debug() output atomic
Build a single (very large) logging message with the debug state.
This prevents the output from being fragmented.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 11:58:21 -04:00
Kevin O'Connor 8d04d3d8fd gcode: Exit if a shutdown occurs while running in batch mode
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 10:05:11 -04:00
Kevin O'Connor f37fc775e5 clocksync: Be conservative when setting serialqueue.set_clock_est()
Accuracy is not as important as ensuring a message is never sent
before it can be received in the serialqueue code.  So, use the
smallest frequency ever seen and add the minimum rtt time when setting
set_clock_est().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-27 09:10:41 -04:00
Kevin O'Connor ead99cf647 docs: Update Features.md document for multiple micro-controllers
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-26 22:27:25 -04:00
Kevin O'Connor 3982b5030e serialqueue: Take baud_adjust into account when calculating receive_time
Use baud_adjust when determining the receive_time of a message read
from the serial port.  This improves the accuracy of the clock
synchronization code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-26 22:27:25 -04:00
Kevin O'Connor d9fe4b6944 clocksync: Rework clock synchronization algorithm
Instead of tracking the minimum frequency ever observed, attempt to
track the actual frequency of the micro-controller (relative to the
host clock).  This improves the stability of the secondary mcu clocks
when multiple mcus are configured.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-26 22:27:25 -04:00
Kevin O'Connor 387cab27bd mcu: Separate restart_microcontroller() into multiple functions
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 16:04:41 -04:00
Kevin O'Connor 6dcc44ce2d chipmisc: Add initial support for servos
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 14:21:36 -04:00
Kevin O'Connor 3b4088c23f chipmisc: Add support for Replicape board
Add support for configuring and controlling the hardware specific to
the revision "B3" Replicape board.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 13:18:07 -04:00
Kevin O'Connor 5a85c1667a pru: Update installation and flash scripts
Update the scripts used to install and "flash" the pru
micro-controller code.  Also, add a "flash" script for the linux
micro-controller code.  This makes it easier to install Klipper on a
Beaglebone board that uses a Replicape.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 12:55:28 -04:00
Kevin O'Connor 16d2ec3a90 linux: Add support for analog IIO devices
Add support for reading analog values via the standard Linux IIO
interface.  This can be used on Replicape boards to sample analog
input pins.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 12:55:28 -04:00
Kevin O'Connor 4d60567bc6 linux: Add support for spidev devices
Add support for sending SPI messages to devices via the standard Linux
SPI interface.  This can be used to configure the shift registers on
Replicape boards.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 12:55:28 -04:00
Kevin O'Connor 73a1c9d249 linux: Add support for pca9685 i2c pwm devices
Add support for controlling pca9685 PWM drivers using the standard
Linux I2C interface.  The pca9685 device is found on Replicape boards.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 12:55:28 -04:00
Kevin O'Connor d851882278 linux: Initial support for running Klipper in a Linux real-time process
Add support for compiling the Klipper micro-controller code as a
real-time process capable of running on standard Linux systems.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 12:55:28 -04:00
Kevin O'Connor 3ccecc568d mcu: Initial support for multiple micro-controllers
Add initial support for controlling multiple independent
micro-controllers from a single Klippy host instance.  Add basic
support for synchronizing the clocks of the additional mcus to the
main mcu's clock.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-20 12:45:00 -04:00
Kevin O'Connor cee200e509 mcu: Move code around in MCU class to keep like code together
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:27:18 -04:00
Kevin O'Connor f1b315e04f mcu: Move print_time to clock conversion code to clocksync.py
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:27:18 -04:00
Kevin O'Connor 94bcd9735a mcu: Add mcu wrapper functions and avoid direct acccess to mcu variables
Don't directly access any of the mcu class variables externally from
the class.  Add wrapper functions for those external callers that need
access to some internal state.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:43 -04:00
Kevin O'Connor f662445766 stepcompress: Implement print time to clock conversion in C code
Implement the conversion from print_time to the local mcu's clock
within the C code.  This simplifies the python code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:43 -04:00
Kevin O'Connor 008be18f41 clocksync: Don't export get_last_clock()
Everywhere the data in get_last_clock() is used can be done just as
easily with estimated_print_time().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:43 -04:00
Kevin O'Connor 13812aa1c9 clocksync: Move clock synchronization code into new file
Move the low-level clock synchronization code from serialhdl.py to a
new file clocksync.py.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:42 -04:00
Kevin O'Connor 2089f19670 toolhead: Separate is_active() code from stats() code
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:42 -04:00
Kevin O'Connor 593741919f mcu: Update file purpose comment
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:42 -04:00
Kevin O'Connor 9d0fcca8a9 serialhdl: Reduce calculations done while holding the lock
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:42 -04:00
Kevin O'Connor 857eb01bfa homing: Move query_endstop() code from kinematic classes to homing.py
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:42 -04:00
Kevin O'Connor a100f174f9 mcu: Pass print_time directly to MCU calls
Now that the print_time is always synchronized with the mcu_time,
there is no longer a need to track mcu_time as a separate quantity.
Eliminate references to mcu_time from the code and pass print_time
directly in its place.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:42 -04:00
Kevin O'Connor 5dfe4e1eb9 toolhead: Synchronize print_time to main mcu's time
Instead of starting the print_time at zero, start it at the estimated
time of the main mcu's clock.  This simplifies the code and it ensures
that print_time never goes backwards.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:25:38 -04:00
Kevin O'Connor b9586bad18 mcu: Use is_fileoutput() externally
Use mcu.is_fileoutput() instead of looking up the "debugoutput" flag
in the start args.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:22:29 -04:00
Kevin O'Connor f1c2f789b6 klippy: Do not start stats timer until after connect completes
Generating stats during connect leads to potential use of not yet
initialized variables.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:22:29 -04:00
Kevin O'Connor 123719bf92 stepper: Fix bug causing 'enable_pin' to be required
Make sure to initialize mcu_enable to None so that it is initialized
if no 'enable_pin' config value is provided.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-19 17:20:41 -04:00
Kevin O'Connor 14810d7e80 stepcompress: Return number of steps traveled from stepcompress_push()
Return the same information from stepcompress_push() that is returned
from stepcompress_push_const() and stpcompress_push_delta().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-13 09:24:27 -04:00
Kevin O'Connor 52156d2c41 pins: Don't pass mcu_freq to update_command()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-13 09:16:58 -04:00
Kevin O'Connor 2a6a9eb52f pru: Avoid calling "slp" instruction on pru0
If pru0 waits in sleep mode then a full beaglebone reboot is needed to
reprogram the pru0 firmware.  For now, avoid using the "slp"
instruction as a workaround.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-11 13:12:18 -04:00
Kevin O'Connor bf85c61b48 corexy: Fix max_xy_halt_velocity calculation on corexy
On corexy, the stepper velocity of a diagonal move could be greater
than the maximum printer velocity.  Account for that when setting the
maximum xy halt velocity in the mcu stepper config.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-09 14:45:10 -04:00
Kevin O'Connor dba488f30a extruder: Remove unused set_max_jerk() call
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-08 19:34:30 -04:00
Kevin O'Connor d618affd63 pru: Batch outgoing writes
Allow pru0 to gather multiple outgoing message blocks into a single
rpmsg.  This can reduce communication overhead.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-08 11:50:21 -04:00
Kevin O'Connor 121c747cc8 pru: Fix race condition in clearing of irq flags
Each irq flag must only be cleared after it has been serviced.  This
fixes a race condition that could cause incoming commands to be
delayed for extended period.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-08 11:50:21 -04:00
Kevin O'Connor 91b9634198 serialqueue: Fix off-by-one error in retransmit sequence number tracking
Commit 4655a6bf allowed naks to be honored if receive_seq was greater
than the last retransmitted sequence.  However, receive_seq is the
receiver's next sequence number, so a nak should only be processed if
it is one greater than that.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-08 11:50:21 -04:00
Kevin O'Connor 7d17002b33 fan: Allow heater_fan to work with heater_bed
Fix order of init error preventing heater_fan from being used with
heater_bed.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-07 11:19:27 -04:00
Kevin O'Connor 477b3941a6 console: Add support for SUPPRESS command
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-07 11:19:27 -04:00
Kevin O'Connor 36dd7e7609 console: Add support for a FLOOD command
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-07 11:19:27 -04:00
Kevin O'Connor 167a65d826 util: Fix reporting of git version of klippy code
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-07 11:19:27 -04:00
Kevin O'Connor c9cd8cea66 mcu: Limit value range of PWM and digital outputs prior to transmission
Make sure schedule_digital_out and schedule_pwm_out commands always go
out with a value that is in range for the particular command.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-06 12:04:05 -04:00
Kevin O'Connor dfdcbece53 mcu: Improve error descriptions in Common_MCU_errors
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-06 12:03:49 -04:00
Kevin O'Connor 5b62f15c6d extruder: Provide more details on extruder errors
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-05 22:12:15 -04:00
Kevin O'Connor 09e32d1b84 mcu: Provide some further help on common MCU shutdown errors
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-05 22:12:15 -04:00
Kevin O'Connor 68fc6abf74 avr: Check that FLASH_DEVICE is set on "make flash" command
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-05 22:12:15 -04:00
Kevin O'Connor ff56c0fb74 extruder: Fix typo in init
Commit 7a81bfc4 broke extrude only moves due to a typo in the commit.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-05 22:12:15 -04:00
Kevin O'Connor 36de6118c1 mcu: Limit ADC min/max range to a 16bit integer
Make sure the ADC range sent to the MCU can be encoded into a 16bit
integer.  Otherwise, if the provided min_temp/max_temp was outside the
range of possible values it could result in a spurious mcu shutdown.
In particular, the AD595 could not properly encode a min_temp of zero.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-05 18:22:21 -04:00
Kevin O'Connor 7083a33ecd pru: Support config_reset command to manually reset mcu
Add support for resetting the MCU via a software only mechanism.  This
is useful on the PRU.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-03 23:16:38 -04:00
Kevin O'Connor 7b7f57e01c pru: Only sleep the pru0 if the incoming queue is fully empty
It's possible for multiple blocks to be pending on the incoming
"rpmsg" stream.  Don't sleep unless the input is confirmed to be
empty.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-03 23:15:49 -04:00
Kevin O'Connor 8d0ef49e8f toolhead: Permit look-ahead between Z moves
Extend the look-ahead mechanism to work between moves that contain Z
movement.  This improves Klipper's handling of g-code produced in
"vase mode".

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-03 15:46:48 -04:00
Kevin O'Connor 7a81bfc4a4 toolhead: Eliminate set_max_jerk() from kinematic classes
Allow the kinematic classes to query the max velocity, max accel, and
max halt velocity from the toolhead class instead of having the
toolhead class call into the kinematic classes with those values.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-03 15:45:04 -04:00
Kevin O'Connor 0d13834293 gcode: Fix error that could cause commands to be processed out of order
Commit d0932009 changed the way command handling was performed, and
commit 95950949 fixed a defect in that commit.  Unfortunately, the fix
was incomplete.

If multiple commands were sent to Klippy without waiting for an "ok"
response from Klippy, then it was possible for those additional
commands to be queued and processed after subsequent commands.  This
would result in commands being processed out of order.

Fix this by only reregistering the input fd in the greenlet that
performs the unregistration of the fd.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-02 12:05:51 -04:00
Kevin O'Connor ac53806e04 gcode: Add an ECHO command for debugging purposes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-09-02 12:05:51 -04:00
Kevin O'Connor 026b9c336c stepcompress: Minor performance tweaks for rpi
Invert the if conditional in queue_append() and change the order of
reads in minmax_point() - gcc on the rpi seems to do generate better
code this way.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-31 10:17:01 -04:00
Kevin O'Connor 60c77fff06 docs: Update Code_Overview.md - step compress queue no longer 64 bit
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-31 10:07:17 -04:00
Kevin O'Connor 588ecbe868 stepcompress: Use addition instead of multiplication on queue add
Replace multiplication with addition where possible.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-31 02:15:32 -04:00
Kevin O'Connor e05c635489 stepcompreses: Change the step queue to use 32bit integers
The RaspberryPi processor implements 'double to int32' conversions
much faster than 'double to int64' conversions.  Rework the code so
that steps stored in the queue are always a small offset from the last
sent step time.  (In the unlikely event that a step is far from the
last step time, then the queue is flushed to maintain this invariant.)

This simplifies the step compression code as well - it no longer needs
to check for integer overflows.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-31 00:27:43 -04:00
Kevin O'Connor f5cc355044 stepcompress: Refactor queue insertion to use a cursor
Create an insertion "cursor" for adding items to the step compression
queue.  This makes the calling code simpler and it makes it easier to
update the queue memory management in the future.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-31 00:15:03 -04:00
Kevin O'Connor 78f4c25a14 homing: Add a small delay before each homing operation
The homing operation can be cpu intensive for the host software.  Add
a small (250ms) delay before homing so that the host has additional
time to process the command before it is due on the mcu.  This is
intended to work around some reports of "timer too close" errors
during Z homing on RPi2 hosts and printers with high precision Z
positioning.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-29 18:02:36 -04:00
Kevin O'Connor 002dc0dfaf stepper: Adjust homing_speed so that it's an even number of ticks per step
Adjust the configured homing speed so that it always results in a
speed that is an even number of mcu ticks per step.  This ensures that
the code can always get good step compression during homing, which is
important as the entire homing operation must be able to fit within
the mcu's move queue.  This fixes some "move queue empty" mcu shutdown
errors that could occur when the Z step distance was an unusual size.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-29 18:00:17 -04:00
Kevin O'Connor 68d6788413 mcu: Add get_mcu() call to the mcu oid objects
Allow external code to obtain the mcu object that controls a pin setup
with setup_pin().  Also, don't bother defining print_to_mcu_time() and
system_to_mcu_time() on each pin object as they can be obtained via
the new get_mcu() method.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-29 17:59:27 -04:00
Kevin O'Connor c7c551369f mcu: Fix bug causing corexy to not work (introduced in 9d75c3b0)
Commit 9d75c3b0 changed the order of allocation for mcu oid integer
ids.  However, the stepper oids must always be allocated before
endstop oids so that corexy can register multiple steppers on a single
endstop.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-29 17:59:15 -04:00
Kevin O'Connor 0c2919b534 klippy: Move restart logic into Printer() class
Move the restart logic out of main() and into Printer.run().  This
simplifies the code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-26 18:27:21 -04:00
Kevin O'Connor d8c75fc608 klippy: Rename internal functions so that they are prefaced with "_"
Preface the internal functions to make it more clear which functions
are interfaces to external code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-26 18:27:21 -04:00
Kevin O'Connor a42cb4fecf toolhead: Avoid directly accessing the printer.mcu field
Lookup the mcu object from the printer objects and store it locally in
the toolhead class.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-26 18:27:21 -04:00
Kevin O'Connor 68ba3d5106 mcu: Drop support for TICKS() expansion in mcu config commands
It's no longer necessary to use the TICKS() hack as the config
commands are now all generated after the mcu speed is known.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-26 18:27:21 -04:00
Kevin O'Connor 80dc1dfcc1 docs: Remove documentation for "custom" command blocks
It should no longer be necessary to configure "custom" commands during
mcu setup.  The ad5206 and static_digital_output config sections
should provide similar functionality.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-26 18:27:21 -04:00
Kevin O'Connor 931811ab59 chipmisc: Add support for configuring ad5206 digipots
Support an "ad5206" config section so that one can configure the
digipots found on Reprap "RAMBo" boards.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-26 18:27:21 -04:00
Kevin O'Connor 9d75c3b0ca chipmisc: Add support for statically configured output pins
Allow digital and PWM output pins to be setup via new config
sections.  This makes it easier to setup pin configurations.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-26 18:27:20 -04:00
Kevin O'Connor 6ab8567d51 mcu: Track stepqueues separately from steppers
The MCU() class needs to track the stepqueues so that it can
initialize the steppersync object.  Track the stepqueues directly
instead of via the list of steppers.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-25 20:45:54 -04:00
Kevin O'Connor c727ed3592 mcu: Track oids separately from objects requiring a build_config() callback
Track the oid count separately from the configurable object count -
this way it is possible to have internal objects that don't require an
oid in the mcu.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-25 20:44:51 -04:00
Kevin O'Connor c72ca983ba mcu: Eliminate "init callback" phase during connect
It's not necessary to register and execute "init callbacks" when
configuring the mcu.  Instead, have each mcu object produce its init
messages in the build_config() callback.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-25 20:41:09 -04:00
Kevin O'Connor ec7990796a pins: Support registering arbitrary chips that supply configurable pins
Allow multiple chips to provide pin mappings (not just the main mcu
chip).  Move the pin parsing from the mcu.py code to pins.py and
support mapping from pin descriptions to their corresponding chips and
parameters.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-25 20:38:55 -04:00
Kevin O'Connor 268834e4ae klippy: Store printer startup parameters in new "start_args" dictionary
Store pertinent information from the software startup in a dictionary
that the various printer components can access instead of in
individual variables in the Printer() class.  This makes it easier to
add future command-line options.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-25 19:27:05 -04:00
Kevin O'Connor b80c488d36 heater: Another minor cleanup to Steinhart-Hart math
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-20 12:42:50 -04:00
Kevin O'Connor f25cb33367 heater: Minor cleanup to Steinhart-Hart math
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-18 13:28:04 -04:00
Kevin O'Connor 4b5f3bec4b heater: Add support for a generic "NTC 100K beta 3950" thermistor
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-17 15:12:51 -04:00
Kevin O'Connor 1f4c6443ef heater: Calibrate thermistor directly from temperature and resistance
Store the underlying temperature and resistance values instead of the
Steinhart-Hart coefficents obtained from them.  This makes it easier
to add new thermistors.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-17 13:26:51 -04:00
Kevin O'Connor 0adea120cd pru: Compile the irq_poll() function with -O2 optimization
Compile the PRU binary with -Os optimization, but request that the
timer dispatch code be compiled with -O2 optimization.  This improves
the performance of timers slightly.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-15 11:05:30 -04:00
Kevin O'Connor 71bb7acb8e pru: Compile with -Os instead of -O2
The gcc -Os option significantly reduces the size of the PRU binary
and it has little impact on performance.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-14 21:08:28 -04:00
Kevin O'Connor 4b5109c1b9 serialqueue: Make sure fds are in non-blocking mode
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-14 21:08:28 -04:00
Kevin O'Connor 085817d332 serialhdl: Sometimes we get an IOError when serial port not found
Catch IOError when opening the serial port.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-14 21:07:26 -04:00
Kevin O'Connor f8bd8b97be command: Don't pass max_size to command_encodef()
The command_encodef() can read the max_size parameter directly from
the 'struct command_encoder' passed into it.  Also, there is no need
to check that a message will fit in a buffer if the buffer is declared
to be MESSAGE_MAX in size.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-14 18:32:15 -04:00
Kevin O'Connor f3da473285 docs: Update Code_Overview.md with PRU and command_dispatch() changes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-11 12:06:19 -04:00
Kevin O'Connor f0f4ab7abe docs: Update benchmarks in Features document
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-11 11:40:54 -04:00
Kevin O'Connor d8225642fa stepper: Revert f8b0c884
Go back to scheduling the unstep time instead of busy waiting in the
timer dispatch.  With the unstep time increased to 2us, it no longer
makes sense to spin while waiting for the unstep.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-11 10:36:02 -04:00
Kevin O'Connor 8ebba6d27a avr: Make sure timer_high and timer_event() stay in sync
Schedule the next wakeup time of timer_event() using timer_high.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-11 09:32:06 -04:00
Kevin O'Connor 1051a52755 timer_irq: Rework timer irq handler to check for tasks pending
Allow timer_dispatch_many() to run for extended periods if there are
no tasks pending.  This reduces the amount of lost cpu time spent
entering and exiting the irq handler.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-09 21:08:40 -04:00
Kevin O'Connor 5583b050a0 graphstats: Increase maximum expected task duration
Now that tasks are only run when needed it's common for there to be a
larger variation in task execution time.  When graphing load, consider
a 99-percentile task duration of 2.5ms to be 100% loaded (up from
1ms).

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-09 19:12:27 -04:00
Kevin O'Connor a38082016d sched: Reduce the amount of time irqs are disabled in sleep check
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-09 12:55:44 -04:00
Kevin O'Connor 156e9b7556 sched: Write out a message on startup
Send a "startup" message after completing the mcu init functions.
This may help detect mcu reboots during debugging.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor 5e6acf7dbc console: Add support for a STATS command
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor 58811b5c44 console: Add LIST command that shows available commands and variables
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor 86a762b2b7 console: Add a HELP command
Show available features at startup.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor f886212b44 avr: Rework timer irq handler to check for tasks pending
Allow the timer dispatch irq handler to run for extended periods if
there are no tasks pending.  This reduces the amount of lost cpu time
spent entering and exiting the irq handler.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor 2c272f99a3 sched: Implement generic sleep mechanism based on tasks pending
Track when tasks are pending and spin in irq_wait() when no tasks are
pending.  This improves the mechanism for sleeping the processor -
it's simpler for the board specific code and it reduces the
possibility of the processor sleeping when tasks are busy.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor a9982beacf sched: Introduce sched_wake_tasks() function to wake up tasks
Add function to indicate when tasks need to be run.  This will allow
the scheduler code to know if there are any tasks that need to be
processed.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor e9d2ec7c41 avr: Tune the low-level timer entry and exit heuristics
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor 78982ebb51 avr: Implement internal avr specific timer to handle 16bit overflows
Don't rely on the generic scheduler code to always have a timer no
more than 1ms in the future.  Instead, create an avr specific timer
that will be called every 0x8000 ticks.  This simplifies the generic
code and it reduces the amount of code that needs to be run every
millisecond.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:28 -04:00
Kevin O'Connor 6a63c27542 sched: Support adding timers to the start of timer_list
If sched_add_timer() is called on a timer that would make it the new
head of the list, then add it and signal the board code that the timer
should be rescheduled.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:27 -04:00
Kevin O'Connor 62f77f6bc5 sched: Don't count milliseconds in the periodic timer
It's not necessary to keep a millisecond counter.  Replace the two
users of sched_check_periodic() with explicit task wakeup flags.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:27 -04:00
Kevin O'Connor 88a10fb31c sam3x8e: Fix watchdog timeout calculation
Fix error causing the watchdog to be set to an ~4ms timeout instead of
500ms.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-08 00:27:27 -04:00
Kevin O'Connor e12527b895 avr: Move prescaler and sleep initialization from timer.c to main.c
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-07 19:39:57 -04:00
Kevin O'Connor 114c8c5b6d avr: Enable watchdog code even on simulavr
The simulavr simulator will warn when writing to the watchdog
registers, but running code closer to what real hardware runs is worth
a few extra warnings.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-07 19:39:57 -04:00
Kevin O'Connor d50f4e23e0 pwmcmds: Update event prototypes to use uint_fast8_t
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-06 20:24:22 -04:00
Kevin O'Connor dca0fc91ea pru: Improve comments in pru0.c
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-08-02 11:02:45 -04:00
Kevin O'Connor 981c53682f stepper: Use a sane default for homing_positive_dir
Use the endstop position to determine a sane default for
homing_positive_dir.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-24 14:31:46 -04:00
Kevin O'Connor 143b7cccf4 stepper: Separate out homing code to its own PrinterHomingStepper class
Keep the homing code separate from the main stepper class.  This makes
it easier to verify the correct config parameters are provided.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-24 13:54:46 -04:00
Kevin O'Connor 8ce042bf04 config: Add additional pin definitions to ramps and rambo configs
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-24 13:18:45 -04:00
Kevin O'Connor 85a1e1118f config: Change default pins defined in example.cfg to use RAMPS pins
Change the example.cfg file to use the pins of a RAMPS config as that
is a very common setup.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-24 13:05:00 -04:00
Kevin O'Connor 51baeb3c2c config: Reduce max_z_velocity in example-delta.cfg to 150
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-24 11:47:25 -04:00
Kevin O'Connor 959a20888c serialhdl: Dump serial stats in dump_debug()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-24 11:43:54 -04:00
Kevin O'Connor 7bf0ec2fe7 gcode: Don't wait for moves to finish if both debug input and output
Don't wait for moves to finish if the output is going to a debug file.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-23 21:32:26 -04:00
Kevin O'Connor c6231a16e3 serialqueue: Improve limit on number of in-flight bytes
Instead of limiting the amount of non-acked messages to 50ms, limit
the amount to one round-trip-time.  This should make it less likely
that the mcu will be overloaded and it should make retransmits faster.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-23 20:47:08 -04:00
Kevin O'Connor a619aacfc6 serialqueue: Further retransmit timing fixes
The first message always has a sync byte with it, so its size should
be one larger.  Also, the idle_time should always be the minimum time
that the message could be received, so it should always be reset to
eventtime on a retransmit.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-23 19:32:42 -04:00
Kevin O'Connor d469db84ee serialqueue: Allow a second nak after a retransmit
If a nak message causes a retransmission then also accept a second nak
message as long as it is for a sequence greater than the first nak.
This should allow faster retransmits when there are multiple
transmission errors in a small time period.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-21 23:49:44 -04:00
Kevin O'Connor 4655a6bfef serialqueue: Fix off-by-one error in retransmit sequence number tracking
Track the sequence number of the message last retransmitted (not the
sequence number of the next message to be transmitted).  This fixes a
small possibility of a valid nak not being honored.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-21 23:43:48 -04:00
Kevin O'Connor 61325c0a14 serialqueue: Improve timing of multiple retransmits
If a retransmit is triggered by a nak, then it is not necessary to
increase the rto.  The next retransmit time should be based on the
expected reception of the first retransmitted message, not the last.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-21 21:26:14 -04:00
Kevin O'Connor 7faa5fe233 gcode: Improve end-of-file handling when input is a debug file
Wait for any pending moves to be fully handled before exiting.  Make
sure the wait is done inside the "self.is_processing_data" check to
avoid infinite recursion.  Don't keep reading from the file while
waiting to exit.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-21 21:22:12 -04:00
Kevin O'Connor 19090bdd5b graphstats: Fix so that older files (predating mcu_awake) still work
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-21 14:19:59 -04:00
Kevin O'Connor 4a6254fac3 build: Allow boards to disable digital input/output support
Allow the micro-controller code to be built without support for
regular gpio pins.  In this case, the code for endstops, steppers, and
gpiocmds will be disabled.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-20 10:44:31 -04:00
Kevin O'Connor 649d26e093 basecmd: Move low-level alloc code into basecmd.c
Implement new dynmem_start() and dynmem_end() functions instead of
alloc_chunk() and alloc_chunks() in the board code.  This simplifies
the board code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-20 10:44:31 -04:00
Kevin O'Connor 2ee42997e4 docs: Update Kinematics.md with regards to stepper torque limits
It is not necessary to limit stepper acceleration - only the limiting
of stepper torque is important.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-19 19:09:14 -04:00
Kevin O'Connor 17a3e25036 docs: Improve description of delta stepper acceleration limits
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-19 14:14:01 -04:00
Kevin O'Connor c4b8d3ea8b graphstats: Support graphing "mcu_awake" statistic
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-19 14:14:01 -04:00
Kevin O'Connor 118fd21cb8 irq: Support sleeping when mcu is idle
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-17 15:02:43 -04:00
Kevin O'Connor 969485c754 fan: Add support for heater_fan objects
Add support for fans designed to cool the components of an extruder or
heater.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-17 11:35:52 -04:00
Kevin O'Connor 519e81d0fa mcu: Support converting from a system time to an mcu time
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-17 11:35:48 -04:00
Kevin O'Connor 12ca45a264 gcode: Log g-code error responses
Be sure to log g-code errors even if debug logging is not enabled.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-17 11:24:15 -04:00
Kevin O'Connor 3ac60b31a2 pru: Move peripheral init from pru0 to pru1
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-17 11:16:55 -04:00
Kevin O'Connor c105ff1c51 pru: Move ADC code from gpio.c to new file adc.c
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-12 23:03:14 -04:00
Kevin O'Connor ae9bc93ccc avr: Fix readl() typo in serial.c
The code should have used a readb() call instead of readl().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-12 23:03:12 -04:00
Kevin O'Connor afc665d7c8 config: Update PRU based configs to use the correct serial device
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-06 12:04:26 -04:00
Kevin O'Connor 2d173f51b1 pru: Add documentation and install scripts for running on the PRU
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-05 14:21:32 -04:00
Kevin O'Connor b32ba3727b pru: Add support for "make flash" rule
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-05 12:50:54 -04:00
Kevin O'Connor 5793271308 fan: Support setting a max_power attribute for the print cooling fan
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-05 10:43:34 -04:00
Kevin O'Connor 09140a51d5 sched: Pass shutdown reason code via longjmp() parameter
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-04 12:49:58 -04:00
Kevin O'Connor cf662b842b msgproto: Catch exceptions during identify data parsing
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-04 12:49:58 -04:00
Kevin O'Connor 0ac518040b msgproto: Export static_strings from mcu to host as a dictionary
Export the static strings as a dictionary instead of as a list.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-07-02 14:11:10 -04:00
Kevin O'Connor 067fac05a8 serialqueue: Rename clock estimation variable names
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-30 20:15:36 -04:00
Kevin O'Connor c7d0358c41 serialhdl: Rework mcu clock synchronization
The existing clock synchronization code has two flaws: intermittent
transmission latency during get_status requests can cause the
estimated clock to be too low, and the estimated clock calculation did
not take into account possible clock drift between samples.  The
former could potentially lead to "Timer too close" errors and the
latter could potentially lead to "Move queue empty" errors.

Rework the code to avoid the above problems.  It's not necessary to
estimate the micro-controller clock as an excellent estimate is
reported by the micro-controller (via the CLOCK_FREQ constant).
Account for a small drift from the reported value, and check on each
sample if the drift exceeds the expected limits.  With a good starting
estimated clock, only the offset needs to be calculated.  Use previous
offsets (and the estimated clock) in calculation of new offsets to
avoid intermittent latency from badly skewing the results.  Finally,
add an additional time offset of one millisecond to account for any
minor inaccuracies.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-30 20:15:36 -04:00
Kevin O'Connor c957e4ba86 serialqueue: Clarify code that associates sent messages to received messages
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-30 20:15:36 -04:00
Kevin O'Connor c8dca0a56c pru: Use a pointer when working with send_data array items
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-30 19:54:40 -04:00
Kevin O'Connor da3569c490 pru: Add hack to shutdown the PRU from a simple command request
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-30 19:54:33 -04:00
Kevin O'Connor e8356afa26 pru: Rework command processing so that most of it is done on pru0
Change the command dispatch and response generation so that most of
the work is done on pru0 instead of pru1.  This allows more code to
fit into the limited space on pru1.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-30 19:53:04 -04:00
Kevin O'Connor c1bd628ce5 command: Directly call command_sendf() for ack/nak messages
Don't use the sendf() macro for ack and nak messages - directly call
the command_sendf() code instead.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:59 -04:00
Kevin O'Connor 849096d5f3 sam3x8e: Integrate serial console functions
Now that console_get_input(), console_pop_input(),
console_get_output() and console_push_output() are local functions,
integrate them into their callers.  This simplifies the code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:59 -04:00
Kevin O'Connor e681369a1a avr: Integrate usb serial console functions
Now that console_get_input(), console_pop_input(),
console_get_output() and console_push_output() are local functions,
integrate them into their callers.  This simplifies the code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:59 -04:00
Kevin O'Connor faa29c8062 avr: Integrate serial console functions
Now that console_get_input(), console_pop_input(),
console_get_output() and console_push_output() are local functions,
integrate them into their callers.  This simplifies the code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:58 -04:00
Kevin O'Connor 44f2a2a952 command: Move low-level sendf transmission into board code
Export a new console_sendf() function from the board code instead of
console_get_output() and console_push_output().  This enables more
flexibility in how the board specific code produces output.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:58 -04:00
Kevin O'Connor 292453d306 command: Move command_task() to board specific code
Move the command_task() code from the generic code to the board
specific code.  This enables more flexibility in how the board
specific code processes input.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:58 -04:00
Kevin O'Connor 1ae78d08e9 command: Encode MESSAGE_MIN in command_parser->max_size
Add the message minimum into the stored constant so it does not need
to be added at run-time.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:58 -04:00
Kevin O'Connor 1c3cbe9456 command: Refactor message block generation
Separate out the buffer management, message encoding, and message
framing code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:58 -04:00
Kevin O'Connor 88f4c38dca command: Refactor the command reading task
Refactor the code so that message block framing, command parsing, and
command dispatch are distinct.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-29 13:33:58 -04:00
Kevin O'Connor b7b368a1ed build: Default to python2 in the Makefile
Set PYTHON=python2 instead of python as some systems point python to
python3.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-28 10:52:05 -04:00
Kevin O'Connor d2fafbdd9e build: Request python2 for all directly executed python binaries
Some systems point python to python3 instead of python2 - explicitly
request python2 to avoid conflicts.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-27 20:26:02 -04:00
Kevin O'Connor d981973096 heater: Fix auto-tune code
Make sure the heater.target_temp is set during the auto-tune test so
that the heater.set_pwm() command will allow the heater to be turned
on.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-22 12:09:55 -04:00
Kevin O'Connor b310501970 sam3x8e: Use readl/writel instead of readb/writeb() in serial.c
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-22 10:51:49 -04:00
Kevin O'Connor e92ce565dd console: Support new artificial DELAY command
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-22 10:51:49 -04:00
Kevin O'Connor da4f2c5ea0 checkstack: Continue to accumulate stack usage on misc instructions
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-22 10:51:49 -04:00
Kevin O'Connor bd48c3a083 pru: Remove unnecessary barrier() calls
The writel() call already implements a barrier() internally.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-16 14:26:37 -04:00
Kevin O'Connor ba58e0446d install-octopi: Add python-virtualdev to package list
Add python-virtualdev to the list of system packages to be installed -
it's usually already installed, but it doesn't hurt to add it to the
list in case it isn't already installed.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-15 10:41:21 -04:00
Kevin O'Connor c03b4921c3 klippy: Make sure to always sleep before retrying next stats() call
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-15 09:37:57 -04:00
Kevin O'Connor c60e4aceed stepper: Increase the step delay time from 1us to 2us
Increase the step delay time so that it works with the common DRV8825
stepper drivers.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-13 11:53:10 -04:00
Kevin O'Connor 156de2e4c2 delta: Fix support for different endstop_position settings on each stepper
The endstop_position is intended to support different values for each
stepper so that the individual tower heights can be configured.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-11 12:48:51 -04:00
Kevin O'Connor 959509496a gcode: Fix regression causing lost asynchronous commands
Commit d0932009 introduced an error that could cause lost input in
cases where the sender did not wait for an "ok" message before sending
the next command.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-11 12:42:11 -04:00
Kevin O'Connor 8419e152bb klippy: Remove some obscure python2 dependencies
Don't modify dictionaries while iterating them and be careful to use
// when doing an integer divide.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-10 00:12:14 -04:00
Kevin O'Connor 1bc3e0a678 klippy: Use newer "except XYZError as e" python syntax
Use the newer syntax for python exceptions.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-10 00:08:06 -04:00
Kevin O'Connor d093200966 gcode: Support running arbitrary gcode on extruder change
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-09 18:55:33 -04:00
Kevin O'Connor 72dc21fb1a gcode: Support for querying and setting multiple extruder heaters
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-09 18:55:30 -04:00
Kevin O'Connor 24b8f4ebc1 extruder: Add initial support for multi-extruders
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-09 18:54:38 -04:00
Kevin O'Connor 136dccbcdf klippy: Allow each module to define their config sections
Create add_printer_objects() functions in the fan, heater, extruder,
and toolhead modules.  Create the necessary printer component objects
from this call instead of placing the code directly in klippy.py.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-09 18:54:34 -04:00
Kevin O'Connor d0e6a0928b pins: Fix typo in at90usb1286 support so PF0-7 pins are defined
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-09 18:46:07 -04:00
Kevin O'Connor 46846d4297 avr: Enable CLEAR_PRESCALER by default on at90usb1286
It appears this option is commonly needed on the at90usb1286 avr chip
(the printrboard requires it), so default it on.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-09 18:42:40 -04:00
Kevin O'Connor 01ee9e16c5 klippy: Prefer python dictionary comprehension to dict() call
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-06 12:35:13 -04:00
Kevin O'Connor 38411fd2e7 delta: Add support for specifying the angle each tower is at
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-05 18:05:45 -04:00
Kevin O'Connor b8094de129 avr: Support using serial instead of usb on AT90USB1286
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-06-05 12:30:49 -04:00
Kevin O'Connor 73207a12ba avr: Allow atmega328 to select a cpu speed of 20Mhz
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-29 14:24:18 -04:00
Kevin O'Connor 3af87e1c42 avr: Add SIMULAVR build option; don't show WATCHDOG or SERIAL_BAUD_U2X
Add a CONFIG_SIMULAVR option to the Kbuild menus and don't directly
prompt users for CONFIG_WATCHDOG or CONFIG_SERIAL_BAUD_U2X.  The only
reason to disable these options would be if one were running on
simulavr.  This simplifies the user visible menu options.

Also, only show CONFIG_CLEAR_PRESCALER for at90usb1286 chips.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-28 11:04:59 -04:00
Kevin O'Connor d2547ce6b0 avr: Add support for atmega328 chip
The atmega328 is basically the same as the atmega168 - it just adds
some additional memory.  Allow the chip to be selected during the
build.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-28 10:45:32 -04:00
Kevin O'Connor 7e3d7e071f avr: Reorder Kconfig entries so that atmega2560 at 16mhz is default
Reorder the MCU list so that newer chips are at the top of the list.
This causes the very popular atmega2560 to be the default chip
selected.

Reorder the frequency list so that higher frequencies are at the top
of the list.  Restrict the 20Mhz frequency to only chips that support
that speed.  This causes the popular 16Mhz frequency to be the default
speed on AVR.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-28 09:59:51 -04:00
Kevin O'Connor d4bed025ed command: Store the command parsing information directly in array
Instead of defining an array of pointers, just define the array
directly.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-26 13:25:51 -04:00
Kevin O'Connor a82e949c00 build: Use compile_time_request system for init, tasks, and shutdown
Avoid using linker magic to define the init, task, and shutdown
functions.  Instead, use the compile_time_request system.  This
simplifies the build and produces more efficient code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-26 12:39:34 -04:00
Kevin O'Connor ca9756413f sched: Allow shutdown_reason to be uint8
Store the shutdown_reason code in an 8-bit integer - this produces
better code on AVR.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-26 12:32:05 -04:00
Kevin O'Connor b9940f0e0d build: Avoid linker magic in compile_time_request.c unique id generation
Avoid generating unique ids via memory locations and linker scripts.
Instead, generate them using code produced by buildcommands.py.
Utilize gcc's ability to perform static string comparisons at compile
time to produce a unique id for each unique string.

This fixes a build failure on ARM introduced in 142b92b8.  It also
reduces the complexity of the build.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-26 12:32:02 -04:00
Kevin O'Connor f91a49c65d docs: Note how to handle odd corner in Pressure_Advance.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-25 13:39:16 -04:00
Kevin O'Connor 4b8ad3fc03 docs: Add a prerequisites section to Pressure_advance.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-22 12:32:20 -04:00
Kevin O'Connor e8aabbb40b docs: Add Todo item for supporting custom fan and pin config sections
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-22 11:55:41 -04:00
Kevin O'Connor 02a5fa2c79 config: Make it clear the "fan" section represents the print cooling fan
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-21 11:52:02 -04:00
Kevin O'Connor 944c121a00 config: Add periods to end of sentences in example configs
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-21 11:51:58 -04:00
Kevin O'Connor c9b6662138 pru: Add support for ADC input
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-17 19:46:12 -04:00
Kevin O'Connor b85755c0ff pru: Move communication code to second PRU
Perform input and output in the second PRU so that more space is
available in the primary PRU.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-17 10:46:38 -04:00
Kevin O'Connor b6f24e78ac pyhelper: Fix GETHEX() macro used in dump_string() debugging
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-17 09:57:09 -04:00
Kevin O'Connor fc24aa041b pins: Add pin mappings for Beaglebone boards
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 15:15:52 -04:00
Kevin O'Connor c9b44b5bb6 serialhdl: Support working with pseudo serial devices
Support working with devices that aren't really serial ports and thus
do not have a baud rate.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 15:15:52 -04:00
Kevin O'Connor 2255176228 pru: Initial support for the Beaglebone PRU
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 15:15:52 -04:00
Kevin O'Connor ccaa25eaa5 pru: Add initial pru_rpmsg library code for Beaglebone PRU
Add external code for using RPMsg on the Beaglebone PRU.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 15:00:52 -04:00
Kevin O'Connor 969ee4c8f9 irq: Add an irq_poll() stub for board code
Allow the board specific code to run checks prior to running each
task.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 15:00:45 -04:00
Kevin O'Connor c35278e217 build: Avoid using noinline in common code
It's not necessary to use noinline for parsef() and stop_steppers().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:59 -04:00
Kevin O'Connor 039d3f0523 stepper: It is not necessary to ensure gpio_out_write value is 0 or 1
The gpio_out_write() and gpio_out_setup() calls will check for zero
and non-zero, so it is not necessary to explicitly convert to 0/1 in
the stepper.c code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:59 -04:00
Kevin O'Connor d56f8407a5 debugcmds: Move debugging commands from basecmd.c to new file
Move the implementation of debug commands to their own file.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:59 -04:00
Kevin O'Connor 142b92b883 command: Use "i" instead of "m" constraint in _DECL_REQUEST_ID
On some architectures, gcc will allocate a register for inline
assembler with an "m" constraint.  Use "i" to avoid that.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:59 -04:00
Kevin O'Connor c292006421 gpiocmds: Change MAX_SOFT_PWM from 255 to 256
Change the range of values used for software PWM to avoid doing an
integer division in the main code.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:59 -04:00
Kevin O'Connor 5c4cc0d646 pwmcmds: Export the maximum PWM value
Instead of assuming the maximum PWM value is 255, export a constant
from the firmware to the host with the maximum value.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:59 -04:00
Kevin O'Connor a361b92184 gpio: Fix off-by-one in declaration of ADC_MAX
The maximum value for the ADC is 1023 for 10bit samples and 4095 for
12bit samples.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:59 -04:00
Kevin O'Connor 37572bc217 command: Only implement 16bit signed conversion on AVR
On regular 32bit machines there is no need to implement explicit
signed conversion on 16bit integers.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:04 -04:00
Kevin O'Connor 233adfe660 build: Add __visible to variables in compile_time_request.c
Add __visible to generated code in compile_time_request.c so that the
main code can be compiled with -fwhole-program.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:02:04 -04:00
Kevin O'Connor 450c14b286 build: Rename makefile CFLAGS-y to CFLAGS and LDFLAGS-y to CFLAGS_klipper.elf
Rename some makefile variables.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-15 14:01:56 -04:00
Kevin O'Connor 33dfc386c9 avr: Merge misc.c into main.c
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-11 13:56:21 -04:00
Kevin O'Connor f331936969 basecmd: Avoid calling malloc() from main code
Introduce a new board function alloc_chunk() to allocate dynamic
memory.  This allows the board code to implement memory allocations
without using the standard malloc() interface.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2017-05-11 13:56:21 -04:00
142 changed files with 11343 additions and 2607 deletions

No files matched your search

+12 -20
View File
@@ -1,6 +1,6 @@
# Klipper build system
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
@@ -22,7 +22,7 @@ OBJCOPY=$(CROSS_PREFIX)objcopy
OBJDUMP=$(CROSS_PREFIX)objdump
STRIP=$(CROSS_PREFIX)strip
CPP=cpp
PYTHON=python
PYTHON=python2
# Source files
src-y =
@@ -32,18 +32,15 @@ dirs-y = src
cc-option=$(shell if test -z "`$(1) $(2) -S -o /dev/null -xc /dev/null 2>&1`" \
; then echo "$(2)"; else echo "$(3)"; fi ;)
CFLAGS-y := -I$(OUT) -Isrc -I$(OUT)board-generic/ -O2 -MD -g \
CFLAGS := -I$(OUT) -Isrc -I$(OUT)board-generic/ -O2 -MD -g \
-Wall -Wold-style-definition $(call cc-option,$(CC),-Wtype-limits,) \
-ffunction-sections -fdata-sections
CFLAGS-y += -flto -fwhole-program -fno-use-linker-plugin
CFLAGS += -flto -fwhole-program -fno-use-linker-plugin
LDFLAGS-y := -Wl,--gc-sections -fno-whole-program
CFLAGS_klipper.elf = $(CFLAGS) -Wl,--gc-sections
CPPFLAGS = -I$(OUT) -P -MD -MT $@
CFLAGS = $(CFLAGS-y)
LDFLAGS = $(LDFLAGS-y)
# Default targets
target-y := $(OUT)klipper.elf
@@ -77,23 +74,18 @@ $(OUT)board-link: $(KCONFIG_CONFIG)
$(Q)mkdir -p $(OUT)board-generic
$(Q)ln -Tsf $(PWD)/src/generic $(OUT)board-generic/board
$(OUT)declfunc.lds: src/declfunc.lds.S
@echo " Precompiling $@"
$(Q)$(CPP) $(CPPFLAGS) -D__ASSEMBLY__ $< -o $@
$(OUT)%.o.ctr: $(OUT)%.o
$(Q)$(OBJCOPY) -j '.compile_time_request' -O binary $^ $@
$(OUT)klipper.o: $(patsubst %.c, $(OUT)src/%.o,$(src-y)) $(OUT)declfunc.lds
@echo " Linking $@"
$(Q)$(CC) $(CFLAGS) $(CFLAGS_klipper.o) -Wl,-r -Wl,-T,$(OUT)declfunc.lds -nostdlib $(patsubst %.c, $(OUT)src/%.o,$(src-y)) -o $@
$(OUT)compile_time_request.o: $(OUT)klipper.o ./scripts/buildcommands.py
$(OUT)compile_time_request.o: $(patsubst %.c, $(OUT)src/%.o.ctr,$(src-y)) ./scripts/buildcommands.py
@echo " Building $@"
$(Q)$(OBJCOPY) -j '.compile_time_request' -O binary $< $(OUT)klipper.o.compile_time_request
$(Q)$(PYTHON) ./scripts/buildcommands.py -d $(OUT)klipper.dict $(OUT)klipper.o.compile_time_request $(OUT)compile_time_request.c
$(Q)cat $(patsubst %.c, $(OUT)src/%.o.ctr,$(src-y)) > $(OUT)klipper.compile_time_request
$(Q)$(PYTHON) ./scripts/buildcommands.py -d $(OUT)klipper.dict $(OUT)klipper.compile_time_request $(OUT)compile_time_request.c
$(Q)$(CC) $(CFLAGS) -c $(OUT)compile_time_request.c -o $@
$(OUT)klipper.elf: $(OUT)klipper.o $(OUT)compile_time_request.o
$(OUT)klipper.elf: $(patsubst %.c, $(OUT)src/%.o,$(src-y)) $(OUT)compile_time_request.o
@echo " Linking $@"
$(Q)$(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
$(Q)$(CC) $(CFLAGS_klipper.elf) $^ -o $@
################ Kconfig rules
+7 -10
View File
@@ -8,38 +8,35 @@
# FIRST. Incorrectly configured parameters may cause damage.
# The stepper_x section is used to describe the X axis as well as the
# stepper controlling the X+Y movement
# stepper controlling the X+Y movement.
[stepper_x]
step_pin: ar54
dir_pin: ar55
enable_pin: !ar38
step_distance: .01
endstop_pin: ^ar2
homing_speed: 50.0
position_min: 0
endstop_pin: ^ar3
position_endstop: 0
position_max: 200
homing_speed: 50
# The stepper_y section is used to describe the Y axis as well as the
# stepper controlling the X-Y movement
# stepper controlling the X-Y movement.
[stepper_y]
step_pin: ar60
dir_pin: ar61
enable_pin: !ar56
step_distance: .01
endstop_pin: ^ar15
homing_speed: 50.0
position_min: 0
endstop_pin: ^ar14
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_z]
step_pin: ar46
dir_pin: ar48
enable_pin: !ar62
step_distance: .01
endstop_pin: ^ar19
position_min: 0.1
endstop_pin: ^ar18
position_endstop: 0.5
position_max: 200
+11 -13
View File
@@ -16,11 +16,15 @@ dir_pin: ar55
enable_pin: !ar38
step_distance: .01
endstop_pin: ^ar2
homing_speed: 50.0
position_endstop: 297.05
#angle:
# This option specifies the angle (in degrees) that the tower is
# at. The default is 210 for stepper_a, 330 for stepper_b, and 90
# for stepper_c.
homing_speed: 50
# The stepper_b section describes the stepper controlling the front
# right tower (at 330 degrees)
# right tower (at 330 degrees).
[stepper_b]
step_pin: ar60
dir_pin: ar61
@@ -30,7 +34,7 @@ endstop_pin: ^ar15
position_endstop: 297.05
# The stepper_c section describes the stepper controlling the rear
# tower (at 90 degrees)
# tower (at 90 degrees).
[stepper_c]
step_pin: ar46
dir_pin: ar48
@@ -64,7 +68,7 @@ control: watermark
min_temp: 0
max_temp: 130
# Extruder print fan (omit section if fan not present)
# Print cooling fan (omit section if fan not present).
#[fan]
#pin: ar9
@@ -77,17 +81,11 @@ kinematics: delta
# This option must be "delta" for linear delta printers.
max_velocity: 300
# Maximum velocity (in mm/s) of the toolhead relative to the
# print. This limits the velocity of the toolhead relative to the
# print - at the extreme end of the print envelope the delta axis
# steppers themselves may briefly exceed this speed by up to 3
# times. This parameter must be specified.
# print. This parameter must be specified.
max_accel: 3000
# Maximum acceleration (in mm/s^2) of the toolhead relative to the
# print. This limits the acceleration of the toolhead relative to
# the print - at the extreme end of the print envelope the delta
# axis steppers may briefly exceed this acceleration by up to 3
# times. This parameter must be specified.
max_z_velocity: 200
# print. This parameter must be specified.
max_z_velocity: 150
# For delta printers this limits the maximum velocity (in mm/s) of
# moves with z axis movement. This setting can be used to reduce the
# maximum speed of up/down moves (which require a higher step rate
+153
View File
@@ -0,0 +1,153 @@
# This file serves as documentation for config parameters of
# additional devices that may be configured on a printer. The snippets
# in this file may be copied into the main printer.cfg file. See the
# "example.cfg" file for description of common config parameters.
# In a multi-extruder printer add an additional extruder section for
# each additional extruder. The additional extruder sections should be
# named "extruder1", "extruder2", "extruder3", and so on. See the
# "extruder" section in example.cfg for a description of available
# parameters.
#[extruder1]
#step_pin: ar36
#dir_pin: ar34
#...
#deactivate_gcode:
# A list of G-Code commands (one per line) to execute on a G-Code
# tool change command (eg, "T1") that deactivates this extruder and
# activates some other extruder. It only makes sense to define this
# section on multi-extruder printers. The default is to not run any
# special G-Code commands on deactivation.
#activate_gcode:
# A list of G-Code commands (one per line) to execute on a G-Code
# tool change command (eg, "T0") that activates this extruder. It
# only makes sense to define this section on multi-extruder
# printers. The default is to not run any special G-Code commands on
# activation.
# Heater cooling fans (one may define any number of sections with a
# "heater_fan" prefix). A "heater fan" is a fan that will be enabled
# whenever its associated heater is active. In the event of an MCU
# software error the heater_fan will be set to its max_power.
#[heater_fan my_nozzle_fan]
# See the "fan" section for fan configuration parameters.
#pin: ar4
# The remaining variables are specific to heater_fan.
#heater: extruder
# Name of the config section defining the heater that this fan is
# associated with. The default is "extruder".
#heater_temp: 50.0
# A temperature (in Celsius) that the heater must drop below before
# the fan is disabled. The default is 50 Celsius.
#fan_speed:
# The fan speed (expressed as a value from 0.0 to 1.0) that the fan
# will be set to when its associated heater is enabled. The default
# is max_power.
# Additional micro-controllers (one may define any number of sections
# with an "mcu" prefix). Additional micro-controllers introduce
# additional pins that may be configured as heaters, steppers, fans,
# etc.. For example, if an "[mcu extra_mcu]" section is introduced,
# then pins such as "extra_mcu:ar9" may then be used elsewhere in the
# config (where "ar9" is a hardware pin name or alias name on the
# given mcu).
#[mcu my_extra_mcu]
# See the "mcu" section in example.cfg for configuration parameters.
# Servos (one may define any number of sections with a "servo"
# prefix). The servos may be controlled using the SET_SERVO g-code
# command. For example: SET_SERVO SERVO=my_servo ANGLE=180
#[servo my_servo]
#pin: ar7
# PWM output pin controlling the servo. This parameter must be
# provided.
#maximum_servo_angle: 180
# The maximum angle (in degrees) that this servo can be set to. The
# default is 180 degrees.
#minimum_pulse_width: 0.001
# The minimum pulse width time (in seconds). This should correspond
# with an angle of 0 degrees. The default is 0.001 seconds.
#maximum_pulse_width: 0.002
# The maximum pulse width time (in seconds). This should correspond
# with an angle of maximum_servo_angle. The default is 0.002
# seconds.
# Statically configured digital output pins (one may define any number
# of sections with a "static_digital_output" prefix). Pins configured
# here will be setup as a GPIO output during MCU configuration.
#[static_digital_output my_output_pins]
#pins:
# A comma separated list of pins to be set as GPIO output pins. The
# pin will be set to a high level unless the pin name is prefaced
# with "!". This parameter must be provided.
# Statically configured PWM output pins (one may define any number of
# sections with a "static_pwm_output" prefix). Pins configured here
# will be setup as PWM outputs during MCU configuration.
#[static_pwm_output my_output_pwm]
#pin:
# The pin to configure as PWM output. This parameter must be
# provided.
#value:
# The value to statically set the PWM output to. This is typically
# set to a number between 0.0 and 1.0 with 1.0 being full on and 0.0
# being full off. However, the range may be changed with the 'scale'
# parameter (see below). This parameter must be provided.
#hard_pwm:
# Set this value to force hardware PWM instead of software PWM. Set
# to 1 to force a hardware PWM at the fastest rate; set to a higher
# number to force hardware PWM with the given cycle time in clock
# ticks. The default is to use software PWM.
#cycle_time: 0.100
# The amount of time (in seconds) per PWM cycle when using software
# based PWM. The default is 0.100 seconds.
#scale:
# This parameter can be used to alter how the 'value' parameter is
# interpreted. If provided, then the 'value' parameter should be
# between 0.0 and 'scale'. This may be useful when configuring a PWM
# pin that controls a stepper voltage reference. The 'scale' can be
# set to the equivalent stepper amperage if the PWM were fully
# enabled, and then the 'value' parameter can be specified using the
# desired amperage for the stepper. The default is to not scale the
# 'value' parameter.
# Statically configured AD5206 digipots connected via SPI bus (one may
# define any number of sections with an "ad5206" prefix).
#[ad5206 my_digipot]
#enable_pin:
# The pin corresponding to the AD5206 chip select line. This pin
# will be set to low at the start of SPI messages and raised to high
# after the message completes. This parameter must be provided.
#channel_1:
#channel_2:
#channel_3:
#channel_4:
#channel_5:
#channel_6:
# The value to statically set the given AD5206 channel to. This is
# typically set to a number between 0.0 and 1.0 with 1.0 being the
# highest resistance and 0.0 being the lowest resistance. However,
# the range may be changed with the 'scale' parameter (see
# below). If a channel is not specified then it is left
# unconfigured.
#scale:
# This parameter can be used to alter how the 'channel_x' parameters
# are interpreted. If provided, then the 'channel_x' parameters
# should be between 0.0 and 'scale'. This may be useful when the
# AD5206 is used to set stepper voltage references. The 'scale' can
# be set to the equivalent stepper amperage if the AD5206 were at
# its highest resistance, and then the 'channel_x' parameters can be
# specified using the desired amperage value for the stepper. The
# default is to not scale the 'channel_x' parameters.
# Replicape support - see the generic-replicape.cfg file for further
# details.
#[replicape]
+65 -61
View File
@@ -2,7 +2,8 @@
# copy and edit this file to configure a new cartesian style
# printer. For delta style printers, see the "example-delta.cfg"
# file. For corexy/h-bot style printers, see the "example-corexy.cfg"
# file.
# file. Only common config sections are described here - see the
# "example-extras.cfg" file for configuring less common devices.
# DO NOT COPY THIS FILE WITHOUT CAREFULLY READING AND UPDATING IT
# FIRST. Incorrectly configured parameters may cause damage.
@@ -18,32 +19,44 @@
# The stepper_x section is used to describe the stepper controlling
# the X axis in a cartesian robot
# the X axis in a cartesian robot.
[stepper_x]
step_pin: ar29
step_pin: ar54
# Step GPIO pin (triggered high). This parameter must be provided.
dir_pin: !ar28
dir_pin: ar55
# Direction GPIO pin (high indicates positive direction). This
# parameter must be provided.
enable_pin: !ar25
enable_pin: !ar38
# Enable pin (default is enable high; use ! to indicate enable
# low). If this parameter is not provided then the stepper motor
# driver must always be enabled.
step_distance: .0225
# Distance in mm that each step causes the axis to travel. This
# parameter must be provided.
endstop_pin: ^ar0
endstop_pin: ^ar3
# Endstop switch detection pin. This parameter must be provided for
# the X, Y, and Z steppers on cartesian style printers.
#position_min: 0
# Minimum valid distance (in mm) the user may command the stepper to
# move to. The default is 0mm.
position_endstop: 0
# Location of the endstop (in mm). This parameter must be provided
# for the X, Y, and Z steppers on cartesian style printers.
position_max: 200
# Maximum valid distance (in mm) the user may command the stepper to
# move to. This parameter must be provided for the X, Y, and Z
# steppers on cartesian style printers.
#homing_speed: 5.0
# Maximum velocity (in mm/s) of the stepper when homing. The default
# is 5mm/s.
#homing_retract_dist: 5.0
# Distance to backoff (in mm) before homing a second time during
# homing. The default is 5mm.
#homing_positive_dir: False
# If true, homes in a positive direction (away from zero). The
# default is False.
#homing_positive_dir:
# If true, homing will cause the stepper to move in a positive
# direction (away from zero); if false, home towards zero. The
# default is true if position_endstop is near position_max and false
# if near position_min.
#homing_stepper_phases: 0
# One may optionally set this to the number of phases of the stepper
# motor driver (which is the number of micro-steps multiplied by
@@ -64,40 +77,28 @@ endstop_pin: ^ar0
# reset. If this is not set, but homing_stepper_phases is set, then
# the stepper phase will be detected on the first home and that
# phase will be used on all subsequent homes.
position_min: -0.25
# Minimum valid distance (in mm) the user may command the stepper to
# move to. The default is 0mm.
position_endstop: 0
# Location of the endstop (in mm). This parameter must be provided
# for the X, Y, and Z steppers on cartesian style printers.
position_max: 200
# Maximum valid distance (in mm) the user may command the stepper to
# move to. This parameter must be provided for the X, Y, and Z
# steppers on cartesian style printers.
# The stepper_y section is used to describe the stepper controlling
# the Y axis in a cartesian robot. It has the same settings as the
# stepper_x section
# stepper_x section.
[stepper_y]
step_pin: ar27
dir_pin: ar26
enable_pin: !ar25
step_pin: ar60
dir_pin: !ar61
enable_pin: !ar56
step_distance: .0225
endstop_pin: ^ar1
position_min: -0.25
endstop_pin: ^ar14
position_endstop: 0
position_max: 200
# The stepper_z section is used to describe the stepper controlling
# the Z axis in a cartesian robot. It has the same settings as the
# stepper_x section
# stepper_x section.
[stepper_z]
step_pin: ar23
dir_pin: !ar22
enable_pin: !ar25
step_pin: ar46
dir_pin: ar48
enable_pin: !ar62
step_distance: .005
endstop_pin: ^ar2
position_min: 0.1
endstop_pin: ^ar18
position_endstop: 0.5
position_max: 200
@@ -105,11 +106,11 @@ position_max: 200
# controlling the printer extruder and the heater parameters for the
# nozzle. The stepper configuration has the same settings as the
# stepper_x section and the heater configuration has the same settings
# as the heater_bed section
# as the heater_bed section (described below).
[extruder]
step_pin: ar19
dir_pin: ar18
enable_pin: !ar25
step_pin: ar26
dir_pin: ar28
enable_pin: !ar24
step_distance: .004242
nozzle_diameter: 0.500
# Diameter of the nozzle orifice (in mm). This parameter must be
@@ -119,9 +120,10 @@ filament_diameter: 3.500
# extruder. This parameter must be provided.
#max_extrude_cross_section:
# Maximum area of the cross section of an extrusion line (in
# mm^2). If a move requests an extrusion rate that would exceed this
# value it will cause an error to be returned. The default is: 4.0 *
# nozzle_diameter^2
# mm^2). This setting prevents excessive amounts of extrusion during
# relatively small XY moves. If a move requests an extrusion rate
# that would exceed this value it will cause an error to be
# returned. The default is: 4.0 * nozzle_diameter^2
#max_extrude_only_distance: 50.0
# Maximum length (in mm of raw filament) that an extrude only move
# may be. If an extrude only move requests a distance greater than
@@ -151,8 +153,8 @@ filament_diameter: 3.500
# buildup. This setting only applies if pressure_advance is
# non-zero. The default is 0.010 (10 milliseconds).
#
# The remaining variables describe the extruder heater
heater_pin: ar4
# The remaining variables describe the extruder heater.
heater_pin: ar10
# PWM output pin controlling the heater. This parameter must be
# provided.
#max_power: 1.0
@@ -164,8 +166,9 @@ heater_pin: ar4
# periods) to the heater. The default is 1.0.
sensor_type: EPCOS 100K B57560G104F
# Type of sensor - this may be "EPCOS 100K B57560G104F", "ATC
# Semitec 104GT-2", or "AD595". This parameter must be provided.
sensor_pin: analog1
# Semitec 104GT-2", "NTC 100K beta 3950", or "AD595". This parameter
# must be provided.
sensor_pin: analog13
# Analog input pin connected to the sensor. This parameter must be
# provided.
#pullup_resistor: 4700
@@ -207,9 +210,9 @@ max_temp: 210
# The heater_bed section describes a heated bed (if present - omit
# section if not present).
[heater_bed]
heater_pin: ar3
heater_pin: ar8
sensor_type: EPCOS 100K B57560G104F
sensor_pin: analog0
sensor_pin: analog14
control: watermark
#max_delta: 2.0
# On 'watermark' controlled heaters this is the number of degrees in
@@ -219,11 +222,18 @@ control: watermark
min_temp: 0
max_temp: 110
# Extruder print fan (omit section if fan not present)
# Print cooling fan (omit section if fan not present).
[fan]
pin: ar14
pin: ar9
# PWM output pin controlling the fan. This parameter must be
# provided.
#max_power: 1.0
# The maximum power (expressed as a value from 0.0 to 1.0) that the
# pin may be set to. The value 1.0 allows the pin to be set fully
# enabled for extended periods, while a value of 0.5 would allow the
# pin to be enabled for no more than half the time. This setting may
# be used to limit the total power output (over extended periods) to
# the fan. The default is 1.0.
#hard_pwm: 0
# Set this value to force hardware PWM instead of software PWM. Set
# to 1 to force a hardware PWM at the fastest rate; set to a higher
@@ -234,7 +244,7 @@ pin: ar14
# Time (in seconds) to run the fan at full speed when first enabling
# it (helps get the fan spinning). The default is 0.100 seconds.
# Micro-controller information
# Micro-controller information.
[mcu]
serial: /dev/ttyACM0
# The serial port to connect to the MCU. The default is /dev/ttyS0
@@ -246,21 +256,15 @@ pin_map: arduino
#restart_method: arduino
# This controls the mechanism the host will use to reset the
# micro-controller. The choices are 'arduino', 'rpi_usb', and
# 'command'. The 'arduino' method (toggle DTR; set baud to 1200) is
# common on Arduino boards and clones. The 'rpi_usb' method is
# useful on Raspberry Pi boards with micro-controllers powered over
# USB - it briefly disables power to all USB ports to accomplish a
# micro-controller reset. The 'command' method involves sending a
# Klipper command to the micro-controller so that it can reset
# itself. The default is 'arduino'.
custom:
# This option may be used to specify a set of custom
# micro-controller commands to be sent at the start of the
# connection. It may be used to configure the initial settings of
# LEDs, to configure micro-stepping pins, to configure a digipot,
# etc.
# 'command'. The 'arduino' method (toggle DTR) is common on Arduino
# boards and clones. The 'rpi_usb' method is useful on Raspberry Pi
# boards with micro-controllers powered over USB - it briefly
# disables power to all USB ports to accomplish a micro-controller
# reset. The 'command' method involves sending a Klipper command to
# the micro-controller so that it can reset itself. The default is
# 'arduino'.
# The printer section controls high level printer settings
# The printer section controls high level printer settings.
[printer]
kinematics: cartesian
# This option must be "cartesian" for cartesian printers.
+79
View File
@@ -0,0 +1,79 @@
# This file contains an example configuration for a Beaglebone PRU
# micro-controller attached to a CRAMPS board.
# THIS FILE HAS NOT BEEN TESTED - PROCEED WITH CAUTION!
# NOTE: Klipper does not alter the input/output state of the
# Beaglebone pins and it does not control their pull-up resistors. In
# order to set the pin state one must use a "device tree overlay" or
# use the config-pin program.
# See the example.cfg file for a description of available parameters.
[stepper_x]
step_pin: P8_13
dir_pin: P8_12
enable_pin: !P9_14
step_distance: .0125
endstop_pin: ^P8_8
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_y]
step_pin: P8_15
dir_pin: P8_14
enable_pin: !P9_14
step_distance: .0125
endstop_pin: ^P8_10
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_z]
step_pin: P8_19
dir_pin: P8_18
enable_pin: !P9_14
step_distance: 0.00025
endstop_pin: ^P9_13
position_endstop: 0
position_max: 200
[extruder]
step_pin: P9_16
dir_pin: P9_12
enable_pin: !P9_14
step_distance: .002
nozzle_diameter: 0.400
filament_diameter: 1.750
heater_pin: P9_15
sensor_type: EPCOS 100K B57560G104F
sensor_pin: P9_36
control: pid
pid_Kp: 22.2
pid_Ki: 1.08
pid_Kd: 114
min_temp: 0
max_temp: 250
[heater_bed]
heater_pin: P8_11
sensor_type: EPCOS 100K B57560G104F
sensor_pin: P9_33
control: watermark
min_temp: 0
max_temp: 130
[fan]
pin: P9_41
[mcu]
serial: /dev/rpmsg_pru30
pin_map: beaglebone
[printer]
kinematics: cartesian
max_velocity: 300
max_accel: 3000
max_z_velocity: 5
max_z_accel: 100
+76
View File
@@ -0,0 +1,76 @@
# This file contains common pin mappings for Melzi v2.0 boards. To use
# this config, the firmware should be compiled for the AVR
# atmega1284p.
# Note that the "make flash" command does not work with Melzi
# boards. The boards are typically flashed with this command:
# avrdude -p atmega1284p -c avrisp -P /dev/ttyUSB0 -U flash:w:out/klipper.elf.hex
# See the example.cfg file for a description of available parameters.
[stepper_x]
step_pin: PD7
dir_pin: PC5
enable_pin: !PD6
step_distance: .0125
endstop_pin: ^!PC2
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_y]
step_pin: PC6
dir_pin: PC7
enable_pin: !PD6
step_distance: .0125
endstop_pin: ^!PC3
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_z]
step_pin: PB3
dir_pin: !PB2
enable_pin: !PA5
step_distance: 0.00025
endstop_pin: ^!PC4
position_endstop: 0.5
position_max: 200
[extruder]
step_pin: PB1
dir_pin: PB0
enable_pin: !PD6
step_distance: .002
nozzle_diameter: 0.400
filament_diameter: 1.750
heater_pin: PD5
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PA7
control: pid
pid_Kp: 22.2
pid_Ki: 1.08
pid_Kd: 114
min_temp: 0
max_temp: 250
[heater_bed]
heater_pin: PD2
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PA6
control: watermark
min_temp: 0
max_temp: 130
[fan]
pin: PB4
[mcu]
serial: /dev/ttyUSB0
[printer]
kinematics: cartesian
max_velocity: 300
max_accel: 3000
max_z_velocity: 5
max_z_accel: 100
+41 -22
View File
@@ -9,9 +9,10 @@ dir_pin: PL1
enable_pin: !PA7
step_distance: .0125
endstop_pin: ^PB6
homing_speed: 50
#endstop_pin: ^PA2
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_y]
step_pin: PC1
@@ -19,9 +20,10 @@ dir_pin: !PL0
enable_pin: !PA6
step_distance: .0125
endstop_pin: ^PB5
homing_speed: 50
#endstop_pin: ^PA1
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_z]
step_pin: PC2
@@ -29,8 +31,8 @@ dir_pin: PL2
enable_pin: !PA5
step_distance: 0.00025
endstop_pin: ^PB4
homing_speed: 5
position_endstop: 0
#endstop_pin: ^PC7
position_endstop: 0.5
position_max: 200
[extruder]
@@ -50,6 +52,14 @@ pid_Kd: 114
min_temp: 0
max_temp: 250
#[extruder1]
#step_pin: PC4
#dir_pin: PL7
#enable_pin: !PA3
#heater_pin: PH4
#sensor_pin: PF1
#...
[heater_bed]
heater_pin: PE5
sensor_type: EPCOS 100K B57560G104F
@@ -61,26 +71,11 @@ max_temp: 130
[fan]
pin: PH5
#[heater_fan nozzle_cooling_fan]
#pin: PH3
[mcu]
serial: /dev/ttyACM0
custom:
# Turn off yellow led
set_digital_out pin=PB7 value=0
# Stepper micro-step pins
set_digital_out pin=PG1 value=1
set_digital_out pin=PG0 value=1
set_digital_out pin=PK7 value=1
set_digital_out pin=PG2 value=1
set_digital_out pin=PK6 value=1
set_digital_out pin=PK5 value=1
set_digital_out pin=PK3 value=1
set_digital_out pin=PK4 value=1
# Initialize digipot
send_spi_message pin=PD7 msg=0487 # X = ~0.75A
send_spi_message pin=PD7 msg=0587 # Y = ~0.75A
send_spi_message pin=PD7 msg=0387 # Z = ~0.75A
send_spi_message pin=PD7 msg=00A5 # E0
send_spi_message pin=PD7 msg=017D # E1
[printer]
kinematics: cartesian
@@ -88,3 +83,27 @@ max_velocity: 300
max_accel: 3000
max_z_velocity: 5
max_z_accel: 100
[ad5206 stepper_digipot]
enable_pin: PD7
# Scale the config so that the channel value can be specified in amps.
# (For Rambo v1.0d boards, use 1.56 instead.)
scale: 2.08
# Channel 1 is E0, 2 is E1, 3 is unused, 4 is Z, 5 is X, 6 is Y
channel_1: 1.34
channel_2: 1.0
channel_4: 1.1
channel_5: 1.1
channel_6: 1.1
# Enable 16 micro-steps on steppers X, Y, Z, E0, E1
[static_digital_output stepper_config]
pins:
PG1, PG0,
PK7, PG2,
PK6, PK5,
PK3, PK4,
PK2, PK1
[static_digital_output yellow_led]
pins: !PB7
+14 -4
View File
@@ -10,9 +10,10 @@ dir_pin: ar55
enable_pin: !ar38
step_distance: .0125
endstop_pin: ^ar3
homing_speed: 50
#endstop_pin: ^ar2
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_y]
step_pin: ar60
@@ -20,9 +21,10 @@ dir_pin: !ar61
enable_pin: !ar56
step_distance: .0125
endstop_pin: ^ar14
homing_speed: 50
#endstop_pin: ^ar15
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_z]
step_pin: ar46
@@ -30,8 +32,8 @@ dir_pin: ar48
enable_pin: !ar62
step_distance: 0.00025
endstop_pin: ^ar18
homing_speed: 5
position_endstop: 0
#endstop_pin: ^ar19
position_endstop: 0.5
position_max: 200
[extruder]
@@ -51,6 +53,14 @@ pid_Kd: 114
min_temp: 0
max_temp: 250
#[extruder1]
#step_pin: ar36
#dir_pin: ar34
#enable_pin: !ar30
#heater_pin: ar9
#sensor_pin: analog15
#...
[heater_bed]
heater_pin: ar8
sensor_type: EPCOS 100K B57560G104F
+124
View File
@@ -0,0 +1,124 @@
# This file contains an example configuration for the Replicape rev B3
# board. To use this config, one must compile and install the
# micro-controller code for the "Beaglebone PRU", and then compile and
# install the micro-controller code a second time for a "Linux
# process".
# NOTE: Klipper does not alter the input/output state of the
# Beaglebone pins and it does not control their pull-up resistors.
# Typically the correct settings are automatically applied when the
# Beaglebone detects the Replicape board, but if changes are needed
# they must be specified in a "device tree overlay" or via the
# config-pin program.
# See the example.cfg file for a description of available parameters.
[stepper_x]
step_pin: P8_17
dir_pin: P8_26
enable_pin: replicape:stepper_x_enable
step_distance: .0125
endstop_pin: ^P9_25
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_y]
step_pin: P8_12
dir_pin: P8_19
enable_pin: replicape:stepper_y_enable
step_distance: .0125
endstop_pin: ^P9_23
position_endstop: 0
position_max: 200
homing_speed: 50
[stepper_z]
step_pin: P8_13
dir_pin: P8_14
enable_pin: replicape:stepper_z_enable
step_distance: 0.00025
endstop_pin: ^P9_13
position_endstop: 0
position_max: 200
[extruder]
step_pin: P9_12
dir_pin: P8_15
enable_pin: replicape:stepper_e_enable
step_distance: .002
nozzle_diameter: 0.400
filament_diameter: 1.750
heater_pin: replicape:power_e
sensor_type: EPCOS 100K B57560G104F
sensor_pin: host:analog4
control: pid
pid_Kp: 22.2
pid_Ki: 1.08
pid_Kd: 114
min_temp: 0
max_temp: 250
[heater_bed]
heater_pin: replicape:power_hotbed
sensor_type: EPCOS 100K B57560G104F
sensor_pin: host:analog6
control: watermark
min_temp: 0
max_temp: 130
[fan]
pin: replicape:power_fan0
[mcu]
serial: /dev/rpmsg_pru30
pin_map: beaglebone
[printer]
kinematics: cartesian
max_velocity: 300
max_accel: 3000
max_z_velocity: 25
max_z_accel: 30
[mcu host]
serial: /tmp/klipper_host_mcu
# The "replicape" config section adds "replicape:stepper_x_enable"
# virtual stepper enable pins (for steppers x, y, z, e, and h) and
# "replicape:power_x" PWM output pins (for hotbed, e, h, fan0, fan1,
# fan2, and fan3) that may then be used elsewhere in the config file.
[replicape]
revision: B3
# The replicape hardware revision. Currently only revision "B3" is
# supported. This parameter must be provided.
#enable_pin: !P9_41
# The replicape global enable pin. The default is !P9_41.
host_mcu: host
# The name of the mcu config section that communicates with the
# Klipper "linux process" mcu instance. This parameter must be
# provided.
stepper_x_microstep_mode: spread16
# This parameter controls the CFG1 and CFG2 pins of the given
# stepper motor driver. Available options are: disable, 1, 2,
# spread2, 4, 16, spread4, spread16, stealth4, and stealth16. The
# default is disable.
stepper_x_current: 0.5
# The configured maximum current (in Amps) of the stepper motor
# driver. This parameter must be provided if the stepper is not in a
# disable mode.
#stepper_x_chopper_off_time_high: False
# This parameter controls the CFG0 pin of the stepper motor driver
# (True sets CFG0 high, False sets it low). The default is False.
#stepper_x_chopper_hysteresis_high: False
# This parameter controls the CFG4 pin of the stepper motor driver
# (True sets CFG4 high, False sets it low). The default is False.
#stepper_x_chopper_blank_time_high: True
# This parameter controls the CFG5 pin of the stepper motor driver
# (True sets CFG5 high, False sets it low). The default is True.
stepper_y_microstep_mode: spread16
stepper_y_current: 0.5
stepper_z_microstep_mode: spread16
stepper_z_current: 0.5
stepper_e_microstep_mode: 16
stepper_e_current: 0.5
+36 -32
View File
@@ -9,12 +9,11 @@ dir_pin: !PL1
enable_pin: !PA7
step_distance: .0225
endstop_pin: ^!PB6
homing_speed: 50.0
homing_stepper_phases: 32
homing_endstop_accuracy: .200
position_min: -0.25
position_endstop: 0.0
position_max: 200
homing_speed: 50
homing_stepper_phases: 32
homing_endstop_accuracy: .200
[stepper_y]
step_pin: PC1
@@ -22,12 +21,11 @@ dir_pin: PL0
enable_pin: !PA6
step_distance: .0225
endstop_pin: ^!PB5
homing_speed: 50.0
homing_stepper_phases: 32
homing_endstop_accuracy: .200
position_min: -0.25
position_endstop: 0.0
position_max: 250
homing_speed: 50
homing_stepper_phases: 32
homing_endstop_accuracy: .200
[stepper_z]
step_pin: PC2
@@ -35,13 +33,12 @@ dir_pin: !PL2
enable_pin: !PA5
step_distance: .005
endstop_pin: ^!PB4
homing_speed: 4.0
homing_retract_dist: 2.0
homing_stepper_phases: 32
homing_endstop_accuracy: .050
position_min: 0.1
position_endstop: 0.7
position_max: 200
homing_retract_dist: 2.0
homing_stepper_phases: 32
homing_endstop_accuracy: .070
[extruder]
step_pin: PC3
@@ -72,28 +69,13 @@ max_temp: 100
[fan]
pin: PH5
[heater_fan nozzle_fan]
pin: PH3
max_power: 0.61
hard_pwm: 1
[mcu]
serial: /dev/ttyACM0
custom:
# Nozzle fan
set_pwm_out pin=PH3 cycle_ticks=1 value=155
# Turn off yellow led
set_digital_out pin=PB7 value=0
# Stepper micro-step pins
set_digital_out pin=PG1 value=1
set_digital_out pin=PG0 value=1
set_digital_out pin=PK7 value=1
set_digital_out pin=PG2 value=1
set_digital_out pin=PK6 value=1
set_digital_out pin=PK5 value=1
set_digital_out pin=PK3 value=1
set_digital_out pin=PK4 value=1
# Initialize digipot
send_spi_message pin=PD7 msg=0487 # X = ~0.75A
send_spi_message pin=PD7 msg=0587 # Y = ~0.75A
send_spi_message pin=PD7 msg=0387 # Z = ~0.75A
send_spi_message pin=PD7 msg=00A5 # E0
send_spi_message pin=PD7 msg=017D # E1
[printer]
kinematics: cartesian
@@ -101,3 +83,25 @@ max_velocity: 500
max_accel: 3000
max_z_velocity: 25
max_z_accel: 30
[ad5206 stepper_digipot]
enable_pin: PD7
# Scale the config so that the channel value can be specified in amps
scale: 1.56
# Channel 1 is E0, 2 is E1, 3 is unused, 4 is Z, 5 is X, 6 is Y
channel_1: 1.0
channel_2: 0.75
channel_4: 0.82
channel_5: 0.82
channel_6: 0.82
# Enable 8 micro-steps on steppers X, Y, Z, E0
[static_digital_output stepper_config]
pins:
PG1, PG0,
PK7, PG2,
PK6, PK5,
PK3, PK4
[static_digital_output yellow_led]
pins: !PB7
+86 -20
View File
@@ -8,13 +8,14 @@ The **src/** directory contains the C source for the micro-controller
code. The **src/avr/** directory contains specific code for Atmel
ATmega micro-controllers. The **src/sam3x8e/** directory contains code
specific to the Arduino Due style ARM micro-controllers. The
**src/simulator/** contains code stubs that allow the micro-controller
to be test compiled on other architectures. The **src/generic/**
directory contains helper code that may be useful across different
host architectures. The build arranges for includes of
"board/somefile.h" to first look in the current architecture directory
(eg, src/avr/somefile.h) and then in the generic directory (eg,
src/generic/somefile.h).
**src/pru/** directory contains code specific to the Beaglebone's
on-board PRU micro-controller. The **src/simulator/** contains code
stubs that allow the micro-controller to be test compiled on other
architectures. The **src/generic/** directory contains helper code
that may be useful across different host architectures. The build
arranges for includes of "board/somefile.h" to first look in the
current architecture directory (eg, src/avr/somefile.h) and then in
the generic directory (eg, src/generic/somefile.h).
The **klippy/** directory contains the C and Python source for the
host part of the software.
@@ -43,10 +44,12 @@ all functions that have been tagged with the DECL_INIT() macro. It
then goes on to repeatedly run all functions tagged with the
DECL_TASK() macro.
One of the main task functions is command_task() located in
**src/command.c**. This function processes incoming serial commands
and runs the associated command function for them. Command functions
are declared using the DECL_COMMAND() macro.
One of the main task functions is command_dispatch() located in
**src/command.c**. This function is called from the board specific
input/output code (eg, **src/avr/serial.c**) and it runs the command
functions associated with the commands found in the input
stream. Command functions are declared using the DECL_COMMAND() macro
(see the [protocol](Protocol.md) document for more information).
Task, init, and command functions always run with interrupts enabled
(however, they can temporarily disable interrupts if needed). These
@@ -145,7 +148,7 @@ provides further information on the mechanics of moves.
start/crusing/end velocity, and distance traveled during
acceleration/cruising/deceleration. All the information is stored in
the Move() class and is in cartesian space in units of millimeters
and seconds. Times are stored relative to the start of the print.
and seconds.
The move is then handed off to the kinematics classes: `Move.move()
-> kin.move()`
@@ -171,14 +174,13 @@ provides further information on the mechanics of moves.
stepcompress_push_const()`, or for delta kinematics:
`DeltaKinematics.move() -> MCU_Stepper.step_delta() ->
stepcompress_push_delta()`. The MCU_Stepper code just performs unit
and axis transformation (seconds to clock ticks and millimeters to
step distances), and calls the C code. The C code calculates the
stepper step times for each movement and fills an array (struct
stepcompress.queue) with the corresponding micro-controller clock
counter times (in 64bit integers) for every step. Here the
"micro-controller clock counter" value directly corresponds to the
micro-controller's hardware counter - it is relative to when the
micro-controller was last powered up.
and axis transformation (millimeters to step distances), and calls
the C code. The C code calculates the stepper step times for each
movement and fills an array (struct stepcompress.queue) with the
corresponding micro-controller clock counter times for every
step. Here the "micro-controller clock counter" value directly
corresponds to the micro-controller's hardware counter - it is
relative to when the micro-controller was last powered up.
* The next major step is to compress the steps: `stepcompress_flush()
-> compress_bisect_add()` (in stepcompress.c). This code generates
@@ -209,3 +211,67 @@ movement. However, the only really interesting parts are in the
ToolHead and kinematic classes. It's this part of the code which
specifies the movements and their timings. The remaining parts of the
processing is mostly just communication and plumbing.
Time
====
Fundamental to the operation of Klipper is the handling of clocks,
times, and timestamps. Klipper executes actions on the printer by
scheduling events to occur in the near future. For example, to turn on
a fan, the code might schedule a change to a GPIO pin in a 100ms. It
is rare for the code to attempt to take an instantaneous action. Thus,
the handling of time within Klipper is critical to correct operation.
There are three types of times tracked internally in the Klipper host
software:
* System time. The system time uses the system's monotonic clock - it
is a floating point number stored as seconds and it is (generally)
relative to when the host computer was last started. System times
have limited use in the software - they are primarily used when
interacting with the operating system. Within the host code, system
times are frequently stored in variables named *eventtime* or
*curtime*.
* Print time. The print time is synchronized to the main
micro-controller clock (the micro-controller defined in the "[mcu]"
config section). It is a floating point number stored as seconds and
is relative to when the main mcu was last restarted. It is possible
to convert from a "print time" to the main micro-controller's
hardware clock by multiplying the print time by the mcu's statically
configured frequency rate. The high-level host code uses print times
to calculates almost all physical actions (eg, head movement, heater
changes, etc.). Within the host code, print times are generally
stored in variables named *print_time* or *move_time*.
* MCU clock. This is the hardware clock counter on each
micro-controller. It is stored as an integer and its update rate is
relative to the frequency of the given micro-controller. The host
software translates its internal times to clocks before transmission
to the mcu. The mcu code only ever tracks time in clock
ticks. Within the host code, clock values are tracked as 64bit
integers, while the mcu code uses 32bit integers. Within the host
code, clocks are generally stored in variables with names containing
*clock* or *ticks*.
Conversion between the different time formats is primarily implemented
in the **klippy/clocksync.py** code.
Some things to be aware of when reviewing the code:
* 32bit and 64bit clocks: To reduce bandwidth and to improve
micro-controller efficiency, clocks on the micro-controller are
tracked as 32bit integers. When comparing two clocks in the mcu
code, the `timer_is_before()` function must always be used to ensure
integer rollovers are handled properly. The host software converts
32bit clocks to 64bit clocks by appending the high-order bits from
the last mcu timestamp it has received - no message from the mcu is
ever more than 2^31 clock ticks in the future or past so this
conversion is never ambiguous. The host converts from 64bit clocks
to 32bit clocks by simply truncating the high-order bits. To ensure
there is no ambiguity in this conversion, the
**klippy/serialqueue.c** code will buffer messages until they are
within 2^31 clock ticks of their target time.
* Multiple micro-controllers: The host software supports using
multiple micro-controllers on a single printer. In this case, the
"MCU clock" of each micro-controller is tracked separately. The
clocksync.py code handles clock drift between micro-controllers by
modifying the way it converts from "print time" to "MCU clock". On
secondary mcus, the mcu frequency that is used in this conversion is
regularly updated to account for measured drift.
+47
View File
@@ -0,0 +1,47 @@
This page provides information on how to contact the Klipper
developers.
Bug reporting
=============
Bug reports are submitted through github issues. All bug reports must
include the full /tmp/klippy.log log file from the session that
produced the error. To acquire this log file, ssh into the computer
running the klipper host software, and run:
```
gzip -k /tmp/klippy.log
```
Then scp the resulting `/tmp/klippy.log.gz` file from the host machine
to your desktop. (If your desktop does not have scp installed, there
are a number of free scp programs available - just do a web search for
`windows scp` to find one.) Open a new issue at
https://github.com/KevinOConnor/klipper/issues , attach the
`klippy.log.gz` file to that issue, and provide a description of the
problem.
Mailing list
============
There is a mailing list for general discussions on Klipper. In order
to send am email to the list, one must first subscribe:
https://www.freelists.org/list/klipper . Once subscribed, emails may
be sent to `klipper@freelists.org`.
Archives of the mailing list are available at:
https://www.freelists.org/archive/klipper/
IRC
===
One may join the #klipper channel on freenode.net (
irc://chat.freenode.net:6667 ).
To communicate in this IRC channel one will need an IRC
client. Configure it to connect to chat.freenode.net on port 6667 and
join the #klipper channel (`/join #klipper`).
If asking a question on IRC, be sure to ask the question and then stay
connected to the channel to receive responses. Due to timezone
differences, it may take several hours before receiving a response.
+4 -4
View File
@@ -75,10 +75,10 @@ cd /patch/to/klipper
make menuconfig
```
and compile the micro-controller software for an AVR atmega644p,
disable the AVR watchdog timer, and set the MCU frequency
to 20000000. Then one can compile Klipper (run `make`) and then start
the simulation with:
and compile the micro-controller software for an AVR atmega644p, set
the MCU frequency to 20Mhz, and select SIMULAVR software emulation
support. Then one can compile Klipper (run `make`) and then start the
simulation with:
```
PYTHONPATH=/path/to/simulavr/src/python/ ./scripts/avrsim.py -m atmega644 -s 20000000 -b 250000 out/klipper.elf
+23 -9
View File
@@ -15,10 +15,10 @@ Klipper has several compelling features:
* Best in class performance. Klipper is able to achieve high stepping
rates on both new and old micro-controllers. Even an old 8bit AVR
micro-controller can obtain rates over 175K steps per second. On
more recent ARM micro-controllers, rates over 450K steps per second
are possible. Higher stepper rates enable higher print
velocities. The stepper event timing remains precise even at high
speeds which improves overall stability.
more recent micro-controllers, rates over 500K steps per second are
possible. Higher stepper rates enable higher print velocities. The
stepper event timing remains precise even at high speeds which
improves overall stability.
* Configuration via simple config file. There's no need to reflash the
micro-controller to change a setting. All of Klipper's configuration
@@ -40,6 +40,14 @@ Klipper has several compelling features:
* Klipper implements the "pressure advance" algorithm for
extruders. When properly tuned, pressure advance reduces extruder
ooze.
* Klipper supports printers with multiple micro-controllers. For
example, one micro-controller could be used to control an
extruder, while another could control the printer's heaters, while
a third controls the rest of the printer. The Klipper host
software implements clock synchronization to account for clock
drift between micro-controllers. No special code is needed to
enable multiple micro-controllers - it just requires a few extra
lines in the config file.
* Klipper also implements a novel "stepper phase endstop" algorithm
that can dramatically improve the accuracy of typical endstop
switches. When properly tuned it can improve a print's first layer
@@ -81,8 +89,14 @@ Step Benchmarks
Below are the results of stepper performance tests. The numbers shown
represent total number of steps per second on the micro-controller.
| Micro-controller | 1 stepper active | 3 steppers active |
| ----------------- | ---------------- | ----------------- |
| 20Mhz AVR | 177K | 117K |
| 16Mhz AVR | 140K | 93K |
| Arduino Due (ARM) | 462K | 406K |
| Micro-controller | Fastest step rate | 3 steppers active |
| ----------------- | ----------------- | ----------------- |
| 20Mhz AVR | 189K | 125K |
| 16Mhz AVR | 151K | 100K |
| Arduino Due (ARM) | 382K | 337K |
| Beaglebone PRU | 689K | 689K |
On AVR platforms, the highest achievable step rate is with just one
stepper stepping. On the Due, the highest step rate is with two
simultaneous steppers stepping. On the PRU, the highest step rate is
with three simultaneous steppers.
+14 -7
View File
@@ -1,25 +1,27 @@
These instructions assume the software will run on a Raspberry Pi
computer in conjunction with OctoPrint. It is recommended that a
Raspberry Pi 2 or Raspberry Pi 3 computer be used as the host
machine.
computer in conjunction with OctoPrint. (See the
[Beaglebone specific instructions](beaglebone.md) if using a
Beaglebone.) It is recommended that a Raspberry Pi 2 or Raspberry Pi 3
computer be used as the host machine.
It should be possible to run the Klipper host software on any computer
running a recent Linux distribution, but doing so will require Linux
admin knowledge to translate these installation instructions to the
particulars of that machine.
Klipper currently supports Atmel ATmega based micro-controllers and
Arduino Due (Atmel SAM3x8e ARM micro-controller) printers.
Klipper currently supports Atmel ATmega based micro-controllers,
Arduino Due (Atmel SAM3x8e ARM micro-controller), and
[Beaglebone PRU](beaglebone.md) based printers.
Prepping an OS image
====================
Start by installing [OctoPi](https://github.com/guysoft/OctoPi) on the
Raspberry Pi computer. Use OctoPi v0.13.0 or later - see the
Raspberry Pi computer. Use OctoPi v0.14.0 or later - see the
[octopi releases](https://github.com/guysoft/OctoPi/releases) for
release information. One should verify that OctoPi boots and that the
OctoPrint web server works. After connecting to the OctoPrint web
page, follow the prompt to upgrade OctoPrint to v1.3.2 or later.
page, follow the prompt to upgrade OctoPrint to v1.3.5 or later.
After installing OctoPi and upgrading OctoPrint, ssh into the target
machine (ssh pi@octopi -- password is "raspberry") and run the
@@ -119,3 +121,8 @@ provides more detailed information.
In addition to common g-code commands, Klipper supports a few extended
commands - "status" and "restart" are examples of these commands. Use
the "help" command to get a list of other extended commands.
Contacting the developers
=========================
See the [contact page](Contact.md) to ask questions or report a bug.
+20 -15
View File
@@ -18,12 +18,12 @@ rapid jerking of the head can cause disruption of recently deposited
filament. Limiting speed changes of the print head (relative to the
print) reduces risks of disrupting the print.
It is also important to enforce a maximum acceleration of the stepper
motors to ensure they do not skip or put excessive stress on the
machine. Klipper limits the acceleration of each stepper by virtue of
limiting the acceleration of the print head. Enforcing acceleration at
the print head naturally also enforces acceleration at the steppers
that control that print head (the inverse is not always true).
It is also important to limit acceleration so that the stepper motors
do not skip or put excessive stress on the machine. Klipper limits the
torque on each stepper by virtue of limiting the acceleration of the
print head. Enforcing acceleration at the print head naturally also
limits the torque of the steppers that move the print head (the
inverse is not always true).
Klipper implements constant acceleration. The key formula for constant
acceleration is:
@@ -88,9 +88,9 @@ The junction speeds are determined using "approximated centripetal
acceleration". Best
[described by the author](https://onehossshay.wordpress.com/2011/09/24/improving_grbl_cornering_algorithm/).
Klipper implements look-ahead between moves contained in the XY plane
that have similar extruder flow rates. Other moves are relatively rare
and implementing look-ahead between them is unnecessary.
Klipper implements look-ahead between moves that have similar extruder
flow rates. Other moves are relatively rare and implementing
look-ahead between them is unnecessary.
Key formula for look-ahead:
```
@@ -211,13 +211,18 @@ With delta kinematics it is possible for a move that is accelerating
in cartesian space to require an acceleration on a particular stepper
motor greater than the move's acceleration. This can occur when a
stepper arm is more horizontal than vertical and the line of movement
is near that stepper's tower.
passes near that stepper's tower. Although these moves could require a
stepper motor acceleration greater than the printer's maximum
configured move acceleration, the effective mass moved by that stepper
would be smaller. Thus the higher stepper acceleration does not result
in significantly higher stepper torque and it is therefore considered
harmless.
Klipper does enforce a maximum ceiling on stepper acceleration that is
three times the maximum acceleration of a move in cartesian
space. (Similarly, the maximum velocity of the stepper is limited to
three times the maximum move velocity.) In order to enforce this
limit, moves at the extreme edge of the build envelope (where a
However, to avoid extreme cases, Klipper enforces a maximum ceiling on
stepper acceleration of three times the printer's configured maximum
move acceleration. (Similarly, the maximum velocity of the stepper is
limited to three times the maximum move velocity.) In order to enforce
this limit, moves at the extreme edge of the build envelope (where a
stepper arm may be nearly horizontal) will have a lower maximum
acceleration and velocity.
+36 -45
View File
@@ -4,10 +4,8 @@ by the Klipper micro-controller software. This document is not an
authoritative reference for these commands, nor is it an exclusive
list of all available commands.
This document may be useful for users needing to configure a set of
hardware actions that their printer may require at startup (via the
"custom" field in the printer config file), and it may be useful for
developers wishing to obtain a high-level feel for low-level commands.
This document may be useful for developers interested in understanding
the low-level micro-controller commands.
See the [protocol](Protocol.md) document for more information on the
format of commands and their transmission. The commands here are
@@ -25,22 +23,13 @@ commands available for that purpose. Unlike most micro-controller
commands, these commands run as soon as they are received and they do
not require any particular setup.
These commands are most useful in the "custom" block of the "mcu"
section of the printer configuration file. This feature is typically
used to configure the initial settings of LEDs, to configure
micro-stepping pins, to configure a digipot, etc.
Several of these commands will take a "pin=%u" parameter. The
low-level micro-controller software uses integer encodings of the
hardware pin numbers, but to make things more readable the host will
translate human readable pin names (eg, "PA3") to their equivalent
integer encodings. By convention, any parameter named "pin" or that
has a "_pin" suffix will use pin name translation by the
host. Similarly, several commands take time parameters specified in
clock ticks. One can specify a value for these parameters in seconds
using the "TICKS()" macro - for example "cycle_ticks=TICKS(0.001)"
would result in "cycle_ticks=16000" on a micro-controller with a 16Mhz
clock.
host.
Common startup commands:
@@ -50,7 +39,7 @@ Common startup commands:
may be useful for configuring the initial value of LEDs and for
configuring the initial value of stepper driver micro-stepping pins.
* `set_pwm_out pin=%u cycle_ticks=%u value=%c` : This command will
* `set_pwm_out pin=%u cycle_ticks=%u value=%hu` : This command will
immediately configure the given pin to use hardware based
pulse-width-modulation (PWM) with the given number of
cycle_ticks. The "cycle_ticks" is the number of MCU clock ticks each
@@ -129,16 +118,16 @@ Common micro-controller objects
This section lists some commonly used config commands.
* `config_digital_out oid=%c pin=%u default_value=%c
* `config_digital_out oid=%c pin=%u value=%c default_value=%c
max_duration=%u` : This command creates an internal micro-controller
object for the given GPIO 'pin'. The pin will be configured in
digital output mode and set to an initial value as specified by
'default_value' (0 for low, 1 for high). Creating a digital_out
object allows the host to schedule GPIO updates for the given pin at
'value' (0 for low, 1 for high). Creating a digital_out object
allows the host to schedule GPIO updates for the given pin at
specified times (see the schedule_digital_out command described
below). Should the micro-controller software go into shutdown mode
then all configured digital_out objects will be set back to their
default values. The 'max_duration' parameter is used to implement a
then all configured digital_out objects will be set to
'default_value'. The 'max_duration' parameter is used to implement a
safety check - if it is non-zero then it is the maximum number of
clock ticks that the host may set the given GPIO to a non-default
value without further updates. For example, if the default_value is
@@ -148,23 +137,23 @@ This section lists some commonly used config commands.
feature can be used with heater pins to ensure the host does not
enable the heater and then go off-line.
* `config_pwm_out oid=%c pin=%u cycle_ticks=%u default_value=%c
max_duration=%u` : This command creates an internal object for
hardware based PWM pins that the host may schedule updates for. Its
usage is analogous to config_digital_out - see the description of
the 'set_pwm_out' and 'config_digital_out' commands for parameter
description.
* `config_pwm_out oid=%c pin=%u cycle_ticks=%u value=%hu
default_value=%hu max_duration=%u` : This command creates an
internal object for hardware based PWM pins that the host may
schedule updates for. Its usage is analogous to config_digital_out -
see the description of the 'set_pwm_out' and 'config_digital_out'
commands for parameter description.
* `config_soft_pwm_out oid=%c pin=%u cycle_ticks=%u default_value=%c
max_duration=%u` : This command creates an internal micro-controller
object for software implemented PWM. Unlike hardware pwm pins, a
software pwm object does not require any special hardware support
(other than the ability to configure the pin as a digital output
GPIO). Because the output switching is implemented in the
micro-controller software, it is recommended that the cycle_ticks
parameter correspond to a time of 10ms or greater. See the
description of the 'set_pwm_out' and 'config_digital_out' commands
for parameter description.
* `config_soft_pwm_out oid=%c pin=%u cycle_ticks=%u value=%c
default_value=%c max_duration=%u` : This command creates an internal
micro-controller object for software implemented PWM. Unlike
hardware pwm pins, a software pwm object does not require any
special hardware support (other than the ability to configure the
pin as a digital output GPIO). Because the output switching is
implemented in the micro-controller software, it is recommended that
the cycle_ticks parameter correspond to a time of 10ms or
greater. See the description of the 'set_pwm_out' and
'config_digital_out' commands for parameter description.
* `config_analog_in oid=%c pin=%u` : This command is used to configure
a pin in analog input sampling mode. Once configured, the pin can be
@@ -205,11 +194,11 @@ only of interest to developers looking to gain insight into Klipper.
same 'oid' parameter must have been issued during micro-controller
configuration.
* `schedule_pwm_out oid=%c clock=%u value=%c` : Schedules a change to
* `schedule_pwm_out oid=%c clock=%u value=%hu` : Schedules a change to
a hardware PWM output pin. See the 'schedule_digital_out' and
'config_pwm_out' commands for more info.
* `schedule_soft_pwm_out oid=%c clock=%u value=%c` : Schedules a
* `schedule_soft_pwm_out oid=%c clock=%u value=%hu` : Schedules a
change to a software PWM output pin. See the 'schedule_digital_out'
and 'config_soft_pwm_out' commands for more info.
@@ -266,13 +255,15 @@ Stepper commands
number of steps generated with dir=1 minus the total number of steps
generated with dir=0.
* `end_stop_home oid=%c clock=%u rest_ticks=%u pin_value=%c` : This
command is used during stepper "homing" operations. To use this
command a 'config_end_stop' command with the same 'oid' parameter
must have been issued during micro-controller configuration. When
this command is invoked, the micro-controller will sample the
endstop pin every 'rest_ticks' clock ticks and check if it has a
value equal to 'pin_value'. If the value matches then the movement
* `end_stop_home oid=%c clock=%u sample_ticks=%u sample_count=%c
rest_ticks=%u pin_value=%c` : This command is used during stepper
"homing" operations. To use this command a 'config_end_stop' command
with the same 'oid' parameter must have been issued during
micro-controller configuration. When this command is invoked, the
micro-controller will sample the endstop pin every 'rest_ticks'
clock ticks and check if it has a value equal to 'pin_value'. If the
value matches (and it continues to match for 'sample_count'
additional samples spread 'sample_ticks' apart) then the movement
queue for the associated stepper will be cleared and the stepper
will come to an immediate halt. The host uses this command to
implement homing - the host instructs the endstop to sample for the
+2 -1
View File
@@ -16,7 +16,8 @@ The [kinematics](Kinematics.md) document provides some technical
details on how Klipper implements motion.
The history of Klipper releases is available at
[releases](Releases.md).
[releases](Releases.md). See [contact](Contact.md) for information on
bug reporting and general communication with the developers.
Developer Documentation
=======================
+25 -5
View File
@@ -4,6 +4,18 @@ pressure advance feature can be helpful in reducing ooze. For more
information on how pressure advance is implemented see the
[kinematics](Kinematics.md) document.
Prerequisites
=============
In order to tune the pressure advance setting the printer must be
configured and operational. The tuning test involves printing objects
and inspecting the differences between objects. In particular, the
extruder
[E steps](http://reprap.org/wiki/Triffid_Hunter%27s_Calibration_Guide#E_steps)
and
[nozzle temperature](http://reprap.org/wiki/Triffid_Hunter%27s_Calibration_Guide#Nozzle_Temperature)
should be tuned prior to tuning pressure advance.
Tuning pressure advance
=======================
@@ -35,11 +47,13 @@ object. (Be sure to issue RESTART between each config change.) The
goal is to attempt to eliminate the blobbing during cornering. (With
pressure advance, the extruder will retract when the head slows down,
thus countering the pressure buildup and ideally eliminate the
blobbing.) If a test run is done with a pressure_advance setting that
is too high, one typically sees a dimple in the corner followed by
possible blobbing after the corner (too much filament is retracted
during slow down and then too much filament is extruded during the
following speed up after cornering):
blobbing.)
If a test run is done with a pressure_advance setting that is too
high, one typically sees a dimple in the corner followed by possible
blobbing after the corner (too much filament is retracted during slow
down and then too much filament is extruded during the following speed
up after cornering):
![corner-dimple](img/corner-dimple.jpg)
@@ -51,6 +65,12 @@ in good quality corners:
Typical pressure_advance values are between 0.05 and 0.20 (the high
end usually only with bowden extruders).
It is not unusual for one corner of the test print to be consistently
different than the other three corners. This typically occurs when the
slicer arranges to always change Z height at that corner. If this
occurs, then ignore that corner and tune pressure_advance using the
other three corners.
Once a good pressure_advance value is found, return
pressure_advance_lookahead_time to its default (0.010). This parameter
controls how far in advance to check if a head slow-down is
+20
View File
@@ -1,6 +1,26 @@
History of Klipper releases. Please see
[installation](Installation.md) for information on installing Klipper.
Klipper 0.5.0
=============
Available on 20171025. Major changes in this release:
* Support for printers with multiple extruders.
* Initial support for running on the Beaglebone PRU. Initial support
for the Replicape board.
* Initial support for running the micro-controller code in a real-time
Linux process.
* Support for multiple micro-controllers. (For example, one could
control an extruder with one micro-controller and the rest of the
printer with another.) Software clock synchronization is implemented
to coordinate actions between micro-controllers.
* Stepper performance improvements (20Mhz AVRs up to 189K steps per
second).
* Support for controlling servos and support for defining nozzle
cooling fans.
* Several bug fixes and code cleanups
Klipper 0.4.0
=============
-11
View File
@@ -60,8 +60,6 @@ Testing features
Documentation
=============
* Document and test running the host software on a Beagle Bone Black.
* Add documentation describing how to perform bed-leveling accurately
in Klipper. Improve description of stepper phase based bed leveling.
@@ -69,16 +67,12 @@ Hardware features
=================
* Port to additional micro-controller architectures:
* Beagle Bone Black PRU
* Smoothieboard / NXP LPC1769 (ARM cortex-M3)
* Unix based scheduling; Unix based real-time scheduling
* Support for additional kinematics: scara, etc.
* Support shared motor enable GPIO lines.
* Support for multiple extruders.
* Support for bed-level probes.
* Possible support for touch panels attached to the micro-controller.
@@ -87,14 +81,9 @@ Hardware features
it would also be useful to handle panels already hardwired to the
micro-controller.)
* Possibly support printers using multiple micro-controllers.
Misc features
=============
* Possibly use cubic functions instead of quadratic functions in step
compression code.
* Possibly support a "feed forward PID" that takes into account the
amount of plastic being extruded. If the extrude rate changes
significantly during a print it can cause heating bumps that the PID
+94
View File
@@ -0,0 +1,94 @@
This document describes the process of running Klipper on a Beaglebone
PRU.
Building an OS image
====================
Start by installing the
[latest Jessie IoT](https://beagleboard.org/latest-images) image
(2017-03-19 or later). One may run the image from either a micro-SD
card or from builtin eMMC. If using the eMMC, install it to eMMC now
by following the instructions from the above link.
Then ssh into the beaglebone machine (ssh debian@beaglebone --
password is "temppwd") and install Klipper by running the following
commands:
```
git clone https://github.com/KevinOConnor/klipper
./klipper/scripts/install-beaglebone.sh
```
Install Octoprint
=================
One may then install Octoprint:
```
git clone https://github.com/foosel/OctoPrint.git
cd OctoPrint/
virtualenv venv
./venv/bin/python setup.py install
```
And setup OctoPrint to start at bootup:
```
sudo cp ~/OctoPrint/scripts/octoprint.init /etc/init.d/octoprint
sudo chmod +x /etc/init.d/octoprint
sudo cp ~/OctoPrint/scripts/octoprint.default /etc/default/octoprint
sudo update-rc.d octoprint defaults
```
It is necessary to modify OctoPrint's **/etc/default/octoprint**
configuration file. One must change the OCTOPRINT_USER user to
"debian", change NICELEVEL to 0, uncomment the BASEDIR, CONFIGFILE,
and DAEMON settings and change the references from "/home/pi/" to
"/home/debian/":
```
sudo nano /etc/default/octoprint
```
Then start the Octoprint service:
```
sudo systemctl start octoprint
```
Make sure the octoprint web server is accessible - it should be at:
[http://beaglebone:5000/](http://beaglebone:5000/)
Building the micro-controller code
==================================
To compile the Klipper micro-controller code, start by configuring it
for the "Beaglebone PRU":
```
cd ~/klipper/
make menuconfig
```
To build and install the new micro-controller code, run:
```
sudo service klipper stop
make flash
sudo service klipper start
```
For the Replicape, it is also necessary to compile and install the
micro-controller code for a Linux host process. Run "make menuconfig"
a second time and configure it for a "Linux process":
```
make menuconfig
```
Then install this micro-controller code as well:
```
sudo service klipper stop
make flash
sudo service klipper start
```
Remaining configuration
=======================
Complete the installation by configuring Klipper and Octoprint
following the instructions in
[the main installation document](Installation.md#configuring-klipper).
+2
View File
@@ -11,4 +11,6 @@ difference() {
cube([square_size, square_size, square_height]);
translate([square_width, square_width, -1])
cube([square_size-2*square_width, square_size-2*square_width, square_height+2]);
translate([-.5, square_size/2 - 4, -1])
cube([1, 2, square_height+2]);
}
+134 -22
View File
@@ -2,6 +2,20 @@ solid OpenSCAD_Model
facet normal -1 0 0
outer loop
vertex 0 0 0
vertex 0 26 5
vertex 0 26 0
endloop
endfacet
facet normal -1 -0 0
outer loop
vertex 0 26 5
vertex 0 0 0
vertex 0 0 5
endloop
endfacet
facet normal -1 0 0
outer loop
vertex 0 28 0
vertex 0 60 5
vertex 0 60 0
endloop
@@ -9,8 +23,8 @@ solid OpenSCAD_Model
facet normal -1 -0 0
outer loop
vertex 0 60 5
vertex 0 0 0
vertex 0 0 5
vertex 0 28 0
vertex 0 28 5
endloop
endfacet
facet normal 0 0 1
@@ -30,7 +44,7 @@ solid OpenSCAD_Model
facet normal 0 0 1
outer loop
vertex 5 55 5
vertex 0 60 5
vertex 0.5 28 5
vertex 5 5 5
endloop
endfacet
@@ -41,6 +55,20 @@ solid OpenSCAD_Model
vertex 60 60 5
endloop
endfacet
facet normal 0 0 1
outer loop
vertex 0 28 5
vertex 5 55 5
vertex 0 60 5
endloop
endfacet
facet normal 0 0 1
outer loop
vertex 5 55 5
vertex 0 28 5
vertex 0.5 28 5
endloop
endfacet
facet normal -0 0 1
outer loop
vertex 55 5 5
@@ -55,6 +83,20 @@ solid OpenSCAD_Model
vertex 55 5 5
endloop
endfacet
facet normal -0 0 1
outer loop
vertex 0.5 26 5
vertex 5 5 5
vertex 0.5 28 5
endloop
endfacet
facet normal -0 0 1
outer loop
vertex 0 26 5
vertex 5 5 5
vertex 0.5 26 5
endloop
endfacet
facet normal 0 0 1
outer loop
vertex 5 5 5
@@ -66,7 +108,7 @@ solid OpenSCAD_Model
outer loop
vertex 0 0 5
vertex 5 5 5
vertex 0 60 5
vertex 0 26 5
endloop
endfacet
facet normal 1 -0 0
@@ -111,11 +153,11 @@ solid OpenSCAD_Model
vertex 55 5 0
endloop
endfacet
facet normal -0 0 -1
facet normal 0 0 -1
outer loop
vertex 0.5 28 0
vertex 5 5 0
vertex 0 0 0
vertex 5 55 0
vertex 0.5 26 0
endloop
endfacet
facet normal 0 0 -1
@@ -125,6 +167,20 @@ solid OpenSCAD_Model
vertex 60 0 0
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 0 26 0
vertex 5 5 0
vertex 0 0 0
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 5 5 0
vertex 0 26 0
vertex 0.5 26 0
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 55 55 0
@@ -139,6 +195,20 @@ solid OpenSCAD_Model
vertex 55 55 0
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 5 5 0
vertex 0.5 28 0
vertex 5 55 0
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 0 28 0
vertex 5 55 0
vertex 0.5 28 0
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 5 55 0
@@ -150,7 +220,7 @@ solid OpenSCAD_Model
outer loop
vertex 0 60 0
vertex 5 55 0
vertex 0 0 0
vertex 0 28 0
endloop
endfacet
facet normal 0 -1 0
@@ -195,20 +265,6 @@ solid OpenSCAD_Model
vertex 55 5 5
endloop
endfacet
facet normal 0 1 -0
outer loop
vertex 55 5 0
vertex 5 5 5
vertex 55 5 5
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 5 5 5
vertex 55 5 0
vertex 5 5 0
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 5 55 0
@@ -223,4 +279,60 @@ solid OpenSCAD_Model
vertex 55 55 0
endloop
endfacet
facet normal 0 1 -0
outer loop
vertex 55 5 0
vertex 5 5 5
vertex 55 5 5
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 5 5 5
vertex 55 5 0
vertex 5 5 0
endloop
endfacet
facet normal -1 0 0
outer loop
vertex 0.5 26 0
vertex 0.5 28 5
vertex 0.5 28 0
endloop
endfacet
facet normal -1 -0 0
outer loop
vertex 0.5 28 5
vertex 0.5 26 0
vertex 0.5 26 5
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 0 28 0
vertex 0.5 28 5
vertex 0 28 5
endloop
endfacet
facet normal 0 -1 -0
outer loop
vertex 0.5 28 5
vertex 0 28 0
vertex 0.5 28 0
endloop
endfacet
facet normal 0 1 -0
outer loop
vertex 0.5 26 0
vertex 0 26 5
vertex 0.5 26 5
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 0 26 5
vertex 0.5 26 0
vertex 0 26 0
endloop
endfacet
endsolid OpenSCAD_Model
+29 -26
View File
@@ -9,20 +9,23 @@ import stepper, homing
StepList = (0, 1, 2)
class CartKinematics:
def __init__(self, printer, config):
self.steppers = [stepper.PrinterStepper(
def __init__(self, toolhead, printer, config):
self.steppers = [stepper.PrinterHomingStepper(
printer, config.getsection('stepper_' + n), n)
for n in ['x', 'y', 'z']]
max_velocity, max_accel = toolhead.get_max_velocity()
self.max_z_velocity = config.getfloat(
'max_z_velocity', 9999999.9, above=0.)
'max_z_velocity', max_velocity, above=0., maxval=max_velocity)
self.max_z_accel = config.getfloat(
'max_z_accel', 9999999.9, above=0.)
'max_z_accel', max_accel, above=0., maxval=max_accel)
self.need_motor_enable = True
self.limits = [(1.0, -1.0)] * 3
def set_max_jerk(self, max_xy_halt_velocity, max_velocity, max_accel):
self.steppers[0].set_max_jerk(max_xy_halt_velocity, max_accel)
self.steppers[1].set_max_jerk(max_xy_halt_velocity, max_accel)
self.steppers[2].set_max_jerk(0., self.max_z_accel)
# Setup stepper max halt velocity
max_halt_velocity = toolhead.get_max_axis_halt()
self.steppers[0].set_max_jerk(max_halt_velocity, max_accel)
self.steppers[1].set_max_jerk(max_halt_velocity, max_accel)
self.steppers[2].set_max_jerk(
min(max_halt_velocity, self.max_z_velocity), max_accel)
def set_position(self, newpos):
for i in StepList:
self.steppers[i].mcu_stepper.set_position(newpos[i])
@@ -43,36 +46,36 @@ class CartKinematics:
rpos = s.position_endstop + s.homing_retract_dist
r2pos = rpos + s.homing_retract_dist
# Initial homing
homing_speed = s.get_homing_speed()
homepos = [None, None, None, None]
homepos[axis] = s.position_endstop
coord = [None, None, None, None]
coord[axis] = pos
homing_state.home(list(coord), homepos, [s], s.homing_speed)
homing_state.home(list(coord), homepos, [s], homing_speed)
# Retract
coord[axis] = rpos
homing_state.retract(list(coord), s.homing_speed)
homing_state.retract(list(coord), homing_speed)
# Home again
coord[axis] = r2pos
homing_state.home(
list(coord), homepos, [s], s.homing_speed/2.0, second_home=True)
list(coord), homepos, [s], homing_speed/2.0, second_home=True)
# Set final homed position
coord[axis] = s.position_endstop + s.get_homed_offset()
homing_state.set_homed_position(coord)
def motor_off(self, move_time):
def query_endstops(self, print_time, query_flags):
return homing.query_endstops(print_time, query_flags, self.steppers)
def motor_off(self, print_time):
self.limits = [(1.0, -1.0)] * 3
for stepper in self.steppers:
stepper.motor_enable(move_time, 0)
stepper.motor_enable(print_time, 0)
self.need_motor_enable = True
def _check_motor_enable(self, move_time, move):
def _check_motor_enable(self, print_time, move):
need_motor_enable = False
for i in StepList:
if move.axes_d[i]:
self.steppers[i].motor_enable(move_time, 1)
self.steppers[i].motor_enable(print_time, 1)
need_motor_enable |= self.steppers[i].need_motor_enable
self.need_motor_enable = need_motor_enable
def query_endstops(self, print_time):
endstops = [(s, s.query_endstop(print_time)) for s in self.steppers]
return [(s.name, es.query_endstop_wait()) for s, es in endstops]
def _check_endstops(self, move):
end_pos = move.end_pos
for i in StepList:
@@ -97,15 +100,15 @@ class CartKinematics:
z_ratio = move.move_d / abs(move.axes_d[2])
move.limit_speed(
self.max_z_velocity * z_ratio, self.max_z_accel * z_ratio)
def move(self, move_time, move):
def move(self, print_time, move):
if self.need_motor_enable:
self._check_motor_enable(move_time, move)
self._check_motor_enable(print_time, move)
for i in StepList:
axis_d = move.axes_d[i]
if not axis_d:
continue
mcu_stepper = self.steppers[i].mcu_stepper
mcu_time = mcu_stepper.print_to_mcu_time(move_time)
move_time = print_time
start_pos = move.start_pos[i]
axis_r = abs(axis_d) / move.move_d
accel = move.accel * axis_r
@@ -115,18 +118,18 @@ class CartKinematics:
if move.accel_r:
accel_d = move.accel_r * axis_d
mcu_stepper.step_const(
mcu_time, start_pos, accel_d, move.start_v * axis_r, accel)
move_time, start_pos, accel_d, move.start_v * axis_r, accel)
start_pos += accel_d
mcu_time += move.accel_t
move_time += move.accel_t
# Cruising steps
if move.cruise_r:
cruise_d = move.cruise_r * axis_d
mcu_stepper.step_const(
mcu_time, start_pos, cruise_d, cruise_v, 0.)
move_time, start_pos, cruise_d, cruise_v, 0.)
start_pos += cruise_d
mcu_time += move.cruise_t
move_time += move.cruise_t
# Deceleration steps
if move.decel_r:
decel_d = move.decel_r * axis_d
mcu_stepper.step_const(
mcu_time, start_pos, decel_d, cruise_v, -accel)
move_time, start_pos, decel_d, cruise_v, -accel)
+6 -4
View File
@@ -25,7 +25,7 @@ defs_stepcompress = """
int stepcompress_set_homing(struct stepcompress *sc, uint64_t homing_clock);
int stepcompress_queue_msg(struct stepcompress *sc, uint32_t *data, int len);
int stepcompress_push(struct stepcompress *sc, double step_clock
int32_t stepcompress_push(struct stepcompress *sc, double step_clock
, int32_t sdir);
int32_t stepcompress_push_const(struct stepcompress *sc, double clock_offset
, double step_offset, double steps, double start_sv, double accel);
@@ -36,6 +36,8 @@ defs_stepcompress = """
struct steppersync *steppersync_alloc(struct serialqueue *sq
, struct stepcompress **sc_list, int sc_num, int move_num);
void steppersync_free(struct steppersync *ss);
void steppersync_set_time(struct steppersync *ss
, double time_offset, double mcu_freq);
int steppersync_flush(struct steppersync *ss, uint64_t move_clock);
"""
@@ -59,8 +61,8 @@ defs_serialqueue = """
, uint64_t min_clock, uint64_t req_clock);
void serialqueue_pull(struct serialqueue *sq, struct pull_queue_message *pqm);
void serialqueue_set_baud_adjust(struct serialqueue *sq, double baud_adjust);
void serialqueue_set_clock_est(struct serialqueue *sq, double est_clock
, double last_ack_time, uint64_t last_ack_clock);
void serialqueue_set_clock_est(struct serialqueue *sq, double est_freq
, double last_clock_time, uint64_t last_clock);
void serialqueue_get_stats(struct serialqueue *sq, char *buf, int len);
int serialqueue_extract_old(struct serialqueue *sq, int sentq
, struct pull_queue_message *q, int max);
@@ -88,7 +90,7 @@ def check_build_code(srcdir, target, sources, cmd, other_files=[]):
src_times = get_mtimes(srcdir, sources + other_files)
obj_times = get_mtimes(srcdir, [target])
if not obj_times or max(src_times) > min(obj_times):
logging.info("Building C code module %s" % (target,))
logging.info("Building C code module %s", target)
srcfiles = [os.path.join(srcdir, fname) for fname in sources]
destlib = os.path.join(srcdir, target)
os.system(cmd % (destlib, ' '.join(srcfiles)))
+296
View File
@@ -0,0 +1,296 @@
# Code to configure miscellaneous chips
#
# Copyright (C) 2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import pins, mcu
######################################################################
# Statically configured output pins
######################################################################
class PrinterStaticDigitalOut:
def __init__(self, printer, config):
pin_list = [pin.strip() for pin in config.get('pins').split(',')]
for pin_desc in pin_list:
mcu_pin = pins.setup_pin(printer, 'digital_out', pin_desc)
mcu_pin.setup_static()
class PrinterStaticPWM:
def __init__(self, printer, config):
mcu_pwm = pins.setup_pin(printer, 'pwm', config.get('pin'))
mcu_pwm.setup_max_duration(0.)
hard_pwm = config.getint('hard_pwm', None, minval=1)
if hard_pwm is None:
mcu_pwm.setup_cycle_time(config.getfloat(
'cycle_time', 0.100, above=0.))
else:
mcu_pwm.setup_hard_pwm(hard_pwm)
scale = config.getfloat('scale', 1., above=0.)
value = config.getfloat('value', minval=0., maxval=scale)
mcu_pwm.setup_static_pwm(value / scale)
######################################################################
# Servos
######################################################################
SERVO_MIN_TIME = 0.100
SERVO_SIGNAL_PERIOD = 0.020
class PrinterServo:
def __init__(self, printer, config):
self.mcu_servo = pins.setup_pin(printer, 'pwm', config.get('pin'))
self.mcu_servo.setup_max_duration(0.)
self.mcu_servo.setup_cycle_time(SERVO_SIGNAL_PERIOD)
self.min_width = config.getfloat(
'minimum_pulse_width', .001, above=0., below=SERVO_SIGNAL_PERIOD)
self.max_width = config.getfloat(
'maximum_pulse_width', .002
, above=self.min_width, below=SERVO_SIGNAL_PERIOD)
self.max_angle = config.getfloat('maximum_servo_angle', 180.)
self.angle_to_width = (self.max_width - self.min_width) / self.max_angle
self.width_to_value = 1. / SERVO_SIGNAL_PERIOD
self.last_value = self.last_value_time = 0.
def set_pwm(self, print_time, value):
if value == self.last_value:
return
print_time = max(self.last_value_time + SERVO_MIN_TIME, print_time)
self.mcu_servo.set_pwm(print_time, value)
self.last_value = value
self.last_value_time = print_time
# External commands
def set_angle(self, print_time, angle):
angle = max(0., min(self.max_angle, angle))
width = self.min_width + angle * self.angle_to_width
self.set_pwm(print_time, width * self.width_to_value)
def set_pulse_width(self, print_time, width):
width = max(self.min_width, min(self.max_width, width))
self.set_pwm(print_time, width * self.width_to_value)
def get_printer_servo(printer, name):
return printer.objects.get('servo ' + name)
######################################################################
# AD5206 digipot
######################################################################
class ad5206:
def __init__(self, printer, config):
enable_pin_params = pins.get_printer_pins(printer).parse_pin_desc(
config.get('enable_pin'))
self.mcu = enable_pin_params['chip']
self.pin = enable_pin_params['pin']
self.mcu.add_config_object(self)
scale = config.getfloat('scale', 1., above=0.)
self.channels = [None] * 6
for i in range(len(self.channels)):
val = config.getfloat('channel_%d' % (i+1,), None,
minval=0., maxval=scale)
if val is not None:
self.channels[i] = int(val * 256. / scale + .5)
def build_config(self):
for i, val in enumerate(self.channels):
if val is not None:
self.mcu.add_config_cmd(
"send_spi_message pin=%s msg=%02x%02x" % (self.pin, i, val))
######################################################################
# Replicape board
######################################################################
REPLICAPE_MAX_CURRENT = 3.84
REPLICAPE_SHIFT_REGISTER_BUS = 1
REPLICAPE_SHIFT_REGISTER_DEVICE = 1
REPLICAPE_PCA9685_BUS = 2
REPLICAPE_PCA9685_ADDRESS = 0x70
REPLICAPE_PCA9685_CYCLE_TIME = .001
class pca9685_pwm:
def __init__(self, replicape, channel, pin_params):
self._replicape = replicape
self._channel = channel
if pin_params['type'] not in ['digital_out', 'pwm']:
raise pins.error("Pin type not supported on replicape")
self._mcu = replicape.host_mcu
self._mcu.add_config_object(self)
self._bus = REPLICAPE_PCA9685_BUS
self._address = REPLICAPE_PCA9685_ADDRESS
self._cycle_time = REPLICAPE_PCA9685_CYCLE_TIME
self._max_duration = 2.
self._oid = None
self._invert = pin_params['invert']
self._shutdown_value = float(self._invert)
self._last_clock = 0
self._pwm_max = 0.
self._cmd_queue = self._mcu.alloc_command_queue()
self._set_cmd = None
self._static_value = None
def get_mcu(self):
return self._mcu
def setup_max_duration(self, max_duration):
self._max_duration = max_duration
def setup_cycle_time(self, cycle_time):
pass
def setup_hard_pwm(self, hard_cycle_ticks):
if hard_cycle_ticks:
raise pins.error("pca9685 does not support hard_pwm parameter")
def setup_static_pwm(self, value):
if self._invert:
value = 1. - value
self._static_value = max(0., min(1., value))
def setup_shutdown_value(self, value):
if self._invert:
value = 1. - value
self._shutdown_value = max(0., min(1., value))
if self._shutdown_value:
self._replicape.note_enable_on_shutdown()
def build_config(self):
self._pwm_max = self._mcu.get_constant_float("PCA9685_MAX")
cycle_ticks = self._mcu.seconds_to_clock(self._cycle_time)
if self._static_value is not None:
value = int(self._static_value * self._pwm_max + 0.5)
self._mcu.add_config_cmd(
"set_pca9685_out bus=%d addr=%d channel=%d"
" cycle_ticks=%d value=%d" % (
self._bus, self._address, self._channel,
cycle_ticks, value))
return
self._oid = self._mcu.create_oid()
self._mcu.add_config_cmd(
"config_pca9685 oid=%d bus=%d addr=%d channel=%d cycle_ticks=%d"
" value=%d default_value=%d max_duration=%d" % (
self._oid, self._bus, self._address, self._channel, cycle_ticks,
self._invert * self._pwm_max,
self._shutdown_value * self._pwm_max,
self._mcu.seconds_to_clock(self._max_duration)))
self._set_cmd = self._mcu.lookup_command(
"schedule_pca9685_out oid=%c clock=%u value=%hu")
def set_pwm(self, print_time, value):
clock = self._mcu.print_time_to_clock(print_time)
if self._invert:
value = 1. - value
value = int(max(0., min(1., value)) * self._pwm_max + 0.5)
self._replicape.note_enable(print_time, self._channel, not not value)
msg = self._set_cmd.encode(self._oid, clock, value)
self._mcu.send(msg, minclock=self._last_clock, reqclock=clock
, cq=self._cmd_queue)
self._last_clock = clock
def set_digital(self, print_time, value):
if value:
self.set_pwm(print_time, 1.)
else:
self.set_pwm(print_time, 0.)
class ReplicapeDACEnable:
def __init__(self, replicape, channel, pin_params):
if pin_params['type'] != 'digital_out':
raise pins.error("Replicape virtual enable pin must be digital_out")
if pin_params['invert']:
raise pins.error("Replicape virtual enable pin can not be inverted")
self.mcu = replicape.host_mcu
self.value = replicape.stepper_dacs[channel]
self.pwm = pca9685_pwm(replicape, channel, pin_params)
self.last = 0
def get_mcu(self):
return self.mcu
def setup_max_duration(self, max_duration):
self.pwm.setup_max_duration(max_duration)
def set_digital(self, print_time, value):
if value:
self.pwm.set_pwm(print_time, self.value)
else:
self.pwm.set_pwm(print_time, 0.)
self.last = value
def get_last_setting(self):
return self.last
ReplicapeStepConfig = {
'disable': None,
'1': (1<<7)|(1<<5), '2': (1<<7)|(1<<5)|(1<<6), 'spread2': (1<<5),
'4': (1<<7)|(1<<5)|(1<<4), '16': (1<<7)|(1<<5)|(1<<6)|(1<<4),
'spread4': (1<<5)|(1<<4), 'spread16': (1<<7), 'stealth4': (1<<7)|(1<<6),
'stealth16': 0
}
class Replicape:
def __init__(self, printer, config):
pins.get_printer_pins(printer).register_chip('replicape', self)
revisions = {'B3': 'B3'}
config.getchoice('revision', revisions)
self.host_mcu = mcu.get_printer_mcu(printer, config.get('host_mcu'))
# Setup enable pin
self.mcu_enable = pins.setup_pin(
printer, 'digital_out', config.get('enable_pin', '!P9_41'))
self.mcu_enable.setup_max_duration(0.)
self.enabled_channels = {}
# Setup power pins
self.pins = {
"power_e": (pca9685_pwm, 5), "power_h": (pca9685_pwm, 3),
"power_hotbed": (pca9685_pwm, 4),
"power_fan0": (pca9685_pwm, 7), "power_fan1": (pca9685_pwm, 8),
"power_fan2": (pca9685_pwm, 9), "power_fan3": (pca9685_pwm, 10) }
# Setup stepper config
self.stepper_dacs = {}
shift_registers = [1] * 5
for port, name in enumerate('xyzeh'):
prefix = 'stepper_%s_' % (name,)
sc = config.getchoice(
prefix + 'microstep_mode', ReplicapeStepConfig, 'disable')
if sc is None:
continue
if config.getboolean(prefix + 'chopper_off_time_high', False):
sc |= 1<<3
if config.getboolean(prefix + 'chopper_hysteresis_high', False):
sc |= 1<<2
if config.getboolean(prefix + 'chopper_blank_time_high', True):
sc |= 1<<1
shift_registers[port] = sc
channel = port + 11
cur = config.getfloat(
prefix + 'current', above=0., maxval=REPLICAPE_MAX_CURRENT)
self.stepper_dacs[channel] = cur / REPLICAPE_MAX_CURRENT
self.pins[prefix + 'enable'] = (ReplicapeDACEnable, channel)
shift_registers.reverse()
self.host_mcu.add_config_cmd("send_spi bus=%d dev=%d msg=%s" % (
REPLICAPE_SHIFT_REGISTER_BUS, REPLICAPE_SHIFT_REGISTER_DEVICE,
"".join(["%02x" % (x,) for x in shift_registers])))
def note_enable_on_shutdown(self):
self.mcu_enable.setup_shutdown_value(1)
def note_enable(self, print_time, channel, is_enable):
if is_enable:
is_off = not self.enabled_channels
self.enabled_channels[channel] = 1
if is_off:
self.mcu_enable.set_digital(print_time, 1)
elif channel in self.enabled_channels:
del self.enabled_channels[channel]
if not self.enabled_channels:
self.mcu_enable.set_digital(print_time, 0)
def setup_pin(self, pin_params):
pin = pin_params['pin']
if pin not in self.pins:
raise pins.error("Unknown replicape pin %s" % (pin,))
pclass, channel = self.pins[pin]
return pclass(self, channel, pin_params)
######################################################################
# Setup
######################################################################
def add_printer_objects(printer, config):
if config.has_section('replicape'):
printer.add_object('replicape', Replicape(
printer, config.getsection('replicape')))
for s in config.get_prefix_sections('static_digital_output '):
printer.add_object(s.section, PrinterStaticDigitalOut(printer, s))
for s in config.get_prefix_sections('static_pwm_output '):
printer.add_object(s.section, PrinterStaticPWM(printer, s))
for s in config.get_prefix_sections('servo '):
printer.add_object(s.section, PrinterServo(printer, s))
for s in config.get_prefix_sections('ad5206 '):
printer.add_object(s.section, ad5206(printer, s))
+212
View File
@@ -0,0 +1,212 @@
# Micro-controller clock synchronization
#
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging, threading, math
COMM_TIMEOUT = 3.5
RTT_AGE = .000010 / (60. * 60.)
DECAY = 1. / (2. * 60.)
TRANSMIT_EXTRA = .001
class ClockSync:
def __init__(self, reactor):
self.reactor = reactor
self.serial = None
self.status_timer = self.reactor.register_timer(self._status_event)
self.status_cmd = None
self.mcu_freq = 1.
self.last_clock = 0
self.clock_est = (0., 0., 0.)
# Minimum round-trip-time tracking
self.min_half_rtt = 999999999.9
self.min_rtt_time = 0.
# Linear regression of mcu clock and system sent_time
self.time_avg = self.time_variance = 0.
self.clock_avg = self.clock_covariance = 0.
self.prediction_variance = 0.
self.last_prediction_time = 0.
def connect(self, serial):
self.serial = serial
msgparser = serial.msgparser
self.mcu_freq = msgparser.get_constant_float('CLOCK_FREQ')
# Load initial clock and frequency
uptime_msg = msgparser.create_command('get_uptime')
params = serial.send_with_response(uptime_msg, 'uptime')
self.last_clock = (params['high'] << 32) | params['clock']
self.clock_avg = self.last_clock
self.time_avg = params['#sent_time']
self.clock_est = (self.time_avg, self.clock_avg, self.mcu_freq)
self.prediction_variance = (.001 * self.mcu_freq)**2
# Enable periodic get_status timer
self.status_cmd = msgparser.create_command('get_status')
for i in range(8):
params = serial.send_with_response(self.status_cmd, 'status')
self._handle_status(params)
self.reactor.pause(0.100)
serial.register_callback(self._handle_status, 'status')
self.reactor.update_timer(self.status_timer, self.reactor.NOW)
def connect_file(self, serial, pace=False):
self.serial = serial
self.mcu_freq = serial.msgparser.get_constant_float('CLOCK_FREQ')
self.clock_est = (0., 0., self.mcu_freq)
freq = 1000000000000.
if pace:
freq = self.mcu_freq
serial.set_clock_est(freq, self.reactor.monotonic(), 0)
# MCU clock querying (status callback invoked from background thread)
def _status_event(self, eventtime):
self.serial.send(self.status_cmd)
return eventtime + 1.0
def _handle_status(self, params):
# Extend clock to 64bit
last_clock = self.last_clock
clock = (last_clock & ~0xffffffff) | params['clock']
if clock < last_clock:
clock += 0x100000000
self.last_clock = clock
# Check if this is the best round-trip-time seen so far
sent_time = params['#sent_time']
if not sent_time:
return
receive_time = params['#receive_time']
half_rtt = .5 * (receive_time - sent_time)
aged_rtt = (sent_time - self.min_rtt_time) * RTT_AGE
if half_rtt < self.min_half_rtt + aged_rtt:
self.min_half_rtt = half_rtt
self.min_rtt_time = sent_time
logging.debug("new minimum rtt %.3f: hrtt=%.6f freq=%d",
sent_time, half_rtt, self.clock_est[2])
# Filter out samples that are extreme outliers
exp_clock = ((sent_time - self.time_avg) * self.clock_est[2]
+ self.clock_avg)
clock_diff2 = (clock - exp_clock)**2
if (clock_diff2 > 25. * self.prediction_variance
and clock_diff2 > (.000500 * self.mcu_freq)**2):
if clock > exp_clock and sent_time < self.last_prediction_time + 10.:
logging.debug("Ignoring clock sample %.3f:"
" freq=%d diff=%d stddev=%.3f",
sent_time, self.clock_est[2], clock - exp_clock,
math.sqrt(self.prediction_variance))
return
logging.info("Resetting prediction variance %.3f:"
" freq=%d diff=%d stddev=%.3f",
sent_time, self.clock_est[2], clock - exp_clock,
math.sqrt(self.prediction_variance))
self.prediction_variance = (.001 * self.mcu_freq)**2
else:
self.last_prediction_time = sent_time
self.prediction_variance = (
(1. - DECAY) * (self.prediction_variance + clock_diff2 * DECAY))
# Add clock and sent_time to linear regression
diff_sent_time = sent_time - self.time_avg
self.time_avg += DECAY * diff_sent_time
self.time_variance = (1. - DECAY) * (
self.time_variance + diff_sent_time**2 * DECAY)
diff_clock = clock - self.clock_avg
self.clock_avg += DECAY * diff_clock
self.clock_covariance = (1. - DECAY) * (
self.clock_covariance + diff_sent_time * diff_clock * DECAY)
# Update prediction from linear regression
new_freq = self.clock_covariance / self.time_variance
pred_stddev = math.sqrt(self.prediction_variance)
self.serial.set_clock_est(new_freq, self.time_avg + TRANSMIT_EXTRA,
int(self.clock_avg - 3. * pred_stddev))
self.clock_est = (self.time_avg - self.min_half_rtt,
self.clock_avg, new_freq)
#logging.debug("regr %.3f: freq=%.3f d=%d(%.3f)",
# sent_time, new_freq, clock - exp_clock, pred_stddev)
# clock frequency conversions
def print_time_to_clock(self, print_time):
return int(print_time * self.mcu_freq)
def clock_to_print_time(self, clock):
return clock / self.mcu_freq
def get_adjusted_freq(self):
return self.mcu_freq
# system time conversions
def get_clock(self, eventtime):
sample_time, clock, freq = self.clock_est
return int(clock + (eventtime - sample_time) * freq)
def estimated_print_time(self, eventtime):
return self.clock_to_print_time(self.get_clock(eventtime))
# misc commands
def clock32_to_clock64(self, clock32):
last_clock = self.last_clock
clock_diff = (last_clock - clock32) & 0xffffffff
if clock_diff & 0x80000000:
return last_clock + 0x100000000 - clock_diff
return last_clock - clock_diff
def is_active(self, eventtime):
print_time = self.estimated_print_time(eventtime)
last_clock_print_time = self.clock_to_print_time(self.last_clock)
return print_time < last_clock_print_time + COMM_TIMEOUT
def dump_debug(self):
sample_time, clock, freq = self.clock_est
return ("clocksync state: mcu_freq=%d last_clock=%d"
" clock_est=(%.3f %d %.3f) min_half_rtt=%.6f min_rtt_time=%.3f"
" time_avg=%.3f(%.3f) clock_avg=%.3f(%.3f)"
" pred_variance=%.3f" % (
self.mcu_freq, self.last_clock, sample_time, clock, freq,
self.min_half_rtt, self.min_rtt_time,
self.time_avg, self.time_variance,
self.clock_avg, self.clock_covariance,
self.prediction_variance))
def stats(self, eventtime):
sample_time, clock, freq = self.clock_est
return "freq=%d" % (freq,)
def calibrate_clock(self, print_time, eventtime):
return (0., self.mcu_freq)
# Clock syncing code for secondary MCUs (whose clocks are sync'ed to a
# primary MCU)
class SecondarySync(ClockSync):
def __init__(self, reactor, main_sync):
ClockSync.__init__(self, reactor)
self.main_sync = main_sync
self.clock_adj = (0., 1.)
def connect(self, serial):
ClockSync.connect(self, serial)
self.clock_adj = (0., self.mcu_freq)
curtime = self.reactor.monotonic()
main_print_time = self.main_sync.estimated_print_time(curtime)
local_print_time = self.estimated_print_time(curtime)
self.clock_adj = (main_print_time - local_print_time, self.mcu_freq)
self.calibrate_clock(0., curtime)
def connect_file(self, serial, pace=False):
ClockSync.connect_file(self, serial, pace)
self.clock_adj = (0., self.mcu_freq)
# clock frequency conversions
def print_time_to_clock(self, print_time):
adjusted_offset, adjusted_freq = self.clock_adj
return int((print_time - adjusted_offset) * adjusted_freq)
def clock_to_print_time(self, clock):
adjusted_offset, adjusted_freq = self.clock_adj
return clock / adjusted_freq + adjusted_offset
def get_adjusted_freq(self):
adjusted_offset, adjusted_freq = self.clock_adj
return adjusted_freq
# misc commands
def dump_debug(self):
adjusted_offset, adjusted_freq = self.clock_adj
return "%s clock_adj=(%.3f %.3f)" % (
ClockSync.dump_debug(self), adjusted_offset, adjusted_freq)
def stats(self, eventtime):
adjusted_offset, adjusted_freq = self.clock_adj
return "%s adj=%d" % (ClockSync.stats(self, eventtime), adjusted_freq)
def calibrate_clock(self, print_time, eventtime):
ser_time, ser_clock, ser_freq = self.main_sync.clock_est
main_mcu_freq = self.main_sync.mcu_freq
main_clock = (eventtime - ser_time) * ser_freq + ser_clock
print_time = max(print_time, main_clock / main_mcu_freq)
main_sync_clock = (print_time + 4.) * main_mcu_freq
sync_time = ser_time + (main_sync_clock - ser_clock) / ser_freq
print_clock = self.print_time_to_clock(print_time)
sync_clock = self.get_clock(sync_time)
adjusted_freq = .25 * (sync_clock - print_clock)
adjusted_offset = print_time - print_clock / adjusted_freq
self.clock_adj = (adjusted_offset, adjusted_freq)
return self.clock_adj
+99 -10
View File
@@ -1,12 +1,31 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# Script to implement a test console with firmware over serial port
#
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys, optparse, os, re, logging
import reactor, serialhdl, pins, util, msgproto, clocksync
import reactor, serialhdl, pins, util, msgproto
help_txt = """
This is a debugging console for the Klipper micro-controller.
In addition to mcu commands, the following artificial commands are
available:
PINS : Load pin name aliases (eg, "PINS arduino")
DELAY : Send a command at a clock time (eg, "DELAY 9999 get_uptime")
FLOOD : Send a command many times (eg, "FLOOD 22 .01 get_uptime")
SUPPRESS : Suppress a response message (eg, "SUPPRESS stats")
SET : Create a local variable (eg, "SET myvar 123.4")
STATS : Report serial statistics
LIST : List available mcu commands, local commands, and local variables
HELP : Show this text
All commands also support evaluation by enclosing an expression in { }.
For example, "reset_step_clock oid=4 clock={clock + freq}". In addition
to user defined variables (via the SET command) the following builtin
variables may be used in expressions:
clock : The current mcu clock time (as estimated by the host)
freq : The mcu clock frequency
"""
re_eval = re.compile(r'\{(?P<eval>[^}]*)\}')
@@ -14,6 +33,7 @@ class KeyboardReader:
def __init__(self, ser, reactor):
self.ser = ser
self.reactor = reactor
self.clocksync = clocksync.ClockSync(self.reactor)
self.fd = sys.stdin.fileno()
util.set_nonblock(self.fd)
self.mcu_freq = 0
@@ -21,41 +41,111 @@ class KeyboardReader:
self.data = ""
reactor.register_fd(self.fd, self.process_kbd)
self.connect_timer = reactor.register_timer(self.connect, reactor.NOW)
self.local_commands = { "PINS": self.set_pin_map, "SET": self.set_var }
self.local_commands = {
"PINS": self.command_PINS, "SET": self.command_SET,
"DELAY": self.command_DELAY, "FLOOD": self.command_FLOOD,
"SUPPRESS": self.command_SUPPRESS, "STATS": self.command_STATS,
"LIST": self.command_LIST, "HELP": self.command_HELP,
}
self.eval_globals = {}
def connect(self, eventtime):
self.output(help_txt)
self.output("="*20 + " attempting to connect " + "="*20)
self.ser.connect()
self.clocksync.connect(self.ser)
self.ser.handle_default = self.handle_default
self.mcu_freq = self.ser.msgparser.get_constant_float('CLOCK_FREQ')
mcu = self.ser.msgparser.get_constant('MCU')
self.pins = pins.get_pin_map(mcu)
self.reactor.unregister_timer(self.connect_timer)
self.output("="*20 + " connected " + "="*20)
return self.reactor.NEVER
def output(self, msg):
sys.stdout.write("%s\n" % (msg,))
sys.stdout.flush()
def handle_default(self, params):
self.output(self.ser.msgparser.format_params(params))
def handle_suppress(self, params):
pass
def update_evals(self, eventtime):
self.eval_globals['freq'] = self.mcu_freq
self.eval_globals['clock'] = self.ser.get_clock(eventtime)
def set_pin_map(self, parts):
self.eval_globals['clock'] = self.clocksync.get_clock(eventtime)
def command_PINS(self, parts):
mcu = self.ser.msgparser.get_constant('MCU')
self.pins = pins.get_pin_map(mcu, parts[1])
def set_var(self, parts):
def command_SET(self, parts):
val = parts[2]
try:
val = float(val)
except ValueError:
pass
self.eval_globals[parts[1]] = val
def command_DELAY(self, parts):
try:
val = int(parts[1])
except ValueError as e:
self.output("Error: %s" % (str(e),))
return
try:
msg = self.ser.msgparser.create_command(' '.join(parts[2:]))
except msgproto.error as e:
self.output("Error: %s" % (str(e),))
return
self.ser.send(msg, minclock=val)
def command_FLOOD(self, parts):
try:
count = int(parts[1])
delay = float(parts[2])
except ValueError as e:
self.output("Error: %s" % (str(e),))
return
try:
msg = self.ser.msgparser.create_command(' '.join(parts[3:]))
except msgproto.error as e:
self.output("Error: %s" % (str(e),))
return
delay_clock = int(delay * self.mcu_freq)
msg_clock = int(self.clocksync.get_clock(self.reactor.monotonic())
+ self.mcu_freq * .200)
for i in range(count):
next_clock = msg_clock + delay_clock
self.ser.send(msg, minclock=msg_clock, reqclock=next_clock)
msg_clock = next_clock
def command_SUPPRESS(self, parts):
oid = None
try:
name = parts[1]
if len(parts) > 2:
oid = int(parts[2])
except ValueError as e:
self.output("Error: %s" % (str(e),))
return
self.ser.register_callback(self.handle_suppress, name, oid)
def command_STATS(self, parts):
curtime = self.reactor.monotonic()
self.output(' '.join([self.ser.stats(curtime),
self.clocksync.stats(curtime)]))
def command_LIST(self, parts):
self.update_evals(self.reactor.monotonic())
mp = self.ser.msgparser
out = "Available mcu commands:"
out += "\n ".join([""] + sorted([
mp.messages_by_id[i].msgformat for i in mp.command_ids]))
out += "\nAvailable artificial commands:"
out += "\n ".join([""] + [n for n in sorted(self.local_commands)])
out += "\nAvailable local variables:"
out += "\n ".join([""] + ["%s: %s" % (k, v)
for k, v in sorted(self.eval_globals.items())])
self.output(out)
def command_HELP(self, parts):
self.output(help_txt)
def translate(self, line, eventtime):
evalparts = re_eval.split(line)
if len(evalparts) > 1:
self.update_evals(eventtime)
try:
for i in range(1, len(evalparts), 2):
e = eval(evalparts[i], self.eval_globals)
e = eval(evalparts[i], dict(self.eval_globals))
if type(e) == type(0.):
e = int(e)
evalparts[i] = str(e)
@@ -66,8 +156,7 @@ class KeyboardReader:
self.output("Eval: %s" % (line,))
if self.pins is not None:
try:
line = pins.update_command(
line, self.mcu_freq, self.pins).strip()
line = pins.update_command(line, self.pins).strip()
except:
self.output("Unable to map pin: %s" % (line,))
return None
@@ -78,7 +167,7 @@ class KeyboardReader:
return None
try:
msg = self.ser.msgparser.create_command(line)
except msgproto.error, e:
except msgproto.error as e:
self.output("Error: %s" % (str(e),))
return None
return msg
+31 -27
View File
@@ -3,28 +3,32 @@
# Copyright (C) 2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import logging, math
import stepper, homing
StepList = (0, 1, 2)
class CoreXYKinematics:
def __init__(self, printer, config):
self.steppers = [stepper.PrinterStepper(
def __init__(self, toolhead, printer, config):
self.steppers = [stepper.PrinterHomingStepper(
printer, config.getsection('stepper_' + n), n)
for n in ['x', 'y', 'z']]
self.steppers[0].mcu_endstop.add_stepper(self.steppers[1].mcu_stepper)
self.steppers[1].mcu_endstop.add_stepper(self.steppers[0].mcu_stepper)
max_velocity, max_accel = toolhead.get_max_velocity()
self.max_z_velocity = config.getfloat(
'max_z_velocity', 9999999.9, above=0.)
'max_z_velocity', max_velocity, above=0., maxval=max_velocity)
self.max_z_accel = config.getfloat(
'max_z_accel', 9999999.9, above=0.)
'max_z_accel', max_accel, above=0., maxval=max_accel)
self.need_motor_enable = True
self.limits = [(1.0, -1.0)] * 3
def set_max_jerk(self, max_xy_halt_velocity, max_velocity, max_accel):
# Setup stepper max halt velocity
max_halt_velocity = toolhead.get_max_axis_halt()
max_xy_halt_velocity = max_halt_velocity * math.sqrt(2.)
self.steppers[0].set_max_jerk(max_xy_halt_velocity, max_accel)
self.steppers[1].set_max_jerk(max_xy_halt_velocity, max_accel)
self.steppers[2].set_max_jerk(0., self.max_z_accel)
self.steppers[2].set_max_jerk(
min(max_halt_velocity, self.max_z_velocity), self.max_z_accel)
def set_position(self, newpos):
pos = (newpos[0] + newpos[1], newpos[0] - newpos[1], newpos[2])
for i in StepList:
@@ -46,40 +50,40 @@ class CoreXYKinematics:
rpos = s.position_endstop + s.homing_retract_dist
r2pos = rpos + s.homing_retract_dist
# Initial homing
homing_speed = s.get_homing_speed()
homepos = [None, None, None, None]
homepos[axis] = s.position_endstop
coord = [None, None, None, None]
coord[axis] = pos
homing_state.home(list(coord), homepos, [s], s.homing_speed)
homing_state.home(list(coord), homepos, [s], homing_speed)
# Retract
coord[axis] = rpos
homing_state.retract(list(coord), s.homing_speed)
homing_state.retract(list(coord), homing_speed)
# Home again
coord[axis] = r2pos
homing_state.home(
list(coord), homepos, [s], s.homing_speed/2.0, second_home=True)
list(coord), homepos, [s], homing_speed/2.0, second_home=True)
if axis == 2:
# Support endstop phase detection on Z axis
coord[axis] = s.position_endstop + s.get_homed_offset()
homing_state.set_homed_position(coord)
def motor_off(self, move_time):
def query_endstops(self, print_time, query_flags):
return homing.query_endstops(print_time, query_flags, self.steppers)
def motor_off(self, print_time):
self.limits = [(1.0, -1.0)] * 3
for stepper in self.steppers:
stepper.motor_enable(move_time, 0)
stepper.motor_enable(print_time, 0)
self.need_motor_enable = True
def _check_motor_enable(self, move_time, move):
def _check_motor_enable(self, print_time, move):
if move.axes_d[0] or move.axes_d[1]:
self.steppers[0].motor_enable(move_time, 1)
self.steppers[1].motor_enable(move_time, 1)
self.steppers[0].motor_enable(print_time, 1)
self.steppers[1].motor_enable(print_time, 1)
if move.axes_d[2]:
self.steppers[2].motor_enable(move_time, 1)
self.steppers[2].motor_enable(print_time, 1)
need_motor_enable = False
for i in StepList:
need_motor_enable |= self.steppers[i].need_motor_enable
self.need_motor_enable = need_motor_enable
def query_endstops(self, print_time):
endstops = [(s, s.query_endstop(print_time)) for s in self.steppers]
return [(s.name, es.query_endstop_wait()) for s, es in endstops]
def _check_endstops(self, move):
end_pos = move.end_pos
for i in StepList:
@@ -104,9 +108,9 @@ class CoreXYKinematics:
z_ratio = move.move_d / abs(move.axes_d[2])
move.limit_speed(
self.max_z_velocity * z_ratio, self.max_z_accel * z_ratio)
def move(self, move_time, move):
def move(self, print_time, move):
if self.need_motor_enable:
self._check_motor_enable(move_time, move)
self._check_motor_enable(print_time, move)
sxp = move.start_pos[0]
syp = move.start_pos[1]
move_start_pos = (sxp + syp, sxp - syp, move.start_pos[2])
@@ -119,7 +123,7 @@ class CoreXYKinematics:
if not axis_d:
continue
mcu_stepper = self.steppers[i].mcu_stepper
mcu_time = mcu_stepper.print_to_mcu_time(move_time)
move_time = print_time
start_pos = move_start_pos[i]
axis_r = abs(axis_d) / move.move_d
accel = move.accel * axis_r
@@ -129,18 +133,18 @@ class CoreXYKinematics:
if move.accel_r:
accel_d = move.accel_r * axis_d
mcu_stepper.step_const(
mcu_time, start_pos, accel_d, move.start_v * axis_r, accel)
move_time, start_pos, accel_d, move.start_v * axis_r, accel)
start_pos += accel_d
mcu_time += move.accel_t
move_time += move.accel_t
# Cruising steps
if move.cruise_r:
cruise_d = move.cruise_r * axis_d
mcu_stepper.step_const(
mcu_time, start_pos, cruise_d, cruise_v, 0.)
move_time, start_pos, cruise_d, cruise_v, 0.)
start_pos += cruise_d
mcu_time += move.cruise_t
move_time += move.cruise_t
# Deceleration steps
if move.decel_r:
decel_d = move.decel_r * axis_d
mcu_stepper.step_const(
mcu_time, start_pos, decel_d, cruise_v, -accel)
move_time, start_pos, decel_d, cruise_v, -accel)
+41 -40
View File
@@ -12,29 +12,36 @@ StepList = (0, 1, 2)
SLOW_RATIO = 3.
class DeltaKinematics:
def __init__(self, printer, config):
self.config = config
self.steppers = [stepper.PrinterStepper(
def __init__(self, toolhead, printer, config):
self.steppers = [stepper.PrinterHomingStepper(
printer, config.getsection('stepper_' + n), n)
for n in ['a', 'b', 'c']]
self.need_motor_enable = self.need_home = True
self.max_velocity = self.max_z_velocity = self.max_accel = 0.
radius = config.getfloat('delta_radius', above=0.)
arm_length = config.getfloat('delta_arm_length', above=radius)
self.arm_length2 = arm_length**2
self.limit_xy2 = -1.
tower_height_at_zeros = math.sqrt(self.arm_length2 - radius**2)
self.max_z = max([s.position_endstop for s in self.steppers])
self.max_z = min([s.position_endstop for s in self.steppers])
self.limit_z = self.max_z - (arm_length - tower_height_at_zeros)
logging.info(
"Delta max build height %.2fmm (radius tapered above %.2fmm)" % (
self.max_z, self.limit_z))
sin = lambda angle: math.sin(math.radians(angle))
cos = lambda angle: math.cos(math.radians(angle))
self.towers = [
(cos(210.)*radius, sin(210.)*radius),
(cos(330.)*radius, sin(330.)*radius),
(cos(90.)*radius, sin(90.)*radius)]
# Setup stepper max halt velocity
self.max_velocity, self.max_accel = toolhead.get_max_velocity()
self.max_z_velocity = config.getfloat(
'max_z_velocity', self.max_velocity,
above=0., maxval=self.max_velocity)
max_halt_velocity = toolhead.get_max_axis_halt()
for s in self.steppers:
s.set_max_jerk(max_halt_velocity, self.max_accel)
# Determine tower locations in cartesian space
angles = [config.getsection('stepper_a').getfloat('angle', 210.),
config.getsection('stepper_b').getfloat('angle', 330.),
config.getsection('stepper_c').getfloat('angle', 90.)]
self.towers = [(math.cos(math.radians(angle)) * radius,
math.sin(math.radians(angle)) * radius)
for angle in angles]
# Find the point where an XY move could result in excessive
# tower movement
half_min_step_dist = min([s.step_dist for s in self.steppers]) * .5
@@ -51,14 +58,6 @@ class DeltaKinematics:
% (math.sqrt(self.max_xy2), math.sqrt(self.slow_xy2),
math.sqrt(self.very_slow_xy2)))
self.set_position([0., 0., 0.])
def set_max_jerk(self, max_xy_halt_velocity, max_velocity, max_accel):
self.max_velocity = max_velocity
max_z_velocity = self.config.getfloat(
'max_z_velocity', max_velocity, above=0.)
self.max_z_velocity = min(max_velocity, max_z_velocity)
self.max_accel = max_accel
for stepper in self.steppers:
stepper.set_max_jerk(max_xy_halt_velocity, max_accel)
def _cartesian_to_actuator(self, coord):
return [math.sqrt(self.arm_length2
- (self.towers[i][0] - coord[0])**2
@@ -106,33 +105,35 @@ class DeltaKinematics:
s = self.steppers[0] # Assume homing speed same for all steppers
self.need_home = False
# Initial homing
homing_speed = s.get_homing_speed()
homepos = [0., 0., self.max_z, None]
coord = list(homepos)
coord[2] = -1.5 * math.sqrt(self.arm_length2-self.max_xy2)
homing_state.home(list(coord), homepos, self.steppers, s.homing_speed)
homing_state.home(list(coord), homepos, self.steppers, homing_speed)
# Retract
coord[2] = homepos[2] - s.homing_retract_dist
homing_state.retract(list(coord), s.homing_speed)
homing_state.retract(list(coord), homing_speed)
# Home again
coord[2] -= s.homing_retract_dist
homing_state.home(list(coord), homepos, self.steppers
, s.homing_speed/2.0, second_home=True)
, homing_speed/2.0, second_home=True)
# Set final homed position
coord = [s.mcu_stepper.get_commanded_position() + s.get_homed_offset()
for s in self.steppers]
homing_state.set_homed_position(self._actuator_to_cartesian(coord))
def motor_off(self, move_time):
spos = self._cartesian_to_actuator(homepos)
spos = [spos[i] + self.steppers[i].position_endstop - self.max_z
+ self.steppers[i].get_homed_offset()
for i in StepList]
homing_state.set_homed_position(self._actuator_to_cartesian(spos))
def query_endstops(self, print_time, query_flags):
return homing.query_endstops(print_time, query_flags, self.steppers)
def motor_off(self, print_time):
self.limit_xy2 = -1.
for stepper in self.steppers:
stepper.motor_enable(move_time, 0)
stepper.motor_enable(print_time, 0)
self.need_motor_enable = self.need_home = True
def _check_motor_enable(self, move_time):
def _check_motor_enable(self, print_time):
for i in StepList:
self.steppers[i].motor_enable(move_time, 1)
self.steppers[i].motor_enable(print_time, 1)
self.need_motor_enable = False
def query_endstops(self, print_time):
endstops = [(s, s.query_endstop(print_time)) for s in self.steppers]
return [(s.name, es.query_endstop_wait()) for s, es in endstops]
def check_move(self, move):
end_pos = move.end_pos
xy2 = end_pos[0]**2 + end_pos[1]**2
@@ -162,9 +163,9 @@ class DeltaKinematics:
move.limit_speed(max_velocity * r, self.max_accel * r)
limit_xy2 = -1.
self.limit_xy2 = min(limit_xy2, self.slow_xy2)
def move(self, move_time, move):
def move(self, print_time, move):
if self.need_motor_enable:
self._check_motor_enable(move_time)
self._check_motor_enable(print_time)
axes_d = move.axes_d
move_d = move.move_d
movexy_r = 1.
@@ -201,24 +202,24 @@ class DeltaKinematics:
# Generate steps
mcu_stepper = self.steppers[i].mcu_stepper
mcu_time = mcu_stepper.print_to_mcu_time(move_time)
move_time = print_time
if accel_d:
mcu_stepper.step_delta(
mcu_time, accel_d, move.start_v, accel,
move_time, accel_d, move.start_v, accel,
vt_startz, vt_startxy_d, vt_arm_d, movez_r)
vt_startz += accel_d * movez_r
vt_startxy_d -= accel_d * movexy_r
mcu_time += move.accel_t
move_time += move.accel_t
if cruise_d:
mcu_stepper.step_delta(
mcu_time, cruise_d, cruise_v, 0.,
move_time, cruise_d, cruise_v, 0.,
vt_startz, vt_startxy_d, vt_arm_d, movez_r)
vt_startz += cruise_d * movez_r
vt_startxy_d -= cruise_d * movexy_r
mcu_time += move.cruise_t
move_time += move.cruise_t
if decel_d:
mcu_stepper.step_delta(
mcu_time, decel_d, cruise_v, -accel,
move_time, decel_d, cruise_v, -accel,
vt_startz, vt_startxy_d, vt_arm_d, movez_r)
+81 -33
View File
@@ -16,14 +16,24 @@ class PrinterExtruder:
self.nozzle_diameter = config.getfloat('nozzle_diameter', above=0.)
filament_diameter = config.getfloat(
'filament_diameter', minval=self.nozzle_diameter)
filament_area = math.pi * (filament_diameter * .5)**2
self.filament_area = math.pi * (filament_diameter * .5)**2
max_cross_section = config.getfloat(
'max_extrude_cross_section', 4. * self.nozzle_diameter**2
, above=0.)
self.max_extrude_ratio = max_cross_section / filament_area
self.max_extrude_ratio = max_cross_section / self.filament_area
toolhead = printer.objects['toolhead']
max_velocity, max_accel = toolhead.get_max_velocity()
self.max_e_velocity = self.config.getfloat(
'max_extrude_only_velocity', max_velocity * self.max_extrude_ratio
, above=0.)
self.max_e_accel = self.config.getfloat(
'max_extrude_only_accel', max_accel * self.max_extrude_ratio
, above=0.)
self.stepper.set_max_jerk(9999999.9, 9999999.9)
self.max_e_dist = config.getfloat(
'max_extrude_only_distance', 50., minval=0.)
self.max_e_velocity = self.max_e_accel = None
self.activate_gcode = config.get('activate_gcode', '')
self.deactivate_gcode = config.get('deactivate_gcode', '')
self.pressure_advance = config.getfloat(
'pressure_advance', 0., minval=0.)
self.pressure_advance_lookahead_time = 0.
@@ -32,37 +42,44 @@ class PrinterExtruder:
'pressure_advance_lookahead_time', 0.010, minval=0.)
self.need_motor_enable = True
self.extrude_pos = 0.
def set_max_jerk(self, max_xy_halt_velocity, max_velocity, max_accel):
self.max_e_velocity = self.config.getfloat(
'max_extrude_only_velocity', max_velocity * self.max_extrude_ratio
, above=0.)
self.max_e_accel = self.config.getfloat(
'max_extrude_only_accel', max_accel * self.max_extrude_ratio
, above=0.)
self.stepper.set_max_jerk(9999999.9, 9999999.9)
def motor_off(self, move_time):
self.stepper.motor_enable(move_time, 0)
def get_heater(self):
return self.heater
def set_active(self, print_time, is_active):
return self.extrude_pos
def get_activate_gcode(self, is_active):
if is_active:
return self.activate_gcode
return self.deactivate_gcode
def motor_off(self, print_time):
self.stepper.motor_enable(print_time, 0)
self.need_motor_enable = True
def check_move(self, move):
move.extrude_r = move.axes_d[3] / move.move_d
move.extrude_max_corner_v = 0.
if not self.heater.can_extrude:
raise homing.EndstopMoveError(
move.end_pos, "Extrude below minimum temp")
raise homing.EndstopError(
"Extrude below minimum temp\n"
"See the 'min_extrude_temp' config option for details")
if not move.is_kinematic_move or move.extrude_r < 0.:
# Extrude only move (or retraction move) - limit accel and velocity
if abs(move.axes_d[3]) > self.max_e_dist:
raise homing.EndstopMoveError(
move.end_pos, "Extrude move too long")
raise homing.EndstopError(
"Extrude only move too long (%.3fmm vs %.3fmm)\n"
"See the 'max_extrude_only_distance' config"
" option for details" % (move.axes_d[3], self.max_e_dist))
inv_extrude_r = 1. / abs(move.extrude_r)
move.limit_speed(self.max_e_velocity * inv_extrude_r
, self.max_e_accel * inv_extrude_r)
elif (move.extrude_r > self.max_extrude_ratio
and move.axes_d[3] > self.nozzle_diameter*self.max_extrude_ratio):
logging.debug("Overextrude: %s vs %s" % (
move.extrude_r, self.max_extrude_ratio))
raise homing.EndstopMoveError(
move.end_pos, "Move exceeds maximum extrusion cross section")
area = move.axes_d[3] * self.filament_area / move.move_d
logging.debug("Overextrude: %s vs %s (area=%.3f dist=%.3f)",
move.extrude_r, self.max_extrude_ratio,
area, move.move_d)
raise homing.EndstopError(
"Move exceeds maximum extrusion (%.3fmm^2 vs %.3fmm^2)\n"
"See the 'max_extrude_cross_section' config option for details"
% (area, self.max_extrude_ratio * self.filament_area))
def calc_junction(self, prev_move, move):
extrude = move.axes_d[3]
prev_extrude = prev_move.axes_d[3]
@@ -114,9 +131,9 @@ class PrinterExtruder:
return i
move.extrude_max_corner_v = max_corner_v
return flush_count
def move(self, move_time, move):
def move(self, print_time, move):
if self.need_motor_enable:
self.stepper.motor_enable(move_time, 1)
self.stepper.motor_enable(print_time, 1)
self.need_motor_enable = False
axis_d = move.axes_d[3]
axis_r = abs(axis_d) / move.move_d
@@ -173,34 +190,35 @@ class PrinterExtruder:
# Prepare for steps
mcu_stepper = self.stepper.mcu_stepper
mcu_time = mcu_stepper.print_to_mcu_time(move_time)
move_time = print_time
# Acceleration steps
if accel_d:
mcu_stepper.step_const(mcu_time, start_pos, accel_d, start_v, accel)
mcu_stepper.step_const(move_time, start_pos, accel_d, start_v, accel)
start_pos += accel_d
mcu_time += accel_t
move_time += accel_t
# Cruising steps
if cruise_d:
mcu_stepper.step_const(mcu_time, start_pos, cruise_d, cruise_v, 0.)
mcu_stepper.step_const(move_time, start_pos, cruise_d, cruise_v, 0.)
start_pos += cruise_d
mcu_time += cruise_t
move_time += cruise_t
# Deceleration steps
if decel_d:
mcu_stepper.step_const(mcu_time, start_pos, decel_d, decel_v, -accel)
mcu_stepper.step_const(
move_time, start_pos, decel_d, decel_v, -accel)
start_pos += decel_d
mcu_time += decel_t
move_time += decel_t
# Retraction steps
if retract_d:
mcu_stepper.step_const(
mcu_time, start_pos, -retract_d, retract_v, accel)
move_time, start_pos, -retract_d, retract_v, accel)
start_pos -= retract_d
self.extrude_pos = start_pos
# Dummy extruder class used when a printer has no extruder at all
class DummyExtruder:
def set_max_jerk(self, max_xy_halt_velocity, max_velocity, max_accel):
pass
def set_active(self, print_time, is_active):
return 0.
def motor_off(self, move_time):
pass
def check_move(self, move):
@@ -210,3 +228,33 @@ class DummyExtruder:
return move.max_cruise_v2
def lookahead(self, moves, flush_count, lazy):
return flush_count
def add_printer_objects(printer, config):
for i in range(99):
section = 'extruder%d' % (i,)
if not config.has_section(section):
if not i and config.has_section('extruder'):
printer.add_object('extruder0', PrinterExtruder(
printer, config.getsection('extruder')))
continue
break
printer.add_object(section, PrinterExtruder(
printer, config.getsection(section)))
def get_printer_extruders(printer):
out = []
for i in range(99):
extruder = printer.objects.get('extruder%d' % (i,))
if extruder is None:
break
out.append(extruder)
return out
def get_printer_heater(printer, name):
if name == 'heater_bed' and name in printer.objects:
return printer.objects[name]
if name == 'extruder':
name = 'extruder0'
if name.startswith('extruder') and name in printer.objects:
return printer.objects[name].get_heater()
raise printer.config_error("Unknown heater '%s'" % (name,))
+44 -13
View File
@@ -1,8 +1,9 @@
# Printer fan support
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import extruder, pins
FAN_MIN_TIME = 0.1
PWM_CYCLE_TIME = 0.010
@@ -11,22 +12,52 @@ class PrinterFan:
def __init__(self, printer, config):
self.last_fan_value = 0.
self.last_fan_time = 0.
self.max_power = config.getfloat('max_power', 1., above=0., maxval=1.)
self.kick_start_time = config.getfloat('kick_start_time', 0.1, minval=0.)
pin = config.get('pin')
hard_pwm = config.getint('hard_pwm', 0)
self.mcu_fan = printer.mcu.create_pwm(pin, PWM_CYCLE_TIME, hard_pwm, 0.)
# External commands
self.mcu_fan = pins.setup_pin(printer, 'pwm', config.get('pin'))
self.mcu_fan.setup_max_duration(0.)
self.mcu_fan.setup_cycle_time(PWM_CYCLE_TIME)
self.mcu_fan.setup_hard_pwm(config.getint('hard_pwm', 0))
def set_speed(self, print_time, value):
value = max(0., min(1., value))
value = max(0., min(self.max_power, value))
if value == self.last_fan_value:
return
mcu_time = self.mcu_fan.print_to_mcu_time(print_time)
mcu_time = max(self.last_fan_time + FAN_MIN_TIME, mcu_time)
if (value and value < 1.
print_time = max(self.last_fan_time + FAN_MIN_TIME, print_time)
if (value and value < self.max_power
and not self.last_fan_value and self.kick_start_time):
# Run fan at full speed for specified kick_start_time
self.mcu_fan.set_pwm(mcu_time, 1.)
mcu_time += self.kick_start_time
self.mcu_fan.set_pwm(mcu_time, value)
self.last_fan_time = mcu_time
self.mcu_fan.set_pwm(print_time, self.max_power)
print_time += self.kick_start_time
self.mcu_fan.set_pwm(print_time, value)
self.last_fan_time = print_time
self.last_fan_value = value
class PrinterHeaterFan:
def __init__(self, printer, config):
self.fan = PrinterFan(printer, config)
self.mcu = printer.objects['mcu']
heater = config.get("heater", "extruder0")
self.heater = extruder.get_printer_heater(printer, heater)
self.heater_temp = config.getfloat("heater_temp", 50.0)
max_power = self.fan.max_power
self.fan_speed = config.getfloat(
"fan_speed", max_power, minval=0., maxval=max_power)
self.fan.mcu_fan.setup_shutdown_value(max_power)
printer.reactor.register_timer(self.callback, printer.reactor.NOW)
def callback(self, eventtime):
current_temp, target_temp = self.heater.get_temp(eventtime)
if not current_temp and not target_temp and not self.fan.last_fan_time:
# Printer still starting
return eventtime + 1.
power = 0.
if target_temp or current_temp > self.heater_temp:
power = self.fan_speed
print_time = self.mcu.estimated_print_time(eventtime) + FAN_MIN_TIME
self.fan.set_speed(print_time, power)
return eventtime + 1.
def add_printer_objects(printer, config):
if config.has_section('fan'):
printer.add_object('fan', PrinterFan(printer, config.getsection('fan')))
for s in config.get_prefix_sections('heater_fan '):
printer.add_object(s.section, PrinterHeaterFan(printer, s))
+176 -96
View File
@@ -4,141 +4,149 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os, re, logging, collections
import homing
import homing, extruder, chipmisc
# Parse out incoming GCode and find and translate head movements
class GCodeParser:
RETRY_TIME = 0.100
def __init__(self, printer, fd, is_fileinput=False):
def __init__(self, printer, fd):
self.printer = printer
self.fd = fd
self.is_fileinput = is_fileinput
# Input handling
self.reactor = printer.reactor
self.is_processing_data = False
self.is_fileinput = not not printer.get_start_args().get("debuginput")
self.fd_handle = None
if not is_fileinput:
if not self.is_fileinput:
self.fd_handle = self.reactor.register_fd(self.fd, self.process_data)
self.input_commands = [""]
self.partial_input = ""
self.bytes_read = 0
self.input_log = collections.deque([], 50)
# Command handling
self.gcode_handlers = self.build_handlers(False)
self.is_printer_ready = False
self.gcode_handlers = {}
self.build_handlers()
self.need_ack = False
self.toolhead = self.heater_nozzle = self.heater_bed = self.fan = None
self.toolhead = self.fan = self.extruder = None
self.heaters = []
self.speed = 25.0
self.absolutecoord = self.absoluteextrude = True
self.base_position = [0.0, 0.0, 0.0, 0.0]
self.last_position = [0.0, 0.0, 0.0, 0.0]
self.homing_add = [0.0, 0.0, 0.0, 0.0]
self.axis2pos = {'X': 0, 'Y': 1, 'Z': 2, 'E': 3}
def build_handlers(self, is_ready):
def build_handlers(self):
handlers = self.all_handlers
if not is_ready:
if not self.is_printer_ready:
handlers = [h for h in handlers
if getattr(self, 'cmd_'+h+'_when_not_ready', False)]
gcode_handlers = dict((h, getattr(self, 'cmd_'+h)) for h in handlers)
for h, f in gcode_handlers.items():
gcode_handlers = { h: getattr(self, 'cmd_'+h) for h in handlers }
for h, f in list(gcode_handlers.items()):
aliases = getattr(self, 'cmd_'+h+'_aliases', [])
gcode_handlers.update(dict([(a, f) for a in aliases]))
return gcode_handlers
gcode_handlers.update({ a: f for a in aliases })
self.gcode_handlers = gcode_handlers
def stats(self, eventtime):
return "gcodein=%d" % (self.bytes_read,)
def set_printer_ready(self, is_ready):
if self.is_printer_ready == is_ready:
return
self.is_printer_ready = is_ready
self.gcode_handlers = self.build_handlers(is_ready)
if not is_ready:
# Printer is shutdown (could be running in a background thread)
return
def connect(self):
self.is_printer_ready = True
self.build_handlers()
# Lookup printer components
self.toolhead = self.printer.objects.get('toolhead')
self.heater_nozzle = None
extruder = self.printer.objects.get('extruder')
if extruder:
self.heater_nozzle = extruder.heater
self.heater_bed = self.printer.objects.get('heater_bed')
extruders = extruder.get_printer_extruders(self.printer)
if extruders:
self.extruder = extruders[0]
self.toolhead.set_extruder(self.extruder)
self.heaters = [ e.get_heater() for e in extruders ]
self.heaters.append(self.printer.objects.get('heater_bed'))
self.fan = self.printer.objects.get('fan')
if self.is_fileinput and self.fd_handle is None:
self.fd_handle = self.reactor.register_fd(self.fd, self.process_data)
def do_shutdown(self):
if not self.is_printer_ready:
return
self.is_printer_ready = False
self.build_handlers()
self.dump_debug()
if self.is_fileinput:
self.printer.request_exit()
def motor_heater_off(self):
if self.toolhead is None:
return
self.toolhead.motor_off()
print_time = self.toolhead.get_last_move_time()
if self.heater_nozzle is not None:
self.heater_nozzle.set_temp(print_time, 0.)
if self.heater_bed is not None:
self.heater_bed.set_temp(print_time, 0.)
for heater in self.heaters:
if heater is not None:
heater.set_temp(print_time, 0.)
if self.fan is not None:
self.fan.set_speed(print_time, 0.)
def dump_debug(self):
logging.info("Dumping gcode input %d blocks" % (
out = []
out.append("Dumping gcode input %d blocks" % (
len(self.input_log),))
for eventtime, data in self.input_log:
logging.info("Read %f: %s" % (eventtime, repr(data)))
out.append("Read %f: %s" % (eventtime, repr(data)))
logging.info("\n".join(out))
# Parse input into commands
args_r = re.compile('([a-zA-Z_]+|[a-zA-Z*])')
def process_commands(self, eventtime):
while len(self.input_commands) > 1:
line = self.input_commands.pop(0)
args_r = re.compile('([A-Z_]+|[A-Z*])')
def process_commands(self, commands, need_ack=True):
prev_need_ack = self.need_ack
for line in commands:
# Ignore comments and leading/trailing spaces
line = origline = line.strip()
cpos = line.find(';')
if cpos >= 0:
line = line[:cpos]
# Break command into parts
parts = self.args_r.split(line)[1:]
params = dict((parts[i].upper(), parts[i+1].strip())
for i in range(0, len(parts), 2))
parts = self.args_r.split(line.upper())[1:]
params = { parts[i]: parts[i+1].strip()
for i in range(0, len(parts), 2) }
params['#original'] = origline
if parts and parts[0].upper() == 'N':
if parts and parts[0] == 'N':
# Skip line number at start of command
del parts[:2]
if not parts:
self.cmd_default(params)
continue
params['#command'] = cmd = parts[0].upper() + parts[1].strip()
params['#command'] = cmd = parts[0] + parts[1].strip()
# Invoke handler for command
self.need_ack = True
self.need_ack = need_ack
handler = self.gcode_handlers.get(cmd, self.cmd_default)
try:
handler(params)
except error, e:
except error as e:
self.respond_error(str(e))
except:
logging.exception("Exception in command handler")
self.toolhead.force_shutdown()
self.respond_error('Internal error on command:"%s"' % (cmd,))
if self.is_fileinput:
self.printer.request_exit('exit_eof')
break
msg = 'Internal error on command:"%s"' % (cmd,)
logging.exception(msg)
self.printer.invoke_shutdown(msg)
self.respond_error(msg)
self.ack()
self.need_ack = prev_need_ack
def process_data(self, eventtime):
data = os.read(self.fd, 4096)
self.input_log.append((eventtime, data))
self.bytes_read += len(data)
lines = data.split('\n')
lines[0] = self.input_commands.pop() + lines[0]
self.input_commands.extend(lines)
lines[0] = self.partial_input + lines[0]
self.partial_input = lines.pop()
if self.is_processing_data:
if len(lines) <= 1:
if not self.is_fileinput and not lines:
return
if not self.is_fileinput and lines[0].strip().upper() == 'M112':
self.cmd_M112({})
self.reactor.unregister_fd(self.fd_handle)
self.fd_handle = None
return
self.is_processing_data = True
self.process_commands(eventtime)
self.is_processing_data = False
if self.fd_handle is None:
if not self.is_fileinput and lines[0].strip().upper() == 'M112':
self.cmd_M112({})
while self.is_processing_data:
eventtime = self.reactor.pause(eventtime + 0.100)
self.fd_handle = self.reactor.register_fd(self.fd, self.process_data)
self.is_processing_data = True
self.process_commands(lines)
if not data and self.is_fileinput:
self.motor_heater_off()
self.printer.request_exit('exit_eof')
if self.toolhead is not None:
self.toolhead.wait_moves()
self.printer.request_exit()
self.is_processing_data = False
# Response handling
def ack(self, msg=None):
if not self.need_ack or self.is_fileinput:
@@ -149,14 +157,15 @@ class GCodeParser:
os.write(self.fd, "ok\n")
self.need_ack = False
def respond(self, msg):
logging.debug(msg)
if self.is_fileinput:
return
os.write(self.fd, msg+"\n")
def respond_info(self, msg):
logging.debug(msg)
lines = [l.strip() for l in msg.strip().split('\n')]
self.respond("// " + "\n// ".join(lines))
def respond_error(self, msg):
logging.warning(msg)
lines = msg.strip().split('\n')
if len(lines) > 1:
self.respond_info("\n".join(lines[:-1]))
@@ -182,18 +191,37 @@ class GCodeParser:
if default is not None:
return default
raise error("Error on '%s': missing %s" % (params['#original'], name))
extended_r = re.compile(
r'^\s*(?:N[0-9]+\s*)?'
r'(?P<cmd>[a-zA-Z_][a-zA-Z_]+)(?:\s+|$)'
r'(?P<args>[^#*;]*?)'
r'\s*(?:[#*;].*)?$')
def get_extended_params(self, params):
m = self.extended_r.match(params['#original'])
if m is None:
# Not an "extended" command
return params
eargs = m.group('args')
try:
eparams = [earg.split('=', 1) for earg in eargs.split()]
eparams = { k.upper(): v for k, v in eparams }
eparams.update({k: params[k] for k in params if k.startswith('#')})
return eparams
except ValueError as e:
raise error("Malformed command '%s'" % (params['#original'],))
# Temperature wrappers
def get_temp(self):
if not self.is_printer_ready:
return "T:0"
# T:XXX /YYY B:XXX /YYY
def get_temp(self, eventtime):
# Tn:XXX /YYY B:XXX /YYY
out = []
if self.heater_nozzle:
cur, target = self.heater_nozzle.get_temp()
out.append("T:%.1f /%.1f" % (cur, target))
if self.heater_bed:
cur, target = self.heater_bed.get_temp()
out.append("B:%.1f /%.1f" % (cur, target))
for i, heater in enumerate(self.heaters):
if heater is not None:
cur, target = heater.get_temp(eventtime)
name = "B"
if i < len(self.heaters) - 1:
name = "T%d" % (i,)
out.append("%s:%.1f /%.1f" % (name, cur, target))
if not out:
return "T:0"
return " ".join(out)
def bg_temp(self, heater):
if self.is_fileinput:
@@ -201,10 +229,19 @@ class GCodeParser:
eventtime = self.reactor.monotonic()
while self.is_printer_ready and heater.check_busy(eventtime):
print_time = self.toolhead.get_last_move_time()
self.respond(self.get_temp())
self.respond(self.get_temp(eventtime))
eventtime = self.reactor.pause(eventtime + 1.)
def set_temp(self, heater, params, wait=False):
def set_temp(self, params, is_bed=False, wait=False):
temp = self.get_float('S', params, 0.)
heater = None
if is_bed:
heater = self.heaters[-1]
elif 'T' in params:
heater_index = self.get_int('T', params)
if heater_index >= 0 and heater_index < len(self.heaters) - 1:
heater = self.heaters[heater_index]
elif self.extruder is not None:
heater = self.extruder.get_heater()
if heater is None:
if temp > 0.:
self.respond_error("Heater not configured")
@@ -212,14 +249,14 @@ class GCodeParser:
print_time = self.toolhead.get_last_move_time()
try:
heater.set_temp(print_time, temp)
except heater.error, e:
except heater.error as e:
self.respond_error(str(e))
return
if wait:
self.bg_temp(heater)
def set_fan_speed(self, speed):
if self.fan is None:
if speed:
if speed and not self.is_fileinput:
self.respond_info("Fan not configured")
return
print_time = self.toolhead.get_last_move_time()
@@ -233,13 +270,38 @@ class GCodeParser:
if not cmd:
logging.debug(params['#original'])
return
self.respond('echo:Unknown command:"%s"' % (cmd,))
if cmd[0] == 'T' and len(cmd) > 1 and cmd[1].isdigit():
# Tn command has to be handled specially
self.cmd_Tn(params)
return
self.respond_info('Unknown command:"%s"' % (cmd,))
def cmd_Tn(self, params):
# Select Tool
index = self.get_int('T', params)
extruders = extruder.get_printer_extruders(self.printer)
if self.extruder is None or index < 0 or index >= len(extruders):
self.respond_error("Extruder %d not configured" % (index,))
return
e = extruders[index]
if self.extruder is e:
return
deactivate_gcode = self.extruder.get_activate_gcode(False)
self.process_commands(deactivate_gcode.split('\n'), need_ack=False)
try:
self.toolhead.set_extruder(e)
except homing.EndstopError as e:
self.respond_error(str(e))
return
self.extruder = e
self.last_position = self.toolhead.get_position()
activate_gcode = self.extruder.get_activate_gcode(True)
self.process_commands(activate_gcode.split('\n'), need_ack=False)
all_handlers = [
'G1', 'G4', 'G20', 'G28', 'G90', 'G91', 'G92',
'M82', 'M83', 'M18', 'M105', 'M104', 'M109', 'M112', 'M114', 'M115',
'M140', 'M190', 'M106', 'M107', 'M206', 'M400',
'IGNORE', 'QUERY_ENDSTOPS', 'PID_TUNE', 'RESTART', 'FIRMWARE_RESTART',
'STATUS', 'HELP']
'IGNORE', 'QUERY_ENDSTOPS', 'PID_TUNE', 'SET_SERVO',
'RESTART', 'FIRMWARE_RESTART', 'ECHO', 'STATUS', 'HELP']
cmd_G1_aliases = ['G0']
def cmd_G1(self, params):
# Move
@@ -259,12 +321,12 @@ class GCodeParser:
if speed <= 0.:
raise ValueError()
self.speed = speed
except ValueError, e:
except ValueError as e:
self.last_position = self.toolhead.get_position()
raise error("Unable to parse move '%s'" % (params['#original'],))
try:
self.toolhead.move(self.last_position, self.speed)
except homing.EndstopError, e:
except homing.EndstopError as e:
self.respond_error(str(e))
self.last_position = self.toolhead.get_position()
def cmd_G4(self, params):
@@ -290,7 +352,7 @@ class GCodeParser:
homing_state.set_no_verify_retract()
try:
self.toolhead.home(homing_state)
except homing.EndstopError, e:
except homing.EndstopError as e:
self.toolhead.motor_off()
self.respond_error(str(e))
return
@@ -325,39 +387,39 @@ class GCodeParser:
cmd_M105_when_not_ready = True
def cmd_M105(self, params):
# Get Extruder Temperature
self.ack(self.get_temp())
self.ack(self.get_temp(self.reactor.monotonic()))
def cmd_M104(self, params):
# Set Extruder Temperature
self.set_temp(self.heater_nozzle, params)
self.set_temp(params)
def cmd_M109(self, params):
# Set Extruder Temperature and Wait
self.set_temp(self.heater_nozzle, params, wait=True)
self.set_temp(params, wait=True)
def cmd_M112(self, params):
# Emergency Stop
self.toolhead.force_shutdown()
self.printer.invoke_shutdown("Shutdown due to M112 command")
cmd_M114_when_not_ready = True
def cmd_M114(self, params):
# Get Current Position
if self.toolhead is None:
self.cmd_default(params)
return
kinpos = self.toolhead.get_position()
self.respond("X:%.3f Y:%.3f Z:%.3f E:%.3f Count X:%.3f Y:%.3f Z:%.3f" % (
raw_pos = self.toolhead.query_endstops("get_mcu_position")
self.respond("X:%.3f Y:%.3f Z:%.3f E:%.3f Count %s" % (
self.last_position[0], self.last_position[1],
self.last_position[2], self.last_position[3],
kinpos[0], kinpos[1], kinpos[2]))
" ".join(["%s:%d" % (n.upper(), p) for n, p in raw_pos])))
cmd_M115_when_not_ready = True
def cmd_M115(self, params):
# Get Firmware Version and Capabilities
kw = {"FIRMWARE_NAME": "Klipper"
, "FIRMWARE_VERSION": self.printer.software_version}
software_version = self.printer.get_start_args().get('software_version')
kw = {"FIRMWARE_NAME": "Klipper", "FIRMWARE_VERSION": software_version}
self.ack(" ".join(["%s:%s" % (k, v) for k, v in kw.items()]))
def cmd_M140(self, params):
# Set Bed Temperature
self.set_temp(self.heater_bed, params)
self.set_temp(params, is_bed=True)
def cmd_M190(self, params):
# Set Bed Temperature and Wait
self.set_temp(self.heater_bed, params, wait=True)
self.set_temp(params, is_bed=True, wait=True)
def cmd_M106(self, params):
# Set fan speed
self.set_fan_speed(self.get_float('S', params, 255.) / 255.)
@@ -387,7 +449,7 @@ class GCodeParser:
return
try:
res = self.toolhead.query_endstops()
except self.printer.mcu.error, e:
except homing.EndstopError as e:
self.respond_error(str(e))
return
self.respond(" ".join(["%s:%s" % (name, ["open", "TRIGGERED"][not not t])
@@ -396,13 +458,28 @@ class GCodeParser:
cmd_PID_TUNE_aliases = ["M303"]
def cmd_PID_TUNE(self, params):
# Run PID tuning
heater = self.get_int('E', params, 0)
heater = {0: self.heater_nozzle, -1: self.heater_bed}[heater]
if heater is None:
heater_index = self.get_int('E', params, 0)
if (heater_index < -1 or heater_index >= len(self.heaters) - 1
or self.heaters[heater_index] is None):
self.respond_error("Heater not configured")
heater = self.heaters[heater_index]
temp = self.get_float('S', params)
heater.start_auto_tune(temp)
self.bg_temp(heater)
cmd_SET_SERVO_help = "Set servo angle"
def cmd_SET_SERVO(self, params):
params = self.get_extended_params(params)
name = params.get('SERVO')
if name is None:
raise error("Error on '%s': missing SERVO" % (params['#original'],))
s = chipmisc.get_printer_servo(self.printer, name)
if s is None:
raise error("Servo not configured")
print_time = self.toolhead.get_last_move_time()
if 'WIDTH' in params:
s.set_pulse_width(print_time, self.get_float('WIDTH', params))
return
s.set_angle(print_time, self.get_float('ANGLE', params))
def prep_restart(self):
if self.is_printer_ready:
self.respond_info("Preparing to restart...")
@@ -419,6 +496,9 @@ class GCodeParser:
def cmd_FIRMWARE_RESTART(self, params):
self.prep_restart()
self.printer.request_exit('firmware_restart')
cmd_ECHO_when_not_ready = True
def cmd_ECHO(self, params):
self.respond_info(params['#original'])
cmd_STATUS_when_not_ready = True
cmd_STATUS_help = "Report the printer status"
def cmd_STATUS(self, params):
+133 -76
View File
@@ -1,28 +1,100 @@
# Printer heater support
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import math, logging, threading
import pins
######################################################################
# Sensors
######################################################################
KELVIN_TO_CELCIUS = -273.15
# Thermistor calibrated with three temp measurements
class Thermistor:
def __init__(self, config, params):
self.pullup = config.getfloat('pullup_resistor', 4700., above=0.)
# Calculate Steinhart-Hart coefficents from temp measurements
inv_t1 = 1. / (params['t1'] - KELVIN_TO_CELCIUS)
inv_t2 = 1. / (params['t2'] - KELVIN_TO_CELCIUS)
inv_t3 = 1. / (params['t3'] - KELVIN_TO_CELCIUS)
ln_r1 = math.log(params['r1'])
ln_r2 = math.log(params['r2'])
ln_r3 = math.log(params['r3'])
ln3_r1, ln3_r2, ln3_r3 = ln_r1**3, ln_r2**3, ln_r3**3
inv_t12, inv_t13 = inv_t1 - inv_t2, inv_t1 - inv_t3
ln_r12, ln_r13 = ln_r1 - ln_r2, ln_r1 - ln_r3
ln3_r12, ln3_r13 = ln3_r1 - ln3_r2, ln3_r1 - ln3_r3
self.c3 = ((inv_t12 - inv_t13 * ln_r12 / ln_r13)
/ (ln3_r12 - ln3_r13 * ln_r12 / ln_r13))
self.c2 = (inv_t12 - self.c3 * ln3_r12) / ln_r12
self.c1 = inv_t1 - self.c2 * ln_r1 - self.c3 * ln3_r1
def calc_temp(self, adc):
r = self.pullup * adc / (1.0 - adc)
ln_r = math.log(r)
inv_t = self.c1 + self.c2 * ln_r + self.c3 * ln_r**3
return 1.0/inv_t + KELVIN_TO_CELCIUS
def calc_adc(self, temp):
inv_t = 1. / (temp - KELVIN_TO_CELCIUS)
if self.c3:
y = (self.c1 - inv_t) / (2. * self.c3)
x = math.sqrt((self.c2 / (3. * self.c3))**3 + y**2)
ln_r = math.pow(x - y, 1./3.) - math.pow(x + y, 1./3.)
else:
ln_r = (inv_t - self.c1) / self.c2
r = math.exp(ln_r)
return r / (self.pullup + r)
# Thermistor calibrated from one temp measurement and its beta
class ThermistorBeta(Thermistor):
def __init__(self, config, params):
self.pullup = config.getfloat('pullup_resistor', 4700., above=0.)
# Calculate Steinhart-Hart coefficents from beta
inv_t1 = 1. / (params['t1'] - KELVIN_TO_CELCIUS)
ln_r1 = math.log(params['r1'])
self.c3 = 0.
self.c2 = 1. / params['beta']
self.c1 = inv_t1 - self.c2 * ln_r1
# Linear style conversion chips calibrated with two temp measurements
class Linear:
def __init__(self, config, params):
adc_voltage = config.getfloat('adc_voltage', 5., above=0.)
slope = (params['t2'] - params['t1']) / (params['v2'] - params['v1'])
self.gain = adc_voltage * slope
self.offset = params['t1'] - params['v1'] * slope
def calc_temp(self, adc):
return adc * self.gain + self.offset
def calc_adc(self, temp):
return (temp - self.offset) / self.gain
# Available sensors
Sensors = {
# Common thermistors and their Steinhart-Hart coefficients
"EPCOS 100K B57560G104F": (
"thermistor",
0.000722136308968056, 0.000216766566488498, 8.92935804531095e-08),
"ATC Semitec 104GT-2": (
"thermistor",
0.000809651054275124, 0.000211636030735685, 7.07420883993973e-08),
# Linear style conversion chips and their gain/offset
"AD595": ("linear", 300.0 / 3.022, 0.),
"EPCOS 100K B57560G104F": {
'class': Thermistor, 't1': 25., 'r1': 100000.,
't2': 150., 'r2': 1641.9, 't3': 250., 'r3': 226.15 },
"ATC Semitec 104GT-2": {
'class': Thermistor, 't1': 20., 'r1': 126800.,
't2': 150., 'r2': 1360., 't3': 300., 'r3': 80.65 },
"NTC 100K beta 3950": {
'class': ThermistorBeta, 't1': 25., 'r1': 100000., 'beta': 3950. },
"AD595": { 'class': Linear, 't1': 25., 'v1': .25, 't2': 300., 'v2': 3.022 },
}
######################################################################
# Heater
######################################################################
SAMPLE_TIME = 0.001
SAMPLE_COUNT = 8
REPORT_TIME = 0.300
PWM_CYCLE_TIME = 0.100
KELVIN_TO_CELCIUS = -273.15
MAX_HEAT_TIME = 5.0
AMBIENT_TEMP = 25.
PID_PARAM_BASE = 255.
@@ -35,20 +107,12 @@ class PrinterHeater:
def __init__(self, printer, config):
self.name = config.section
sensor_params = config.getchoice('sensor_type', Sensors)
self.is_linear_sensor = (sensor_params[0] == 'linear')
if self.is_linear_sensor:
adc_voltage = config.getfloat('adc_voltage', 5., above=0.)
self.sensor_coef = sensor_params[1] * adc_voltage, sensor_params[2]
else:
pullup = config.getfloat('pullup_resistor', 4700., above=0.)
self.sensor_coef = sensor_params[1:] + (pullup,)
self.sensor = sensor_params['class'](config, sensor_params)
self.min_temp = config.getfloat('min_temp', minval=0.)
self.max_temp = config.getfloat('max_temp', above=self.min_temp)
self.min_extrude_temp = config.getfloat(
'min_extrude_temp', 170., minval=self.min_temp, maxval=self.max_temp)
self.max_power = config.getfloat('max_power', 1., above=0., maxval=1.)
self.can_extrude = (self.min_extrude_temp <= 0.
or printer.mcu.is_fileoutput())
self.lock = threading.Lock()
self.last_temp = 0.
self.last_temp_time = 0.
@@ -56,18 +120,20 @@ class PrinterHeater:
algos = {'watermark': ControlBangBang, 'pid': ControlPID}
algo = config.getchoice('control', algos)
heater_pin = config.get('heater_pin')
sensor_pin = config.get('sensor_pin')
if algo is ControlBangBang and self.max_power == 1.:
self.mcu_pwm = printer.mcu.create_digital_out(
heater_pin, MAX_HEAT_TIME)
self.mcu_pwm = pins.setup_pin(printer, 'digital_out', heater_pin)
else:
self.mcu_pwm = printer.mcu.create_pwm(
heater_pin, PWM_CYCLE_TIME, 0, MAX_HEAT_TIME)
self.mcu_adc = printer.mcu.create_adc(sensor_pin)
adc_range = [self.calc_adc(self.min_temp), self.calc_adc(self.max_temp)]
self.mcu_adc.set_minmax(SAMPLE_TIME, SAMPLE_COUNT,
minval=min(adc_range), maxval=max(adc_range))
self.mcu_adc.set_adc_callback(REPORT_TIME, self.adc_callback)
self.mcu_pwm = pins.setup_pin(printer, 'pwm', heater_pin)
self.mcu_pwm.setup_cycle_time(PWM_CYCLE_TIME)
self.mcu_pwm.setup_max_duration(MAX_HEAT_TIME)
self.mcu_adc = pins.setup_pin(printer, 'adc', config.get('sensor_pin'))
adc_range = [self.sensor.calc_adc(self.min_temp),
self.sensor.calc_adc(self.max_temp)]
self.mcu_adc.setup_minmax(SAMPLE_TIME, SAMPLE_COUNT,
minval=min(adc_range), maxval=max(adc_range))
self.mcu_adc.setup_adc_callback(REPORT_TIME, self.adc_callback)
is_fileoutput = self.mcu_adc.get_mcu().is_fileoutput()
self.can_extrude = self.min_extrude_temp <= 0. or is_fileoutput
self.control = algo(self, config)
# pwm caching
self.next_pwm_time = 0.
@@ -82,41 +148,18 @@ class PrinterHeater:
pwm_time = read_time + REPORT_TIME + SAMPLE_TIME*SAMPLE_COUNT
self.next_pwm_time = pwm_time + 0.75 * MAX_HEAT_TIME
self.last_pwm_value = value
logging.debug("%s: pwm=%.3f@%.3f (from %.3f@%.3f [%.3f])" % (
self.name, value, pwm_time,
self.last_temp, self.last_temp_time, self.target_temp))
logging.debug("%s: pwm=%.3f@%.3f (from %.3f@%.3f [%.3f])",
self.name, value, pwm_time,
self.last_temp, self.last_temp_time, self.target_temp)
self.mcu_pwm.set_pwm(pwm_time, value)
# Temperature calculation
def calc_temp(self, adc):
if self.is_linear_sensor:
gain, offset = self.sensor_coef
return adc * gain + offset
c1, c2, c3, pullup = self.sensor_coef
r = pullup * adc / (1.0 - adc)
ln_r = math.log(r)
temp_inv = c1 + c2*ln_r + c3*math.pow(ln_r, 3)
return 1.0/temp_inv + KELVIN_TO_CELCIUS
def calc_adc(self, temp):
if temp is None:
return None
if self.is_linear_sensor:
gain, offset = self.sensor_coef
return (temp - offset) / gain
c1, c2, c3, pullup = self.sensor_coef
temp -= KELVIN_TO_CELCIUS
temp_inv = 1./temp
y = (c1 - temp_inv) / (2*c3)
x = math.sqrt(math.pow(c2 / (3.*c3), 3.) + math.pow(y, 2.))
r = math.exp(math.pow(x-y, 1./3.) - math.pow(x+y, 1./3.))
return r / (pullup + r)
def adc_callback(self, read_time, read_value):
temp = self.calc_temp(read_value)
temp = self.sensor.calc_temp(read_value)
with self.lock:
self.last_temp = temp
self.last_temp_time = read_time
self.can_extrude = (temp >= self.min_extrude_temp)
self.control.adc_callback(read_time, temp)
#logging.debug("temp: %.3f %f = %f" % (read_time, read_value, temp))
#logging.debug("temp: %.3f %f = %f", read_time, read_value, temp)
# External commands
def set_temp(self, print_time, degrees):
if degrees and (degrees < self.min_temp or degrees > self.max_temp):
@@ -124,15 +167,25 @@ class PrinterHeater:
% (degrees, self.min_temp, self.max_temp))
with self.lock:
self.target_temp = degrees
def get_temp(self):
def get_temp(self, eventtime):
print_time = self.mcu_adc.get_mcu().estimated_print_time(eventtime) - 5.
with self.lock:
if self.last_temp_time < print_time:
return 0., self.target_temp
return self.last_temp, self.target_temp
def check_busy(self, eventtime):
with self.lock:
return self.control.check_busy(eventtime)
def start_auto_tune(self, temp):
def start_auto_tune(self, degrees):
if degrees and (degrees < self.min_temp or degrees > self.max_temp):
raise error("Requested temperature (%.1f) out of range (%.1f:%.1f)"
% (degrees, self.min_temp, self.max_temp))
with self.lock:
self.control = ControlAutoTune(self, self.control, temp)
self.control = ControlAutoTune(self, self.control)
self.target_temp = degrees
def finish_auto_tune(self, old_control):
self.control = old_control
self.target_temp = 0
######################################################################
@@ -189,8 +242,8 @@ class ControlPID:
temp_integ = max(0., min(self.temp_integ_max, temp_integ))
# Calculate output
co = self.Kp*temp_err + self.Ki*temp_integ - self.Kd*temp_deriv
#logging.debug("pid: %f@%.3f -> diff=%f deriv=%f err=%f integ=%f co=%d" % (
# temp, read_time, temp_diff, temp_deriv, temp_err, temp_integ, co))
#logging.debug("pid: %f@%.3f -> diff=%f deriv=%f err=%f integ=%f co=%d",
# temp, read_time, temp_diff, temp_deriv, temp_err, temp_integ, co)
bounded_co = max(0., min(self.heater.max_power, co))
self.heater.set_pwm(read_time, bounded_co)
# Store state for next measurement
@@ -211,19 +264,19 @@ class ControlPID:
TUNE_PID_DELTA = 5.0
class ControlAutoTune:
def __init__(self, heater, old_control, target_temp):
def __init__(self, heater, old_control):
self.heater = heater
self.old_control = old_control
self.target_temp = target_temp
self.heating = False
self.peaks = []
self.peak = 0.
self.peak_time = 0.
def adc_callback(self, read_time, temp):
if self.heating and temp >= self.target_temp:
if self.heating and temp >= self.heater.target_temp:
self.heating = False
self.check_peaks()
elif not self.heating and temp <= self.target_temp - TUNE_PID_DELTA:
elif (not self.heating
and temp <= self.heater.target_temp - TUNE_PID_DELTA):
self.heating = True
self.check_peaks()
if self.heating:
@@ -255,13 +308,13 @@ class ControlAutoTune:
Td = 0.125 * Tu
Ki = Kp / Ti
Kd = Kp * Td
logging.info("Autotune: raw=%f/%f Ku=%f Tu=%f Kp=%f Ki=%f Kd=%f" % (
temp_diff, max_power, Ku, Tu,
Kp * PID_PARAM_BASE, Ki * PID_PARAM_BASE, Kd * PID_PARAM_BASE))
logging.info("Autotune: raw=%f/%f Ku=%f Tu=%f Kp=%f Ki=%f Kd=%f",
temp_diff, max_power, Ku, Tu, Kp * PID_PARAM_BASE,
Ki * PID_PARAM_BASE, Kd * PID_PARAM_BASE)
def check_busy(self, eventtime):
if self.heating or len(self.peaks) < 12:
return True
self.heater.control = self.old_control
self.heater.finish_auto_tune(self.old_control)
return False
@@ -270,10 +323,9 @@ class ControlAutoTune:
######################################################################
class ControlBumpTest:
def __init__(self, heater, old_control, target_temp):
def __init__(self, heater, old_control):
self.heater = heater
self.old_control = old_control
self.target_temp = target_temp
self.temp_samples = {}
self.pwm_samples = {}
self.state = 0
@@ -287,14 +339,14 @@ class ControlBumpTest:
if len(self.temp_samples) >= 20:
self.state += 1
elif self.state == 1:
if temp < self.target_temp:
if temp < self.heater.target_temp:
self.set_pwm(read_time, self.heater.max_power)
return
self.set_pwm(read_time, 0.)
self.state += 1
elif self.state == 2:
self.set_pwm(read_time, 0.)
if temp <= (self.target_temp + AMBIENT_TEMP) / 2.:
if temp <= (self.heater.target_temp + AMBIENT_TEMP) / 2.:
self.dump_stats()
self.state += 1
def dump_stats(self):
@@ -306,5 +358,10 @@ class ControlBumpTest:
def check_busy(self, eventtime):
if self.state < 3:
return True
self.heater.control = self.old_control
self.heater.finish_auto_tune(self.old_control)
return False
def add_printer_objects(printer, config):
if config.has_section('heater_bed'):
printer.add_object('heater_bed', PrinterHeater(
printer, config.getsection('heater_bed')))
+31 -9
View File
@@ -1,10 +1,14 @@
# Code for state tracking during homing operations
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
HOMING_DELAY = 0.250
ENDSTOP_SAMPLE_TIME = .000015
ENDSTOP_SAMPLE_COUNT = 4
class Homing:
def __init__(self, toolhead, changed_axes):
self.toolhead = toolhead
@@ -29,21 +33,24 @@ class Homing:
# Alter kinematics class to think printer is at forcepos
self.toolhead.set_position(self._fill_coord(forcepos))
# Start homing and issue move
if not second_home:
self.toolhead.dwell(HOMING_DELAY)
print_time = self.toolhead.get_last_move_time()
endstops = []
for s in steppers:
es = s.enable_endstop_checking(print_time, s.step_dist / speed)
endstops.append((s, es, s.mcu_stepper.get_mcu_position()))
s.mcu_endstop.home_start(print_time, ENDSTOP_SAMPLE_TIME,
ENDSTOP_SAMPLE_COUNT, s.step_dist / speed)
endstops.append((s, s.mcu_stepper.get_mcu_position()))
self.toolhead.move(self._fill_coord(movepos), speed)
move_end_print_time = self.toolhead.get_last_move_time()
self.toolhead.reset_print_time()
for s, es, last_pos in endstops:
es.home_finalize(es.print_to_mcu_time(move_end_print_time))
self.toolhead.reset_print_time(print_time)
for s, last_pos in endstops:
s.mcu_endstop.home_finalize(move_end_print_time)
# Wait for endstops to trigger
for s, es, last_pos in endstops:
for s, last_pos in endstops:
try:
es.home_wait()
except es.error, e:
s.mcu_endstop.home_wait()
except s.mcu_endstop.error as e:
raise EndstopError("Failed to home stepper %s: %s" % (
s.name, str(e)))
post_home_pos = s.mcu_stepper.get_mcu_position()
@@ -53,6 +60,21 @@ class Homing:
def set_homed_position(self, pos):
self.toolhead.set_position(self._fill_coord(pos))
def query_endstops(print_time, query_flags, steppers):
if query_flags == "get_mcu_position":
# Only the commanded position is requested
return [(s.name.upper(), s.mcu_stepper.get_mcu_position())
for s in steppers]
for s in steppers:
s.mcu_endstop.query_endstop(print_time)
out = []
for s in steppers:
try:
out.append((s.name, s.mcu_endstop.query_endstop_wait()))
except s.mcu_endstop.error as e:
raise EndstopError(str(e))
return out
class EndstopError(Exception):
pass
+127 -140
View File
@@ -1,12 +1,12 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# Main code for host side printer firmware
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys, optparse, ConfigParser, logging, time, threading
import gcode, toolhead, util, mcu, fan, heater, extruder, reactor, queuelogger
import msgproto
import util, reactor, queuelogger, msgproto, gcode
import pins, mcu, chipmisc, toolhead, extruder, heater, fan
message_ready = "Printer is ready"
@@ -61,7 +61,7 @@ class ConfigWrapper:
(self.section.lower(), option.lower())] = 1
try:
v = parser(self.section, option)
except self.error, e:
except self.error as e:
raise
except:
raise self.error("Unable to parse option '%s' in section '%s'" % (
@@ -105,6 +105,11 @@ class ConfigWrapper:
return choices[c]
def getsection(self, section):
return ConfigWrapper(self.printer, section)
def has_section(self, section):
return self.printer.fileconfig.has_section(section)
def get_prefix_sections(self, prefix):
return [self.getsection(s) for s in self.printer.fileconfig.sections()
if s.startswith(prefix)]
class ConfigLogger():
def __init__(self, cfg, bglogger):
@@ -118,149 +123,139 @@ class ConfigLogger():
self.lines.append(data.strip())
class Printer:
def __init__(self, conffile, input_fd, startup_state
, is_fileinput=False, version="?", bglogger=None):
self.conffile = conffile
self.startup_state = startup_state
self.software_version = version
config_error = ConfigParser.Error
def __init__(self, input_fd, bglogger, start_args):
self.bglogger = bglogger
self.start_args = start_args
if bglogger is not None:
bglogger.set_rollover_info("config", None)
self.reactor = reactor.Reactor()
self.objects = {}
self.gcode = gcode.GCodeParser(self, input_fd, is_fileinput)
self.stats_timer = self.reactor.register_timer(self.stats)
self.gcode = gcode.GCodeParser(self, input_fd)
self.stats_timer = self.reactor.register_timer(self._stats)
self.connect_timer = self.reactor.register_timer(
self.connect, self.reactor.NOW)
self._connect, self.reactor.NOW)
self.all_config_options = {}
self.need_dump_debug = False
self.state_message = message_startup
self.debugoutput = self.dictionary = None
self.is_shutdown = False
self.async_shutdown_msg = ""
self.run_result = None
self.fileconfig = None
self.mcu = None
def set_fileoutput(self, debugoutput, dictionary):
self.debugoutput = debugoutput
self.dictionary = dictionary
def stats(self, eventtime, force_output=False):
if self.need_dump_debug:
# Call dump_debug here so it is executed in the main thread
self.gcode.dump_debug()
self.need_dump_debug = False
self.mcus = []
def get_start_args(self):
return self.start_args
def _stats(self, eventtime, force_output=False):
toolhead = self.objects.get('toolhead')
if toolhead is None or self.mcu is None:
return
is_active, thstats = toolhead.stats(eventtime)
if toolhead is None:
return eventtime + 1.
is_active = toolhead.check_active(eventtime)
if not is_active and not force_output:
return
return eventtime + 1.
out = []
out.append(self.gcode.stats(eventtime))
out.append(thstats)
out.append(self.mcu.stats(eventtime))
logging.info("Stats %.1f: %s" % (eventtime, ' '.join(out)))
out.append(toolhead.stats(eventtime))
for m in self.mcus:
out.append(m.stats(eventtime))
logging.info("Stats %.1f: %s", eventtime, ' '.join(out))
return eventtime + 1.
def load_config(self):
def add_object(self, name, obj):
self.objects[name] = obj
def _load_config(self):
self.fileconfig = ConfigParser.RawConfigParser()
res = self.fileconfig.read(self.conffile)
config_file = self.start_args['config_file']
res = self.fileconfig.read(config_file)
if not res:
raise ConfigParser.Error("Unable to open config file %s" % (
self.conffile,))
raise self.config_error("Unable to open config file %s" % (
config_file,))
if self.bglogger is not None:
ConfigLogger(self.fileconfig, self.bglogger)
self.mcu = mcu.MCU(self, ConfigWrapper(self, 'mcu'))
if self.debugoutput is not None:
self.mcu.connect_file(self.debugoutput, self.dictionary)
if self.fileconfig.has_section('extruder'):
self.objects['extruder'] = extruder.PrinterExtruder(
self, ConfigWrapper(self, 'extruder'))
if self.fileconfig.has_section('fan'):
self.objects['fan'] = fan.PrinterFan(
self, ConfigWrapper(self, 'fan'))
if self.fileconfig.has_section('heater_bed'):
self.objects['heater_bed'] = heater.PrinterHeater(
self, ConfigWrapper(self, 'heater_bed'))
self.objects['toolhead'] = toolhead.ToolHead(
self, ConfigWrapper(self, 'printer'))
# Create printer components
config = ConfigWrapper(self, 'printer')
for m in [pins, mcu, chipmisc, toolhead, extruder, heater, fan]:
m.add_printer_objects(self, config)
self.mcus = mcu.get_printer_mcus(self)
# Validate that there are no undefined parameters in the config file
valid_sections = dict([(s, 1) for s, o in self.all_config_options])
valid_sections = { s: 1 for s, o in self.all_config_options }
for section in self.fileconfig.sections():
section = section.lower()
if section not in valid_sections:
raise ConfigParser.Error("Unknown config file section '%s'" % (
raise self.config_error("Unknown config file section '%s'" % (
section,))
for option in self.fileconfig.options(section):
option = option.lower()
if (section, option) not in self.all_config_options:
raise ConfigParser.Error(
raise self.config_error(
"Unknown option '%s' in section '%s'" % (
option, section))
def connect(self, eventtime):
def _connect(self, eventtime):
self.reactor.unregister_timer(self.connect_timer)
try:
self.load_config()
if self.debugoutput is None:
self.reactor.update_timer(self.stats_timer, self.reactor.NOW)
self.mcu.connect()
self.gcode.set_printer_ready(True)
self._load_config()
for m in self.mcus:
m.connect()
self.gcode.connect()
self.state_message = message_ready
except ConfigParser.Error, e:
if self.start_args.get('debugoutput') is None:
self.reactor.update_timer(self.stats_timer, self.reactor.NOW)
except (self.config_error, pins.error) as e:
logging.exception("Config error")
self.state_message = "%s%s" % (str(e), message_restart)
self.reactor.update_timer(self.stats_timer, self.reactor.NEVER)
except msgproto.error, e:
except msgproto.error as e:
logging.exception("Protocol error")
self.state_message = "%s%s" % (str(e), message_protocol_error)
self.reactor.update_timer(self.stats_timer, self.reactor.NEVER)
except mcu.error, e:
except mcu.error as e:
logging.exception("MCU error during connect")
self.state_message = "%s%s" % (str(e), message_mcu_connect_error)
self.reactor.update_timer(self.stats_timer, self.reactor.NEVER)
except:
logging.exception("Unhandled exception during connect")
self.state_message = "Internal error during connect.%s" % (
message_restart)
self.reactor.update_timer(self.stats_timer, self.reactor.NEVER)
self.reactor.unregister_timer(self.connect_timer)
message_restart,)
return self.reactor.NEVER
def run(self):
systime = time.time()
monotime = self.reactor.monotonic()
logging.info("Start printer at %s (%.1f %.1f)" % (
time.asctime(time.localtime(systime)), systime, monotime))
try:
self.reactor.run()
except:
logging.exception("Unhandled exception during run")
return
return self.run_result
logging.info("Start printer at %s (%.1f %.1f)",
time.asctime(time.localtime(systime)), systime, monotime)
while 1:
# Enter main reactor loop
try:
self.reactor.run()
except:
logging.exception("Unhandled exception during run")
return "exit"
# Check restart flags
run_result = self.run_result
try:
if run_result == 'shutdown':
self.invoke_shutdown(self.async_shutdown_msg, True)
continue
self._stats(self.reactor.monotonic(), force_output=True)
for m in self.mcus:
if run_result == 'firmware_restart':
m.microcontroller_restart()
m.disconnect()
except:
logging.exception("Unhandled exception during post run")
return run_result
def get_state_message(self):
return self.state_message
def note_shutdown(self, msg):
if self.state_message == message_ready:
self.need_dump_debug = True
self.state_message = "Firmware shutdown: %s%s" % (
msg, message_shutdown)
self.gcode.set_printer_ready(False)
def note_mcu_error(self, msg):
self.state_message = "%s%s" % (msg, message_restart)
self.gcode.set_printer_ready(False)
self.gcode.motor_heater_off()
def disconnect(self):
try:
if self.mcu is not None:
self.stats(self.reactor.monotonic(), force_output=True)
self.mcu.disconnect()
except:
logging.exception("Unhandled exception during disconnect")
def firmware_restart(self):
try:
if self.mcu is not None:
self.stats(self.reactor.monotonic(), force_output=True)
self.mcu.microcontroller_restart()
self.mcu.disconnect()
except:
logging.exception("Unhandled exception during firmware_restart")
def get_startup_state(self):
return self.startup_state
def invoke_shutdown(self, msg, is_mcu_shutdown=False):
if self.is_shutdown:
return
self.is_shutdown = True
if is_mcu_shutdown:
self.state_message = "%s%s" % (msg, message_shutdown)
else:
self.state_message = "%s%s" % (msg, message_restart)
for m in self.mcus:
m.do_shutdown()
self.gcode.do_shutdown()
toolhead = self.objects.get('toolhead')
if toolhead is not None:
toolhead.do_shutdown()
def invoke_async_shutdown(self, msg):
self.async_shutdown_msg = msg
self.request_exit("shutdown")
def request_exit(self, result="exit"):
self.run_result = result
self.reactor.end()
@@ -270,18 +265,19 @@ class Printer:
# Startup
######################################################################
def read_dictionary(filename):
dfile = open(filename, 'rb')
dictionary = dfile.read()
dfile.close()
return dictionary
def arg_dictionary(option, opt_str, value, parser):
key, fname = "dictionary", value
if '=' in value:
mcu_name, fname = value.split('=', 1)
key = "dictionary_" + mcu_name
if parser.values.dictionary is None:
parser.values.dictionary = {}
parser.values.dictionary[key] = fname
def main():
usage = "%prog [options] <config file>"
opts = optparse.OptionParser(usage)
opts.add_option("-o", "--debugoutput", dest="outputfile",
help="write output to file instead of to serial port")
opts.add_option("-i", "--debuginput", dest="inputfile",
opts.add_option("-i", "--debuginput", dest="debuginput",
help="read commands from file instead of from tty port")
opts.add_option("-I", "--input-tty", dest="inputtty", default='/tmp/printer',
help="input tty name (default is /tmp/printer)")
@@ -289,63 +285,54 @@ def main():
help="write log to file instead of stderr")
opts.add_option("-v", action="store_true", dest="verbose",
help="enable debug messages")
opts.add_option("-d", dest="read_dictionary",
opts.add_option("-o", "--debugoutput", dest="debugoutput",
help="write output to file instead of to serial port")
opts.add_option("-d", "--dictionary", dest="dictionary", type="string",
action="callback", callback=arg_dictionary,
help="file to read for mcu protocol dictionary")
options, args = opts.parse_args()
if len(args) != 1:
opts.error("Incorrect number of arguments")
conffile = args[0]
start_args = {'config_file': args[0], 'start_reason': 'startup'}
input_fd = debuginput = debugoutput = bglogger = None
input_fd = bglogger = None
debuglevel = logging.INFO
if options.verbose:
debuglevel = logging.DEBUG
if options.inputfile:
debuginput = open(options.inputfile, 'rb')
if options.debuginput:
start_args['debuginput'] = options.debuginput
debuginput = open(options.debuginput, 'rb')
input_fd = debuginput.fileno()
else:
input_fd = util.create_pty(options.inputtty)
if options.outputfile:
debugoutput = open(options.outputfile, 'wb')
if options.debugoutput:
start_args['debugoutput'] = options.debugoutput
start_args.update(options.dictionary)
if options.logfile:
bglogger = queuelogger.setup_bg_logging(options.logfile, debuglevel)
else:
logging.basicConfig(level=debuglevel)
logging.info("Starting Klippy...")
software_version = util.get_git_version()
start_args['software_version'] = util.get_git_version()
if bglogger is not None:
lines = ["Args: %s" % (sys.argv,),
"Git version: %s" % (repr(software_version),),
"Git version: %s" % (repr(start_args['software_version']),),
"CPU: %s" % (util.get_cpu_info(),),
"Python: %s" % (repr(sys.version),)]
lines = "\n".join(lines)
logging.info(lines)
bglogger.set_rollover_info('versions', lines)
# Start firmware
res = 'startup'
# Start Printer() class
while 1:
is_fileinput = debuginput is not None
printer = Printer(
conffile, input_fd, res, is_fileinput, software_version, bglogger)
if debugoutput:
proto_dict = read_dictionary(options.read_dictionary)
printer.set_fileoutput(debugoutput, proto_dict)
printer = Printer(input_fd, bglogger, start_args)
res = printer.run()
if res == 'restart':
printer.disconnect()
time.sleep(1.)
logging.info("Restarting printer")
continue
elif res == 'firmware_restart':
printer.firmware_restart()
time.sleep(1.)
logging.info("Restarting printer")
continue
elif res == 'exit_eof':
printer.disconnect()
break
if res == 'exit':
break
time.sleep(1.)
logging.info("Restarting printer")
start_args['start_reason'] = res
if bglogger is not None:
bglogger.stop()
+507 -379
View File
File diff suppressed because it is too large. Load diff
+24 -15
View File
@@ -183,9 +183,10 @@ class MessageParser:
error = error
def __init__(self):
self.unknown = UnknownFormat()
self.command_ids = []
self.messages_by_id = {}
self.messages_by_name = {}
self.static_strings = []
self.static_strings = {}
self.config = {}
self.version = ""
self.raw_identify_data = ""
@@ -207,7 +208,7 @@ class MessageParser:
msgcrc = s[msglen-MESSAGE_TRAILER_CRC:msglen-MESSAGE_TRAILER_CRC+2]
crc = crc16_ccitt(s[:msglen-MESSAGE_TRAILER_SIZE])
if crc != msgcrc:
#logging.debug("got crc %s vs %s" % (repr(crc), repr(msgcrc)))
#logging.debug("got crc %s vs %s", repr(crc), repr(msgcrc))
return -1
return msglen
def dump(self, s):
@@ -240,7 +241,7 @@ class MessageParser:
params['#name'] = mid.name
static_string_id = params.get('static_string_id')
if static_string_id is not None:
params['#msg'] = self.static_strings[static_string_id]
params['#msg'] = self.static_strings.get(static_string_id, "?")
return params
def encode(self, seq, cmd):
msglen = MESSAGE_MIN + len(cmd)
@@ -252,7 +253,7 @@ class MessageParser:
def _parse_buffer(self, value):
tval = int(value, 16)
out = []
for i in range(len(value)/2):
for i in range(len(value) // 2):
out.append(tval & 0xff)
tval >>= 8
out.reverse()
@@ -303,17 +304,25 @@ class MessageParser:
self.messages_by_id[msgid] = msg
self.messages_by_name[msg.name] = msg
def process_identify(self, data, decompress=True):
if decompress:
data = zlib.decompress(data)
self.raw_identify_data = data
data = json.loads(data)
messages = data.get('messages')
commands = data.get('commands')
responses = data.get('responses')
self._init_messages(messages, commands+responses)
self.static_strings = data.get('static_strings', [])
self.config.update(data.get('config', {}))
self.version = data.get('version', '')
try:
if decompress:
data = zlib.decompress(data)
self.raw_identify_data = data
data = json.loads(data)
messages = data.get('messages')
commands = data.get('commands')
self.command_ids = commands
responses = data.get('responses')
self._init_messages(messages, commands+responses)
static_strings = data.get('static_strings', {})
self.static_strings = { int(k): v for k, v in static_strings.items() }
self.config.update(data.get('config', {}))
self.version = data.get('version', '')
except error as e:
raise
except Exception as e:
logging.exception("process_identify error")
raise error("Error during identify: %s" % (str(e),))
def get_constant(self, name):
try:
return self.config[name]
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# Script to parse a serial port data dump
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
+123 -18
View File
@@ -1,11 +1,15 @@
# Pin name to pin number definitions
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import re
######################################################################
# Hardware pin names
######################################################################
def port_pins(port_count, bit_count=8):
pins = {}
for port in range(port_count):
@@ -16,11 +20,24 @@ def port_pins(port_count, bit_count=8):
pins['P%c%d' % (portchr, portbit)] = port * bit_count + portbit
return pins
def named_pins(fmt, port_count, bit_count=32):
return { fmt % (port, portbit) : port * bit_count + portbit
for port in range(port_count)
for portbit in range(bit_count) }
def beaglebone_pins():
gpios = named_pins("gpio%d_%d", 4)
gpios.update({"AIN%d" % i: i+4*32 for i in range(8)})
return gpios
MCU_PINS = {
"atmega168": port_pins(4), "atmega644p": port_pins(4),
"at90usb1286": port_pins(5),
"atmega168": port_pins(4), "atmega328": port_pins(4),
"atmega644p": port_pins(4), "atmega1284p": port_pins(4),
"at90usb1286": port_pins(6),
"atmega1280": port_pins(12), "atmega2560": port_pins(12),
"sam3x8e": port_pins(4, 32)
"sam3x8e": port_pins(4, 32),
"pru": beaglebone_pins(),
"linux": {"analog%d" % i: i for i in range(8)}, # XXX
}
@@ -84,28 +101,116 @@ Arduino_from_mcu = {
"sam3x8e": (Arduino_Due, Arduino_Due_analog),
}
def update_map_arduino(pins, mcu):
dpins, apins = Arduino_from_mcu.get(mcu, ([], []))
for i in range(len(dpins)):
pins['ar' + str(i)] = pins[dpins[i]]
for i in range(len(apins)):
pins['analog%d' % (i,)] = pins[apins[i]]
######################################################################
# External commands
# Beaglebone mappings
######################################################################
beagleboneblack_mappings = {
'P8_3': 'gpio1_6', 'P8_4': 'gpio1_7', 'P8_5': 'gpio1_2',
'P8_6': 'gpio1_3', 'P8_7': 'gpio2_2', 'P8_8': 'gpio2_3',
'P8_9': 'gpio2_5', 'P8_10': 'gpio2_4', 'P8_11': 'gpio1_13',
'P8_12': 'gpio1_12', 'P8_13': 'gpio0_23', 'P8_14': 'gpio0_26',
'P8_15': 'gpio1_15', 'P8_16': 'gpio1_14', 'P8_17': 'gpio0_27',
'P8_18': 'gpio2_1', 'P8_19': 'gpio0_22', 'P8_20': 'gpio1_31',
'P8_21': 'gpio1_30', 'P8_22': 'gpio1_5', 'P8_23': 'gpio1_4',
'P8_24': 'gpio1_1', 'P8_25': 'gpio1_0', 'P8_26': 'gpio1_29',
'P8_27': 'gpio2_22', 'P8_28': 'gpio2_24', 'P8_29': 'gpio2_23',
'P8_30': 'gpio2_25', 'P8_31': 'gpio0_10', 'P8_32': 'gpio0_11',
'P8_33': 'gpio0_9', 'P8_34': 'gpio2_17', 'P8_35': 'gpio0_8',
'P8_36': 'gpio2_16', 'P8_37': 'gpio2_14', 'P8_38': 'gpio2_15',
'P8_39': 'gpio2_12', 'P8_40': 'gpio2_13', 'P8_41': 'gpio2_10',
'P8_42': 'gpio2_11', 'P8_43': 'gpio2_8', 'P8_44': 'gpio2_9',
'P8_45': 'gpio2_6', 'P8_46': 'gpio2_7', 'P9_11': 'gpio0_30',
'P9_12': 'gpio1_28', 'P9_13': 'gpio0_31', 'P9_14': 'gpio1_18',
'P9_15': 'gpio1_16', 'P9_16': 'gpio1_19', 'P9_17': 'gpio0_5',
'P9_18': 'gpio0_4', 'P9_19': 'gpio0_13', 'P9_20': 'gpio0_12',
'P9_21': 'gpio0_3', 'P9_22': 'gpio0_2', 'P9_23': 'gpio1_17',
'P9_24': 'gpio0_15', 'P9_25': 'gpio3_21', 'P9_26': 'gpio0_14',
'P9_27': 'gpio3_19', 'P9_28': 'gpio3_17', 'P9_29': 'gpio3_15',
'P9_30': 'gpio3_16', 'P9_31': 'gpio3_14', 'P9_41': 'gpio0_20',
'P9_42': 'gpio3_20', 'P9_43': 'gpio0_7', 'P9_44': 'gpio3_18',
'P9_33': 'AIN4', 'P9_35': 'AIN6', 'P9_36': 'AIN5', 'P9_37': 'AIN2',
'P9_38': 'AIN3', 'P9_39': 'AIN0', 'P9_40': 'AIN1',
}
def update_map_beaglebone(pins, mcu):
for pin, gpio in beagleboneblack_mappings.items():
pins[pin] = pins[gpio]
######################################################################
# Command translation
######################################################################
# Obtains the pin mappings
def get_pin_map(mcu, mapping_name=None):
pins = MCU_PINS.get(mcu, {})
pins = dict(MCU_PINS.get(mcu, {}))
if mapping_name == 'arduino':
dpins, apins = Arduino_from_mcu.get(mcu, [])
for i in range(len(dpins)):
pins['ar' + str(i)] = pins[dpins[i]]
for i in range(len(apins)):
pins['analog%d' % (i,)] = pins[apins[i]]
update_map_arduino(pins, mcu)
elif mapping_name == 'beaglebone':
update_map_beaglebone(pins, mcu)
return pins
# Translate pin names and tick times in a firmware command
# Translate pin names in a firmware command
re_pin = re.compile(r'(?P<prefix>[ _]pin=)(?P<name>[^ ]*)')
re_ticks = re.compile(r'TICKS\((?P<ticks>[^)]*)\)')
def update_command(cmd, mcu_freq, pmap):
def update_command(cmd, pmap):
def pin_fixup(m):
return m.group('prefix') + str(pmap[m.group('name')])
def ticks_fixup(m):
return str(int(mcu_freq * float(m.group('ticks'))))
return re_ticks.sub(ticks_fixup, re_pin.sub(pin_fixup, cmd))
return re_pin.sub(pin_fixup, cmd)
######################################################################
# Pin to chip mapping
######################################################################
class error(Exception):
pass
class PrinterPins:
error = error
def __init__(self):
self.chips = {}
def parse_pin_desc(self, pin_desc, can_invert=False, can_pullup=False):
pullup = invert = 0
if can_pullup and pin_desc.startswith('^'):
pullup = 1
pin_desc = pin_desc[1:].strip()
if can_invert and pin_desc.startswith('!'):
invert = 1
pin_desc = pin_desc[1:].strip()
if ':' not in pin_desc:
chip_name, pin = 'mcu', pin_desc
else:
chip_name, pin = [s.strip() for s in pin_desc.split(':', 1)]
if chip_name not in self.chips:
raise error("Unknown pin chip name '%s'" % (chip_name,))
return {'chip': self.chips[chip_name], 'pin': pin,
'invert': invert, 'pullup': pullup}
def register_chip(self, chip_name, chip):
chip_name = chip_name.strip()
if chip_name in self.chips:
raise error("Duplicate chip name '%s'" % (chip_name,))
self.chips[chip_name] = chip
def add_printer_objects(printer, config):
printer.add_object('pins', PrinterPins())
def get_printer_pins(printer):
return printer.objects['pins']
def setup_pin(printer, pin_type, pin_desc):
ppins = get_printer_pins(printer)
can_invert = pin_type in ['stepper', 'endstop', 'digital_out', 'pwm']
can_pullup = pin_type == 'endstop'
pin_params = ppins.parse_pin_desc(pin_desc, can_invert, can_pullup)
pin_params['type'] = pin_type
return pin_params['chip'].setup_pin(pin_params)
+1 -1
View File
@@ -69,7 +69,7 @@ report_errno(char *where, int rc)
}
// Return a hex character for a given number
#define GETHEX(x) ((x) < 10 ? '0' + (x) : 'e' + (x) - 10)
#define GETHEX(x) ((x) < 10 ? '0' + (x) : 'a' + (x) - 10)
// Translate a binary string into an ASCII string with escape sequences
char *
+39 -102
View File
@@ -1,6 +1,6 @@
# Serial port management for firmware communication
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging, threading
@@ -25,22 +25,15 @@ class SerialReader:
self.serialqueue = None
self.default_cmd_queue = self.alloc_command_queue()
self.stats_buf = self.ffi_main.new('char[4096]')
# MCU time/clock tracking
self.last_ack_time = self.last_ack_rtt_time = 0.
self.last_ack_clock = self.last_ack_rtt_clock = 0
self.est_clock = 0.
# Threading
self.lock = threading.Lock()
self.background_thread = None
# Message handlers
self.status_timer = self.reactor.register_timer(self._status_event)
self.status_cmd = None
handlers = {
'#unknown': self.handle_unknown,
'#output': self.handle_output, 'status': self.handle_status,
'#unknown': self.handle_unknown, '#output': self.handle_output,
'shutdown': self.handle_output, 'is_shutdown': self.handle_output
}
self.handlers = dict(((k, None), v) for k, v in handlers.items())
self.handlers = { (k, None): v for k, v in handlers.items() }
def _bg_thread(self):
response = self.ffi_main.new('struct pull_queue_message *')
while 1:
@@ -51,8 +44,8 @@ class SerialReader:
params = self.msgparser.parse(response.msg[0:count])
params['#sent_time'] = response.sent_time
params['#receive_time'] = response.receive_time
hdl = (params['#name'], params.get('oid'))
with self.lock:
hdl = (params['#name'], params.get('oid'))
hdl = self.handlers.get(hdl, self.handle_default)
try:
hdl(params)
@@ -64,12 +57,17 @@ class SerialReader:
while 1:
starttime = self.reactor.monotonic()
try:
self.ser = serial.Serial(self.serialport, self.baud, timeout=0)
except (OSError, serial.SerialException), e:
logging.warn("Unable to open port: %s" % (e,))
if self.baud:
self.ser = serial.Serial(
self.serialport, self.baud, timeout=0)
else:
self.ser = open(self.serialport, 'rb+')
except (OSError, IOError, serial.SerialException) as e:
logging.warn("Unable to open port: %s", e)
self.reactor.pause(starttime + 5.)
continue
stk500v2_leave(self.ser, self.reactor)
if self.baud:
stk500v2_leave(self.ser, self.reactor)
self.serialqueue = self.ffi_lib.serialqueue_alloc(
self.ser.fileno(), 0)
self.background_thread = threading.Thread(target=self._bg_thread)
@@ -86,44 +84,23 @@ class SerialReader:
msgparser.process_identify(identify_data)
self.msgparser = msgparser
self.register_callback(self.handle_unknown, '#unknown')
logging.info("Loaded %d commands (%s)" % (
len(msgparser.messages_by_id), msgparser.version))
logging.info("MCU config: %s" % (" ".join(
["%s=%s" % (k, v) for k, v in msgparser.config.items()])))
logging.info("Loaded %d commands (%s)",
len(msgparser.messages_by_id), msgparser.version)
logging.info("MCU config: %s", " ".join(
["%s=%s" % (k, v) for k, v in msgparser.config.items()]))
# Setup baud adjust
mcu_baud = float(msgparser.config.get('SERIAL_BAUD', 0.))
if mcu_baud:
baud_adjust = self.BITS_PER_BYTE / mcu_baud
self.ffi_lib.serialqueue_set_baud_adjust(
self.serialqueue, baud_adjust)
# Enable periodic get_status timer
get_status = msgparser.lookup_command('get_status')
self.status_cmd = get_status.encode()
self.reactor.update_timer(self.status_timer, self.reactor.NOW)
# Load initial last_ack_clock/last_ack_time
uptime_msg = msgparser.create_command('get_uptime')
params = self.send_with_response(uptime_msg, 'uptime')
self.last_ack_clock = (params['high'] << 32) | params['clock']
self.last_ack_time = params['#receive_time']
# Make sure est_clock is calculated
starttime = eventtime = self.reactor.monotonic()
while not self.est_clock:
if eventtime > starttime + 5.:
raise error("timeout on est_clock calculation")
eventtime = self.reactor.pause(eventtime + 0.010)
def connect_file(self, debugoutput, dictionary, pace=False):
self.ser = debugoutput
self.msgparser.process_identify(dictionary, decompress=False)
est_clock = 1000000000000.
if pace:
est_clock = float(self.msgparser.config['CLOCK_FREQ'])
self.serialqueue = self.ffi_lib.serialqueue_alloc(self.ser.fileno(), 1)
self.est_clock = est_clock
self.last_ack_time = self.reactor.monotonic()
self.last_ack_clock = 0
def set_clock_est(self, freq, last_time, last_clock):
self.ffi_lib.serialqueue_set_clock_est(
self.serialqueue, self.est_clock, self.last_ack_time
, self.last_ack_clock)
self.serialqueue, freq, last_time, last_clock)
def disconnect(self):
if self.serialqueue is not None:
self.ffi_lib.serialqueue_exit(self.serialqueue)
@@ -137,15 +114,9 @@ class SerialReader:
def stats(self, eventtime):
if self.serialqueue is None:
return ""
sqstats = self.ffi_lib.serialqueue_get_stats(
self.ffi_lib.serialqueue_get_stats(
self.serialqueue, self.stats_buf, len(self.stats_buf))
sqstats = self.ffi_main.string(self.stats_buf)
tstats = " est_clock=%.3f last_ack_time=%.3f last_ack_clock=%d" % (
self.est_clock, self.last_ack_time, self.last_ack_clock)
return sqstats + tstats
def _status_event(self, eventtime):
self.send(self.status_cmd)
return eventtime + 1.0
return self.ffi_main.string(self.stats_buf)
# Serial response callbacks
def register_callback(self, callback, name, oid=None):
with self.lock:
@@ -153,21 +124,6 @@ class SerialReader:
def unregister_callback(self, name, oid=None):
with self.lock:
del self.handlers[name, oid]
# Clock tracking
def get_clock(self, eventtime):
with self.lock:
return int(self.last_ack_clock
+ (eventtime - self.last_ack_time) * self.est_clock)
def translate_clock(self, raw_clock):
with self.lock:
last_ack_clock = self.last_ack_clock
clock_diff = (last_ack_clock - raw_clock) & 0xffffffff
if clock_diff & 0x80000000:
return last_ack_clock + 0x100000000 - clock_diff
return last_ack_clock - clock_diff
def get_last_clock(self):
with self.lock:
return self.last_ack_clock, self.last_ack_time
# Command sending
def send(self, cmd, minclock=0, reqclock=0, cq=None):
if cq is None:
@@ -185,55 +141,36 @@ class SerialReader:
self.ffi_lib.serialqueue_free_commandqueue)
# Dumping debug lists
def dump_debug(self):
out = []
out.append("Dumping serial stats: %s" % (
self.stats(self.reactor.monotonic()),))
sdata = self.ffi_main.new('struct pull_queue_message[1024]')
rdata = self.ffi_main.new('struct pull_queue_message[1024]')
scount = self.ffi_lib.serialqueue_extract_old(
self.serialqueue, 1, sdata, len(sdata))
rcount = self.ffi_lib.serialqueue_extract_old(
self.serialqueue, 0, rdata, len(rdata))
logging.info("Dumping send queue %d messages" % (scount,))
out.append("Dumping send queue %d messages" % (scount,))
for i in range(scount):
msg = sdata[i]
cmds = self.msgparser.dump(msg.msg[0:msg.len])
logging.info("Sent %d %f %f %d: %s" % (
out.append("Sent %d %f %f %d: %s" % (
i, msg.receive_time, msg.sent_time, msg.len, ', '.join(cmds)))
logging.info("Dumping receive queue %d messages" % (rcount,))
out.append("Dumping receive queue %d messages" % (rcount,))
for i in range(rcount):
msg = rdata[i]
cmds = self.msgparser.dump(msg.msg[0:msg.len])
logging.info("Receive: %d %f %f %d: %s" % (
out.append("Receive: %d %f %f %d: %s" % (
i, msg.receive_time, msg.sent_time, msg.len, ', '.join(cmds)))
return '\n'.join(out)
# Default message handlers
def handle_status(self, params):
with self.lock:
# Update last_ack_time / last_ack_clock
ack_clock = (self.last_ack_clock & ~0xffffffff) | params['clock']
if ack_clock < self.last_ack_clock:
ack_clock += 0x100000000
sent_time = params['#sent_time']
self.last_ack_time = receive_time = params['#receive_time']
self.last_ack_clock = ack_clock
# Update est_clock (if applicable)
if receive_time > self.last_ack_rtt_time + 1. and sent_time:
if self.last_ack_rtt_time:
timedelta = receive_time - self.last_ack_rtt_time
clockdelta = ack_clock - self.last_ack_rtt_clock
estclock = clockdelta / timedelta
if estclock > self.est_clock and self.est_clock:
self.est_clock = (self.est_clock * 63. + estclock) / 64.
else:
self.est_clock = estclock
self.last_ack_rtt_time = sent_time
self.last_ack_rtt_clock = ack_clock
self.ffi_lib.serialqueue_set_clock_est(
self.serialqueue, self.est_clock, receive_time, ack_clock)
def handle_unknown(self, params):
logging.warn("Unknown message type %d: %s" % (
params['#msgid'], repr(params['#msg'])))
logging.warn("Unknown message type %d: %s",
params['#msgid'], repr(params['#msg']))
def handle_output(self, params):
logging.info("%s: %s" % (params['#name'], params['#msg']))
logging.info("%s: %s", params['#name'], params['#msg'])
def handle_default(self, params):
logging.warn("got %s" % (params,))
logging.warn("got %s", params)
def __del__(self):
self.disconnect()
@@ -312,8 +249,8 @@ class SerialBootStrap:
self.serial.send(imsg)
return eventtime + self.RETRY_TIME
def handle_unknown(self, params):
logging.debug("Unknown message %d (len %d) while identifying" % (
params['#msgid'], len(params['#msg'])))
logging.debug("Unknown message %d (len %d) while identifying",
params['#msgid'], len(params['#msg']))
# Attempt to place an AVR stk500v2 style programmer into normal mode
def stk500v2_leave(ser, reactor):
@@ -330,16 +267,16 @@ def stk500v2_leave(ser, reactor):
ser.write('\x1b\x01\x00\x01\x0e\x11\x04')
reactor.pause(reactor.monotonic() + 0.050)
res = ser.read(4096)
logging.debug("Got %s from stk500v2" % (repr(res),))
logging.debug("Got %s from stk500v2", repr(res))
ser.baudrate = origbaud
# Attempt an arduino style reset on a serial port
def arduino_reset(serialport, reactor):
# First try opening the port at 1200 baud
ser = serial.Serial(serialport, 1200, timeout=0)
# First try opening the port at a different baud
ser = serial.Serial(serialport, 2400, timeout=0)
ser.read(1)
reactor.pause(reactor.monotonic() + 0.100)
# Then try toggling DTR
# Then toggle DTR
ser.dtr = True
reactor.pause(reactor.monotonic() + 0.100)
ser.dtr = False
+75 -36
View File
@@ -12,6 +12,7 @@
// clock times, prioritizes commands, and handles retransmissions. A
// background thread is launched to do this work and minimize latency.
#include <fcntl.h> // fcntl
#include <math.h> // ceil
#include <poll.h> // poll
#include <pthread.h> // pthread_mutex_lock
@@ -102,14 +103,12 @@ pollreactor_add_timer(struct pollreactor *pr, int pos, void *callback)
pr->timers[pos].waketime = PR_NEVER;
}
#if 0
// Return the last schedule wake-up time for a timer
static double
pollreactor_get_timer(struct pollreactor *pr, int pos)
{
return pr->timers[pos].waketime;
}
#endif
// Set the wake-up time for a given timer
static void
@@ -180,6 +179,22 @@ pollreactor_is_exit(struct pollreactor *pr)
return pr->must_exit;
}
static int
set_non_blocking(int fd)
{
int flags = fcntl(fd, F_GETFL);
if (flags < 0) {
report_errno("fcntl getfl", flags);
return -1;
}
int ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
if (ret < 0) {
report_errno("fcntl setfl", flags);
return -1;
}
return 0;
}
/****************************************************************
* Serial protocol helpers
@@ -344,17 +359,17 @@ struct serialqueue {
int receive_waiting;
// Baud / clock tracking
double baud_adjust, idle_time;
double est_clock, last_ack_time;
uint64_t last_ack_clock;
double est_freq, last_clock_time;
uint64_t last_clock;
double last_receive_sent_time;
// Retransmit support
uint64_t send_seq, receive_seq;
uint64_t retransmit_seq, rtt_sample_seq;
uint64_t ignore_nak_seq, retransmit_seq, rtt_sample_seq;
struct list_head sent_queue;
double srtt, rttvar, rto;
// Pending transmission message queues
struct list_head pending_queues;
int ready_bytes, stalled_bytes;
int ready_bytes, stalled_bytes, need_ack_bytes;
uint64_t need_kick_clock;
// Received messages
struct list_head receive_queue;
@@ -374,7 +389,6 @@ struct serialqueue {
#define MIN_RTO 0.025
#define MAX_RTO 5.000
#define MAX_SERIAL_BUFFER 0.050
#define MIN_REQTIME_DELTA 0.250
#define IDLE_QUERY_TIME 1.0
@@ -427,23 +441,31 @@ static void
update_receive_seq(struct serialqueue *sq, double eventtime, uint64_t rseq)
{
// Remove from sent queue
int ack_count = rseq - sq->receive_seq;
uint64_t sent_seq = sq->receive_seq;
while (!list_empty(&sq->sent_queue) && ack_count--) {
for (;;) {
struct queue_message *sent = list_first_entry(
&sq->sent_queue, struct queue_message, node);
if (rseq == ++sent_seq)
sq->last_receive_sent_time = sent->receive_time;
if (list_empty(&sq->sent_queue)) {
// Got an ack for a message not sent; must be connection init
sq->send_seq = rseq;
sq->last_receive_sent_time = 0.;
break;
}
sq->need_ack_bytes -= sent->len;
list_del(&sent->node);
debug_queue_add(&sq->old_sent, sent);
sent_seq++;
if (rseq == sent_seq) {
// Found sent message corresponding with the received sequence
sq->last_receive_sent_time = sent->receive_time;
break;
}
}
sq->receive_seq = rseq;
if (rseq > sq->send_seq)
sq->send_seq = rseq;
pollreactor_update_timer(&sq->pr, SQPT_COMMAND, PR_NOW);
// Update retransmit info
if (sq->rtt_sample_seq && rseq >= sq->rtt_sample_seq
if (sq->rtt_sample_seq && rseq > sq->rtt_sample_seq
&& sq->last_receive_sent_time) {
// RFC6298 rtt calculations
double delta = eventtime - sq->last_receive_sent_time;
@@ -487,7 +509,7 @@ handle_message(struct serialqueue *sq, double eventtime, int len)
if (rseq != sq->receive_seq)
// New sequence number
update_receive_seq(sq, eventtime, rseq);
else if (len == MESSAGE_MIN && rseq > sq->retransmit_seq
else if (len == MESSAGE_MIN && rseq > sq->ignore_nak_seq
&& !list_empty(&sq->sent_queue))
// Duplicate sequence number in an empty message is a nak
pollreactor_update_timer(&sq->pr, SQPT_RETRANSMIT, PR_NOW);
@@ -495,8 +517,10 @@ handle_message(struct serialqueue *sq, double eventtime, int len)
if (len > MESSAGE_MIN) {
// Add message to receive queue
struct queue_message *qm = message_fill(sq->input_buf, len);
qm->sent_time = sq->last_receive_sent_time;
qm->sent_time = (rseq > sq->retransmit_seq
? sq->last_receive_sent_time : 0.);
qm->receive_time = get_monotonic(); // must be time post read()
qm->receive_time -= sq->baud_adjust * len;
list_add_tail(&qm->node, &sq->receive_queue);
check_wake_receive(sq);
}
@@ -561,12 +585,14 @@ retransmit_event(struct serialqueue *sq, double eventtime)
// Retransmit all pending messages
uint8_t buf[MESSAGE_MAX * MESSAGE_SEQ_MASK + 1];
int buflen = 0;
int buflen = 0, first_buflen = 0;
buf[buflen++] = MESSAGE_SYNC;
struct queue_message *qm;
list_for_each_entry(qm, &sq->sent_queue, node) {
memcpy(&buf[buflen], qm->msg, qm->len);
buflen += qm->len;
if (!first_buflen)
first_buflen = qm->len + 1;
}
ret = write(sq->serial_fd, buf, buflen);
if (ret < 0)
@@ -574,13 +600,23 @@ retransmit_event(struct serialqueue *sq, double eventtime)
sq->bytes_retransmit += buflen;
// Update rto
sq->rto *= 2.0;
if (sq->rto > MAX_RTO)
sq->rto = MAX_RTO;
if (pollreactor_get_timer(&sq->pr, SQPT_RETRANSMIT) == PR_NOW) {
// Retransmit due to nak
sq->ignore_nak_seq = sq->receive_seq;
if (sq->receive_seq < sq->retransmit_seq)
// Second nak for this retransmit - don't allow third
sq->ignore_nak_seq = sq->retransmit_seq;
} else {
// Retransmit due to timeout
sq->rto *= 2.0;
if (sq->rto > MAX_RTO)
sq->rto = MAX_RTO;
sq->ignore_nak_seq = sq->send_seq;
}
sq->retransmit_seq = sq->send_seq;
sq->rtt_sample_seq = 0;
sq->idle_time = eventtime + buflen * sq->baud_adjust;
double waketime = sq->idle_time + sq->rto;
double waketime = eventtime + first_buflen * sq->baud_adjust + sq->rto;
pthread_mutex_unlock(&sq->lock);
return waketime;
@@ -643,9 +679,10 @@ build_and_send_command(struct serialqueue *sq, double eventtime)
if (list_empty(&sq->sent_queue))
pollreactor_update_timer(&sq->pr, SQPT_RETRANSMIT
, sq->idle_time + sq->rto);
sq->send_seq++;
if (!sq->rtt_sample_seq)
sq->rtt_sample_seq = sq->send_seq;
sq->send_seq++;
sq->need_ack_bytes += out->len;
list_add_tail(&out->node, &sq->sent_queue);
}
@@ -653,10 +690,8 @@ build_and_send_command(struct serialqueue *sq, double eventtime)
static double
check_send_command(struct serialqueue *sq, double eventtime)
{
if (eventtime < sq->idle_time - MAX_SERIAL_BUFFER)
// Serial port already busy
return sq->idle_time - MAX_SERIAL_BUFFER;
if (sq->send_seq - sq->receive_seq >= MESSAGE_SEQ_MASK
if ((sq->send_seq - sq->receive_seq >= MESSAGE_SEQ_MASK
|| (sq->need_ack_bytes - 2*MESSAGE_MAX) * sq->baud_adjust > sq->srtt)
&& sq->receive_seq != (uint64_t)-1)
// Need an ack before more messages can be sent
return PR_NEVER;
@@ -664,8 +699,9 @@ check_send_command(struct serialqueue *sq, double eventtime)
// Check for stalled messages now ready
double idletime = eventtime > sq->idle_time ? eventtime : sq->idle_time;
idletime += MESSAGE_MIN * sq->baud_adjust;
double timedelta = idletime - sq->last_ack_time;
uint64_t ack_clock = (uint64_t)(timedelta * sq->est_clock) + sq->last_ack_clock;
double timedelta = idletime - sq->last_clock_time;
uint64_t ack_clock = ((uint64_t)(timedelta * sq->est_freq)
+ sq->last_clock);
uint64_t min_stalled_clock = MAX_CLOCK, min_ready_clock = MAX_CLOCK;
struct command_queue *cq;
list_for_each_entry(cq, &sq->pending_queues, node) {
@@ -695,20 +731,20 @@ check_send_command(struct serialqueue *sq, double eventtime)
// Check for messages to send
if (sq->ready_bytes >= MESSAGE_PAYLOAD_MAX)
return PR_NOW;
if (! sq->est_clock) {
if (! sq->est_freq) {
if (sq->ready_bytes)
return PR_NOW;
sq->need_kick_clock = MAX_CLOCK;
return PR_NEVER;
}
uint64_t reqclock_delta = MIN_REQTIME_DELTA * sq->est_clock;
uint64_t reqclock_delta = MIN_REQTIME_DELTA * sq->est_freq;
if (min_ready_clock <= ack_clock + reqclock_delta)
return PR_NOW;
uint64_t wantclock = min_ready_clock - reqclock_delta;
if (min_stalled_clock < wantclock)
wantclock = min_stalled_clock;
sq->need_kick_clock = wantclock;
return idletime + (wantclock - ack_clock) / sq->est_clock;
return idletime + (wantclock - ack_clock) / sq->est_freq;
}
// Callback timer to send data to the serial port
@@ -759,6 +795,9 @@ serialqueue_alloc(int serial_fd, int write_only)
pollreactor_add_fd(&sq->pr, SQPF_PIPE, sq->pipe_fds[0], kick_event);
pollreactor_add_timer(&sq->pr, SQPT_RETRANSMIT, retransmit_event);
pollreactor_add_timer(&sq->pr, SQPT_COMMAND, command_event);
set_non_blocking(serial_fd);
set_non_blocking(sq->pipe_fds[0]);
set_non_blocking(sq->pipe_fds[1]);
// Retransmit setup
sq->send_seq = 1;
@@ -974,13 +1013,13 @@ serialqueue_set_baud_adjust(struct serialqueue *sq, double baud_adjust)
// Set the estimated clock rate of the mcu on the other end of the
// serial port
void
serialqueue_set_clock_est(struct serialqueue *sq, double est_clock
, double last_ack_time, uint64_t last_ack_clock)
serialqueue_set_clock_est(struct serialqueue *sq, double est_freq
, double last_clock_time, uint64_t last_clock)
{
pthread_mutex_lock(&sq->lock);
sq->est_clock = est_clock;
sq->last_ack_time = last_ack_time;
sq->last_ack_clock = last_ack_clock;
sq->est_freq = est_freq;
sq->last_clock_time = last_clock_time;
sq->last_clock = last_clock;
pthread_mutex_unlock(&sq->lock);
}
+2 -2
View File
@@ -59,8 +59,8 @@ void serialqueue_encode_and_send(struct serialqueue *sq, struct command_queue *c
, uint64_t min_clock, uint64_t req_clock);
void serialqueue_pull(struct serialqueue *sq, struct pull_queue_message *pqm);
void serialqueue_set_baud_adjust(struct serialqueue *sq, double baud_adjust);
void serialqueue_set_clock_est(struct serialqueue *sq, double est_clock
, double last_ack_time, uint64_t last_ack_clock);
void serialqueue_set_clock_est(struct serialqueue *sq, double est_freq
, double last_clock_time, uint64_t last_clock);
void serialqueue_get_stats(struct serialqueue *sq, char *buf, int len);
int serialqueue_extract_old(struct serialqueue *sq, int sentq
, struct pull_queue_message *q, int max);
+202 -152
View File
@@ -28,9 +28,10 @@
struct stepcompress {
// Buffer management
uint64_t *queue, *queue_end, *queue_pos, *queue_next;
uint32_t *queue, *queue_end, *queue_pos, *queue_next;
// Internal tracking
uint32_t max_error;
double mcu_time_offset, mcu_freq;
// Message generation
uint64_t last_step_clock, homing_clock;
struct list_head msg_queue;
@@ -39,42 +40,6 @@ struct stepcompress {
};
/****************************************************************
* Queue management
****************************************************************/
// Shuffle the internal queue to avoid having to allocate more ram
static void
clean_queue(struct stepcompress *sc)
{
int in_use = sc->queue_next - sc->queue_pos;
memmove(sc->queue, sc->queue_pos, in_use * sizeof(*sc->queue));
sc->queue_pos = sc->queue;
sc->queue_next = sc->queue + in_use;
}
// Expand the internal queue of step times
static void
expand_queue(struct stepcompress *sc, int count)
{
int alloc = sc->queue_end - sc->queue;
if (count + sc->queue_next - sc->queue_pos <= alloc) {
clean_queue(sc);
return;
}
int pos = sc->queue_pos - sc->queue;
int next = sc->queue_next - sc->queue;
if (!alloc)
alloc = QUEUE_START_SIZE;
while (next + count > alloc)
alloc *= 2;
sc->queue = realloc(sc->queue, alloc * sizeof(*sc->queue));
sc->queue_end = sc->queue + alloc;
sc->queue_pos = sc->queue + pos;
sc->queue_next = sc->queue + next;
}
/****************************************************************
* Step compression
****************************************************************/
@@ -100,10 +65,10 @@ struct points {
// Given a requested step time, return the minimum and maximum
// acceptable times
static inline struct points
minmax_point(struct stepcompress *sc, uint64_t *pos)
minmax_point(struct stepcompress *sc, uint32_t *pos)
{
uint32_t prevpoint = pos > sc->queue_pos ? *(pos-1) - sc->last_step_clock : 0;
uint32_t point = *pos - sc->last_step_clock;
uint32_t lsc = sc->last_step_clock, point = *pos - lsc;
uint32_t prevpoint = pos > sc->queue_pos ? *(pos-1) - lsc : 0;
uint32_t max_error = (point - prevpoint) / 2;
if (max_error > sc->max_error)
max_error = sc->max_error;
@@ -126,6 +91,9 @@ struct step_move {
static struct step_move
compress_bisect_add(struct stepcompress *sc)
{
uint32_t *qlast = sc->queue_next;
if (qlast > sc->queue_pos + 65535)
qlast = sc->queue_pos + 65535;
struct points point = minmax_point(sc, sc->queue_pos);
int32_t outer_mininterval = point.minp, outer_maxinterval = point.maxp;
int32_t add = 0, minadd = -0x8000, maxadd = 0x7fff;
@@ -140,10 +108,7 @@ compress_bisect_add(struct stepcompress *sc)
int32_t nextcount = 1;
for (;;) {
nextcount++;
if (nextcount > bestcount
&& (&sc->queue_pos[nextcount-1] >= sc->queue_next
|| sc->queue_pos[nextcount-1] >= sc->last_step_clock+(3<<28)
|| nextcount > 65535)) {
if (&sc->queue_pos[nextcount-1] >= qlast) {
int32_t count = nextcount - 1;
return (struct step_move){ interval, count, add };
}
@@ -230,18 +195,7 @@ check_line(struct stepcompress *sc, struct step_move move)
{
if (!CHECK_LINES)
return 0;
if (move.count == 1) {
if (move.interval != (uint32_t)(*sc->queue_pos - sc->last_step_clock)
|| *sc->queue_pos < sc->last_step_clock) {
errorf("stepcompress o=%d i=%d c=%d a=%d:"
" Count 1 point out of range (%lld)"
, sc->oid, move.interval, move.count, move.add
, (long long)(*sc->queue_pos - sc->last_step_clock));
return ERROR_RET;
}
return 0;
}
if (!move.count || (!move.interval && !move.add)
if (!move.count || (!move.interval && !move.add && move.count > 1)
|| move.interval >= 0x80000000) {
errorf("stepcompress o=%d i=%d c=%d a=%d: Invalid sequence"
, sc->oid, move.interval, move.count, move.add);
@@ -310,7 +264,7 @@ stepcompress_flush(struct stepcompress *sc, uint64_t move_clock)
{
if (sc->queue_pos >= sc->queue_next)
return 0;
while (move_clock > sc->last_step_clock) {
while (sc->last_step_clock < move_clock) {
struct step_move move = compress_bisect_add(sc);
int ret = check_line(sc, move);
if (ret)
@@ -321,14 +275,9 @@ stepcompress_flush(struct stepcompress *sc, uint64_t move_clock)
};
struct queue_message *qm = message_alloc_and_encode(msg, 5);
qm->min_clock = qm->req_clock = sc->last_step_clock;
if (move.count == 1 && sc->last_step_clock + (1<<27) < *sc->queue_pos) {
// Be careful with 32bit overflow
sc->last_step_clock = qm->req_clock = *sc->queue_pos;
} else {
int32_t addfactor = move.count*(move.count-1)/2;
uint32_t ticks = move.add*addfactor + move.interval*move.count;
sc->last_step_clock += ticks;
}
int32_t addfactor = move.count*(move.count-1)/2;
uint32_t ticks = move.add*addfactor + move.interval*move.count;
sc->last_step_clock += ticks;
if (sc->homing_clock)
// When homing, all steps should be sent prior to homing_clock
qm->min_clock = qm->req_clock = sc->homing_clock;
@@ -343,6 +292,23 @@ stepcompress_flush(struct stepcompress *sc, uint64_t move_clock)
return 0;
}
// Generate a queue_step for a step far in the future from the last step
static int
stepcompress_flush_far(struct stepcompress *sc, uint64_t abs_step_clock)
{
uint32_t msg[5] = {
sc->queue_step_msgid, sc->oid, abs_step_clock - sc->last_step_clock, 1, 0
};
struct queue_message *qm = message_alloc_and_encode(msg, 5);
qm->min_clock = sc->last_step_clock;
sc->last_step_clock = qm->req_clock = abs_step_clock;
if (sc->homing_clock)
// When homing, all steps should be sent prior to homing_clock
qm->min_clock = qm->req_clock = sc->homing_clock;
list_add_tail(&qm->node, &sc->msg_queue);
return 0;
}
// Send the set_next_step_dir command
static int
set_next_step_dir(struct stepcompress *sc, int sdir)
@@ -362,35 +328,6 @@ set_next_step_dir(struct stepcompress *sc, int sdir)
return 0;
}
// Check if the internal queue needs to be expanded, and expand if so
static int
_check_push(struct stepcompress *sc)
{
if (sc->queue_next - sc->queue_pos > 65535 + 2000) {
// No point in keeping more than 64K steps in memory
int ret = stepcompress_flush(sc, *(sc->queue_next - 65535));
if (ret)
return ret;
}
expand_queue(sc, 1);
return 0;
}
static inline int
check_push(struct stepcompress *sc, uint64_t **pqnext, uint64_t **pqend
, uint64_t c)
{
if (unlikely(*pqnext >= *pqend)) {
sc->queue_next = *pqnext;
int ret = _check_push(sc);
if (ret)
return ret;
*pqnext = sc->queue_next;
*pqend = sc->queue_end;
}
*(*pqnext)++ = c;
return 0;
}
// Reset the internal state of the stepcompress object
int
stepcompress_reset(struct stepcompress *sc, uint64_t last_step_clock)
@@ -428,11 +365,124 @@ stepcompress_queue_msg(struct stepcompress *sc, uint32_t *data, int len)
return 0;
}
// Set the conversion rate of 'print_time' to mcu clock
static void
stepcompress_set_time(struct stepcompress *sc
, double time_offset, double mcu_freq)
{
sc->mcu_time_offset = time_offset;
sc->mcu_freq = mcu_freq;
}
/****************************************************************
* Queue management
****************************************************************/
struct queue_append {
struct stepcompress *sc;
uint32_t *qnext, *qend, last_step_clock_32;
double clock_offset;
};
// Maximium clock delta between messages in the queue
#define CLOCK_DIFF_MAX (3<<28)
// Create a cursor for inserting clock times into the queue
static inline struct queue_append
queue_append_start(struct stepcompress *sc, double print_time, double adjust)
{
double print_clock = (print_time - sc->mcu_time_offset) * sc->mcu_freq;
return (struct queue_append) {
.sc = sc, .qnext = sc->queue_next, .qend = sc->queue_end,
.last_step_clock_32 = sc->last_step_clock,
.clock_offset = (print_clock - (double)sc->last_step_clock) + adjust };
}
// Finalize a cursor created with queue_append_start()
static inline void
queue_append_finish(struct queue_append qa)
{
qa.sc->queue_next = qa.qnext;
}
// Slow path for queue_append()
static int
queue_append_slow(struct stepcompress *sc, double rel_sc)
{
uint64_t abs_step_clock = (uint64_t)rel_sc + sc->last_step_clock;
if (abs_step_clock >= sc->last_step_clock + CLOCK_DIFF_MAX) {
// Avoid integer overflow on steps far in the future
int ret = stepcompress_flush(sc, abs_step_clock - CLOCK_DIFF_MAX + 1);
if (ret)
return ret;
if (abs_step_clock >= sc->last_step_clock + CLOCK_DIFF_MAX)
return stepcompress_flush_far(sc, abs_step_clock);
}
if (sc->queue_next - sc->queue_pos > 65535 + 2000) {
// No point in keeping more than 64K steps in memory
int ret = stepcompress_flush(sc, *(sc->queue_next - 65535));
if (ret)
return ret;
}
int in_use = sc->queue_next - sc->queue_pos;
if (sc->queue_pos > sc->queue) {
// Shuffle the internal queue to avoid having to allocate more ram
memmove(sc->queue, sc->queue_pos, in_use * sizeof(*sc->queue));
} else {
// Expand the internal queue of step times
int alloc = sc->queue_end - sc->queue;
if (!alloc)
alloc = QUEUE_START_SIZE;
while (in_use >= alloc)
alloc *= 2;
sc->queue = realloc(sc->queue, alloc * sizeof(*sc->queue));
sc->queue_end = sc->queue + alloc;
}
sc->queue_pos = sc->queue;
sc->queue_next = sc->queue + in_use;
*sc->queue_next++ = abs_step_clock;
return 0;
}
// Add a clock time to the queue (flushing the queue if needed)
static inline int
queue_append(struct queue_append *qa, double step_clock)
{
double rel_sc = step_clock + qa->clock_offset;
if (likely(!(qa->qnext >= qa->qend || rel_sc >= (double)CLOCK_DIFF_MAX))) {
*qa->qnext++ = qa->last_step_clock_32 + (uint32_t)rel_sc;
return 0;
}
// Call queue_append_slow() to handle queue expansion and integer overflow
struct stepcompress *sc = qa->sc;
uint64_t old_last_step_clock = sc->last_step_clock;
sc->queue_next = qa->qnext;
int ret = queue_append_slow(sc, rel_sc);
if (ret)
return ret;
qa->qnext = sc->queue_next;
qa->qend = sc->queue_end;
qa->last_step_clock_32 = sc->last_step_clock;
qa->clock_offset -= sc->last_step_clock - old_last_step_clock;
return 0;
}
/****************************************************************
* Motion to step conversions
****************************************************************/
// Common suffixes: _sd is step distance (a unit length the same
// distance the stepper moves on each step), _sv is step velocity (in
// units of step distance per time), _sd2 is step distance squared, _r
// is ratio (scalar usually between 0.0 and 1.0). Times are in
// seconds and acceleration is in units of step distance per second
// squared.
// Wrapper around sqrt() to handle small negative numbers
static double
_safe_sqrt(double v)
@@ -448,38 +498,29 @@ static inline double safe_sqrt(double v) {
}
// Schedule a step event at the specified step_clock time
int
stepcompress_push(struct stepcompress *sc, double step_clock, int32_t sdir)
int32_t
stepcompress_push(struct stepcompress *sc, double print_time, int32_t sdir)
{
int ret = set_next_step_dir(sc, !!sdir);
if (ret)
return ret;
step_clock += 0.5;
uint64_t *qnext = sc->queue_next, *qend = sc->queue_end;
ret = check_push(sc, &qnext, &qend, step_clock);
struct queue_append qa = queue_append_start(sc, print_time, 0.5);
ret = queue_append(&qa, 0.);
if (ret)
return ret;
sc->queue_next = qnext;
return 0;
queue_append_finish(qa);
return sdir ? 1 : -1;
}
// Common suffixes: _sd is step distance (a unit length the same
// distance the stepper moves on each step), _sv is step velocity (in
// units of step distance per clock tick), _sd2 is step distance
// squared, _r is ratio (scalar usually between 0.0 and 1.0). Times
// are represented as clock ticks (a unit of time determined by a
// micro-controller tick) and acceleration is in units of step
// distance per clock ticks squared.
// Schedule 'steps' number of steps at constant acceleration. If
// acceleration is zero (ie, constant velocity) it uses the formula:
// step_clock = clock_offset + step_num/start_sv
// step_time = print_time + step_num/start_sv
// Otherwise it uses the formula:
// step_clock = (clock_offset + sqrt(2*step_num/accel + (start_sv/accel)**2)
// - start_sv/accel)
// step_time = (print_time + sqrt(2*step_num/accel + (start_sv/accel)**2)
// - start_sv/accel)
int32_t
stepcompress_push_const(
struct stepcompress *sc, double clock_offset
struct stepcompress *sc, double print_time
, double step_offset, double steps, double start_sv, double accel)
{
// Calculate number of steps to take
@@ -493,7 +534,7 @@ stepcompress_push_const(
if (count <= 0 || count > 10000000) {
if (count && steps) {
errorf("push_const invalid count %d %f %f %f %f %f"
, sc->oid, clock_offset, step_offset, steps
, sc->oid, print_time, step_offset, steps
, start_sv, accel);
return ERROR_RET;
}
@@ -505,35 +546,35 @@ stepcompress_push_const(
int res = sdir ? count : -count;
// Calculate each step time
clock_offset += 0.5;
double pos = step_offset + .5;
uint64_t *qnext = sc->queue_next, *qend = sc->queue_end;
if (!accel) {
// Move at constant velocity (zero acceleration)
double inv_cruise_sv = 1. / start_sv;
struct queue_append qa = queue_append_start(sc, print_time, .5);
double inv_cruise_sv = sc->mcu_freq / start_sv;
double pos = (step_offset + .5) * inv_cruise_sv;
while (count--) {
uint64_t c = clock_offset + pos*inv_cruise_sv;
int ret = check_push(sc, &qnext, &qend, c);
ret = queue_append(&qa, pos);
if (ret)
return ret;
pos += 1.0;
pos += inv_cruise_sv;
}
queue_append_finish(qa);
} else {
// Move with constant acceleration
double inv_accel = 1. / accel;
clock_offset -= start_sv * inv_accel;
pos += .5 * start_sv*start_sv * inv_accel;
double accel_multiplier = 2. * inv_accel;
double accel_time = start_sv * inv_accel * sc->mcu_freq;
struct queue_append qa = queue_append_start(
sc, print_time, 0.5 - accel_time);
double accel_multiplier = 2. * inv_accel * sc->mcu_freq * sc->mcu_freq;
double pos = (step_offset + .5)*accel_multiplier + accel_time*accel_time;
while (count--) {
double v = safe_sqrt(pos * accel_multiplier);
uint64_t c = clock_offset + (accel_multiplier >= 0. ? v : -v);
int ret = check_push(sc, &qnext, &qend, c);
double v = safe_sqrt(pos);
int ret = queue_append(&qa, accel_multiplier >= 0. ? v : -v);
if (ret)
return ret;
pos += 1.0;
pos += accel_multiplier;
}
queue_append_finish(qa);
}
sc->queue_next = qnext;
return res;
}
@@ -541,7 +582,7 @@ stepcompress_push_const(
static int32_t
_stepcompress_push_delta(
struct stepcompress *sc, int sdir
, double clock_offset, double move_sd, double start_sv, double accel
, double print_time, double move_sd, double start_sv, double accel
, double height, double startxy_sd, double arm_sd, double movez_r)
{
// Calculate number of steps to take
@@ -553,7 +594,7 @@ _stepcompress_push_delta(
if (count <= 0 || count > 10000000) {
if (count) {
errorf("push_delta invalid count %d %d %f %f %f %f %f %f %f %f"
, sc->oid, count, clock_offset, move_sd, start_sv, accel
, sc->oid, count, print_time, move_sd, start_sv, accel
, height, startxy_sd, arm_sd, movez_r);
return ERROR_RET;
}
@@ -565,32 +606,30 @@ _stepcompress_push_delta(
int res = sdir ? count : -count;
// Calculate each step time
clock_offset += 0.5;
height += (sdir ? .5 : -.5);
uint64_t *qnext = sc->queue_next, *qend = sc->queue_end;
if (!accel) {
// Move at constant velocity (zero acceleration)
double inv_cruise_sv = 1. / start_sv;
struct queue_append qa = queue_append_start(sc, print_time, .5);
double inv_cruise_sv = sc->mcu_freq / start_sv;
if (!movez_r) {
// Optimized case for common XY only moves (no Z movement)
while (count--) {
double v = safe_sqrt(arm_sd2 - height*height);
double pos = startxy_sd + (sdir ? -v : v);
uint64_t c = clock_offset + pos * inv_cruise_sv;
int ret = check_push(sc, &qnext, &qend, c);
int ret = queue_append(&qa, pos * inv_cruise_sv);
if (ret)
return ret;
height += (sdir ? 1. : -1.);
}
} else if (!movexy_r) {
// Optimized case for Z only moves
double pos = (sdir ? height-end_height : end_height-height);
double pos = ((sdir ? height-end_height : end_height-height)
* inv_cruise_sv);
while (count--) {
uint64_t c = clock_offset + pos * inv_cruise_sv;
int ret = check_push(sc, &qnext, &qend, c);
int ret = queue_append(&qa, pos);
if (ret)
return ret;
pos += 1.;
pos += inv_cruise_sv;
}
} else {
// General case (handles XY+Z moves)
@@ -599,39 +638,39 @@ _stepcompress_push_delta(
double relheight = movexy_r*height - zoffset;
double v = safe_sqrt(arm_sd2 - relheight*relheight);
double pos = start_pos + movez_r*height + (sdir ? -v : v);
uint64_t c = clock_offset + pos * inv_cruise_sv;
int ret = check_push(sc, &qnext, &qend, c);
int ret = queue_append(&qa, pos * inv_cruise_sv);
if (ret)
return ret;
height += (sdir ? 1. : -1.);
}
}
queue_append_finish(qa);
} else {
// Move with constant acceleration
double start_pos = movexy_r*startxy_sd, zoffset = movez_r*startxy_sd;
double inv_accel = 1. / accel;
clock_offset -= start_sv * inv_accel;
start_pos += 0.5 * start_sv*start_sv * inv_accel;
double accel_multiplier = 2. * inv_accel;
struct queue_append qa = queue_append_start(
sc, print_time, 0.5 - start_sv * inv_accel * sc->mcu_freq);
double accel_multiplier = 2. * inv_accel * sc->mcu_freq * sc->mcu_freq;
while (count--) {
double relheight = movexy_r*height - zoffset;
double v = safe_sqrt(arm_sd2 - relheight*relheight);
double pos = start_pos + movez_r*height + (sdir ? -v : v);
v = safe_sqrt(pos * accel_multiplier);
uint64_t c = clock_offset + (accel_multiplier >= 0. ? v : -v);
int ret = check_push(sc, &qnext, &qend, c);
int ret = queue_append(&qa, accel_multiplier >= 0. ? v : -v);
if (ret)
return ret;
height += (sdir ? 1. : -1.);
}
queue_append_finish(qa);
}
sc->queue_next = qnext;
return res;
}
int32_t
stepcompress_push_delta(
struct stepcompress *sc, double clock_offset, double move_sd
struct stepcompress *sc, double print_time, double move_sd
, double start_sv, double accel
, double height, double startxy_sd, double arm_sd, double movez_r)
{
@@ -639,22 +678,22 @@ stepcompress_push_delta(
if (reversexy_sd <= 0.)
// All steps are in down direction
return _stepcompress_push_delta(
sc, 0, clock_offset, move_sd, start_sv, accel
sc, 0, print_time, move_sd, start_sv, accel
, height, startxy_sd, arm_sd, movez_r);
double movexy_r = movez_r ? sqrt(1. - movez_r*movez_r) : 1.;
if (reversexy_sd >= move_sd * movexy_r)
// All steps are in up direction
return _stepcompress_push_delta(
sc, 1, clock_offset, move_sd, start_sv, accel
sc, 1, print_time, move_sd, start_sv, accel
, height, startxy_sd, arm_sd, movez_r);
// Steps in both up and down direction
int res1 = _stepcompress_push_delta(
sc, 1, clock_offset, reversexy_sd / movexy_r, start_sv, accel
sc, 1, print_time, reversexy_sd / movexy_r, start_sv, accel
, height, startxy_sd, arm_sd, movez_r);
if (res1 == ERROR_RET)
return res1;
int res2 = _stepcompress_push_delta(
sc, 0, clock_offset, move_sd, start_sv, accel
sc, 0, print_time, move_sd, start_sv, accel
, height + res1, startxy_sd, arm_sd, movez_r);
if (res2 == ERROR_RET)
return res2;
@@ -718,6 +757,17 @@ steppersync_free(struct steppersync *ss)
free(ss);
}
// Set the conversion rate of 'print_time' to mcu clock
void
steppersync_set_time(struct steppersync *ss, double time_offset, double mcu_freq)
{
int i;
for (i=0; i<ss->sc_num; i++) {
struct stepcompress *sc = ss->sc_list[i];
stepcompress_set_time(sc, time_offset, mcu_freq);
}
}
// Implement a binary heap algorithm to track when the next available
// 'struct move' in the mcu will be available
static void
+87 -60
View File
@@ -1,10 +1,10 @@
# Printer stepper support
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import math, logging
import homing
import homing, pins
class PrinterStepper:
def __init__(self, printer, config, name):
@@ -13,52 +13,18 @@ class PrinterStepper:
self.step_dist = config.getfloat('step_distance', above=0.)
self.inv_step_dist = 1. / self.step_dist
self.min_stop_interval = 0.
self.mcu_stepper = pins.setup_pin(
printer, 'stepper', config.get('step_pin'))
dir_pin_params = pins.get_printer_pins(printer).parse_pin_desc(
config.get('dir_pin'), can_invert=True)
self.mcu_stepper.setup_dir_pin(dir_pin_params)
self.mcu_stepper.setup_step_distance(self.step_dist)
self.homing_speed = config.getfloat('homing_speed', 5.0, above=0.)
self.homing_positive_dir = config.getboolean(
'homing_positive_dir', False)
self.homing_retract_dist = config.getfloat(
'homing_retract_dist', 5., above=0.)
self.homing_stepper_phases = config.getint(
'homing_stepper_phases', None, minval=0)
endstop_accuracy = config.getfloat(
'homing_endstop_accuracy', None, above=0.)
self.homing_endstop_accuracy = self.homing_endstop_phase = None
if self.homing_stepper_phases:
self.homing_endstop_phase = config.getint(
'homing_endstop_phase', None, minval=0
, maxval=self.homing_stepper_phases-1)
if endstop_accuracy is None:
self.homing_endstop_accuracy = self.homing_stepper_phases//2 - 1
elif self.homing_endstop_phase is not None:
self.homing_endstop_accuracy = int(math.ceil(
endstop_accuracy * self.inv_step_dist / 2.))
else:
self.homing_endstop_accuracy = int(math.ceil(
endstop_accuracy * self.inv_step_dist))
if self.homing_endstop_accuracy >= self.homing_stepper_phases/2:
logging.info("Endstop for %s is not accurate enough for stepper"
" phase adjustment" % (name,))
self.homing_stepper_phases = None
if printer.mcu.is_fileoutput():
self.homing_endstop_accuracy = self.homing_stepper_phases
self.position_min = self.position_endstop = self.position_max = None
endstop_pin = config.get('endstop_pin', None)
step_pin = config.get('step_pin')
dir_pin = config.get('dir_pin')
mcu = printer.mcu
self.mcu_stepper = mcu.create_stepper(step_pin, dir_pin)
self.mcu_stepper.set_step_distance(self.step_dist)
enable_pin = config.get('enable_pin', None)
self.mcu_enable = None
if enable_pin is not None:
self.mcu_enable = mcu.create_digital_out(enable_pin, 0)
if endstop_pin is not None:
self.mcu_endstop = mcu.create_endstop(endstop_pin)
self.mcu_endstop.add_stepper(self.mcu_stepper)
self.position_min = config.getfloat('position_min', 0.)
self.position_max = config.getfloat(
'position_max', 0., above=self.position_min)
self.position_endstop = config.getfloat('position_endstop')
self.mcu_enable = pins.setup_pin(printer, 'digital_out', enable_pin)
self.mcu_enable.setup_max_duration(0.)
self.need_motor_enable = True
def _dist_to_time(self, dist, start_velocity, accel):
# Calculate the time it takes to travel a distance with constant accel
@@ -71,31 +37,92 @@ class PrinterStepper:
second_last_step_time = self._dist_to_time(
2. * self.step_dist, max_halt_velocity, max_accel)
min_stop_interval = second_last_step_time - last_step_time
self.mcu_stepper.set_min_stop_interval(min_stop_interval)
def motor_enable(self, move_time, enable=0):
self.mcu_stepper.setup_min_stop_interval(min_stop_interval)
def motor_enable(self, print_time, enable=0):
if enable and self.need_motor_enable:
mcu_time = self.mcu_stepper.print_to_mcu_time(move_time)
self.mcu_stepper.reset_step_clock(mcu_time)
self.mcu_stepper.reset_step_clock(print_time)
if (self.mcu_enable is not None
and self.mcu_enable.get_last_setting() != enable):
mcu_time = self.mcu_enable.print_to_mcu_time(move_time)
self.mcu_enable.set_digital(mcu_time, enable)
self.mcu_enable.set_digital(print_time, enable)
self.need_motor_enable = not enable
def enable_endstop_checking(self, move_time, step_time):
mcu_time = self.mcu_endstop.print_to_mcu_time(move_time)
self.mcu_endstop.home_start(mcu_time, step_time)
return self.mcu_endstop
def query_endstop(self, print_time):
mcu_time = self.mcu_endstop.print_to_mcu_time(print_time)
self.mcu_endstop.query_endstop(mcu_time)
return self.mcu_endstop
class PrinterHomingStepper(PrinterStepper):
def __init__(self, printer, config, name):
PrinterStepper.__init__(self, printer, config, name)
self.mcu_endstop = pins.setup_pin(
printer, 'endstop', config.get('endstop_pin'))
self.mcu_endstop.add_stepper(self.mcu_stepper)
self.position_min = config.getfloat('position_min', 0.)
self.position_max = config.getfloat(
'position_max', 0., above=self.position_min)
self.position_endstop = config.getfloat('position_endstop')
self.homing_speed = config.getfloat('homing_speed', 5.0, above=0.)
self.homing_positive_dir = config.getboolean('homing_positive_dir', None)
if self.homing_positive_dir is None:
axis_len = self.position_max - self.position_min
if self.position_endstop <= self.position_min + axis_len / 4.:
self.homing_positive_dir = False
elif self.position_endstop >= self.position_max - axis_len / 4.:
self.homing_positive_dir = True
else:
raise config.error(
"Unable to infer homing_positive_dir in section '%s'" % (
config.section,))
self.homing_retract_dist = config.getfloat(
'homing_retract_dist', 5., above=0.)
self.homing_stepper_phases = config.getint(
'homing_stepper_phases', None, minval=0)
endstop_accuracy = config.getfloat(
'homing_endstop_accuracy', None, above=0.)
self.homing_endstop_accuracy = self.homing_endstop_phase = None
if self.homing_stepper_phases:
self.homing_endstop_phase = config.getint(
'homing_endstop_phase', None, minval=0
, maxval=self.homing_stepper_phases-1)
if self.homing_endstop_phase is not None:
# Adjust the endstop position so 0.0 is always at a full step
micro_steps = self.homing_stepper_phases // 4
phase_offset = (
((self.homing_endstop_phase + micro_steps // 2) % micro_steps)
- micro_steps // 2) * self.step_dist
full_step = micro_steps * self.step_dist
es_pos = (int(self.position_endstop / full_step + .5) * full_step
+ phase_offset)
if es_pos != self.position_endstop:
logging.info("Changing %s endstop position to %.3f"
" (from %.3f)", self.name, es_pos,
self.position_endstop)
self.position_endstop = es_pos
if endstop_accuracy is None:
self.homing_endstop_accuracy = self.homing_stepper_phases//2 - 1
elif self.homing_endstop_phase is not None:
self.homing_endstop_accuracy = int(math.ceil(
endstop_accuracy * self.inv_step_dist / 2.))
else:
self.homing_endstop_accuracy = int(math.ceil(
endstop_accuracy * self.inv_step_dist))
if self.homing_endstop_accuracy >= self.homing_stepper_phases // 2:
logging.info("Endstop for %s is not accurate enough for stepper"
" phase adjustment", name)
self.homing_stepper_phases = None
if self.mcu_endstop.get_mcu().is_fileoutput():
self.homing_endstop_accuracy = self.homing_stepper_phases
def get_homing_speed(self):
# Round the configured homing speed so that it is an even
# number of ticks per step.
adjusted_freq = self.mcu_stepper.get_mcu().get_adjusted_freq()
dist_ticks = adjusted_freq * self.step_dist
ticks_per_step = round(dist_ticks / self.homing_speed)
return dist_ticks / ticks_per_step
def get_homed_offset(self):
if not self.homing_stepper_phases or self.need_motor_enable:
return 0
pos = self.mcu_stepper.get_mcu_position()
pos %= self.homing_stepper_phases
if self.homing_endstop_phase is None:
logging.info("Setting %s endstop phase to %d" % (self.name, pos))
logging.info("Setting %s endstop phase to %d", self.name, pos)
self.homing_endstop_phase = pos
return 0
delta = (pos - self.homing_endstop_phase) % self.homing_stepper_phases
+113 -107
View File
@@ -4,7 +4,7 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import math, logging
import cartesian, corexy, delta, extruder
import mcu, homing, cartesian, corexy, delta, extruder
# Common suffixes: _d is distance (in mm), _v is velocity (in
# mm/second), _v2 is velocity squared (mm^2/s^2), _t is time (in
@@ -42,18 +42,18 @@ class Move:
self.delta_v2 = 2.0 * self.move_d * self.accel
self.smooth_delta_v2 = min(self.smooth_delta_v2, self.delta_v2)
def calc_junction(self, prev_move):
axes_d = self.axes_d
prev_axes_d = prev_move.axes_d
if (axes_d[2] or prev_axes_d[2] or self.accel != prev_move.accel
or not self.is_kinematic_move or not prev_move.is_kinematic_move):
if not self.is_kinematic_move or not prev_move.is_kinematic_move:
return
# Allow extruder to calculate its maximum junction
extruder_v2 = self.toolhead.extruder.calc_junction(prev_move, self)
# Find max velocity using approximated centripetal velocity as
# described at:
# https://onehossshay.wordpress.com/2011/09/24/improving_grbl_cornering_algorithm/
axes_d = self.axes_d
prev_axes_d = prev_move.axes_d
junction_cos_theta = -((axes_d[0] * prev_axes_d[0]
+ axes_d[1] * prev_axes_d[1])
+ axes_d[1] * prev_axes_d[1]
+ axes_d[2] * prev_axes_d[2])
/ (self.move_d * prev_move.move_d))
if junction_cos_theta > 0.999999:
return
@@ -61,8 +61,9 @@ class Move:
sin_theta_d2 = math.sqrt(0.5*(1.0-junction_cos_theta))
R = self.toolhead.junction_deviation * sin_theta_d2 / (1. - sin_theta_d2)
self.max_start_v2 = min(
R * self.accel, self.max_cruise_v2, prev_move.max_cruise_v2
, extruder_v2, prev_move.max_start_v2 + prev_move.delta_v2)
R * self.accel, R * prev_move.accel, extruder_v2
, self.max_cruise_v2, prev_move.max_cruise_v2
, prev_move.max_start_v2 + prev_move.delta_v2)
self.max_smoothed_v2 = min(
self.max_start_v2
, prev_move.max_smoothed_v2 + prev_move.smooth_delta_v2)
@@ -96,8 +97,8 @@ LOOKAHEAD_FLUSH_TIME = 0.250
# Class to track a list of pending move requests and to facilitate
# "look-ahead" across moves to reduce acceleration between moves.
class MoveQueue:
def __init__(self, extruder_lookahead):
self.extruder_lookahead = extruder_lookahead
def __init__(self):
self.extruder_lookahead = None
self.queue = []
self.leftover = 0
self.junction_flush = LOOKAHEAD_FLUSH_TIME
@@ -107,6 +108,8 @@ class MoveQueue:
self.junction_flush = LOOKAHEAD_FLUSH_TIME
def set_flush_time(self, flush_time):
self.junction_flush = flush_time
def set_extruder(self, extruder):
self.extruder_lookahead = extruder.lookahead
def flush(self, lazy=False):
self.junction_flush = LOOKAHEAD_FLUSH_TIME
update_flush_count = lazy
@@ -181,21 +184,16 @@ class ToolHead:
def __init__(self, printer, config):
self.printer = printer
self.reactor = printer.reactor
self.extruder = printer.objects.get('extruder')
if self.extruder is None:
self.extruder = extruder.DummyExtruder()
kintypes = {'cartesian': cartesian.CartKinematics,
'corexy': corexy.CoreXYKinematics,
'delta': delta.DeltaKinematics}
self.kin = config.getchoice('kinematics', kintypes)(printer, config)
self.max_speed = config.getfloat('max_velocity', above=0.)
self.all_mcus = mcu.get_printer_mcus(printer)
self.mcu = self.all_mcus[0]
self.max_velocity = config.getfloat('max_velocity', above=0.)
self.max_accel = config.getfloat('max_accel', above=0.)
self.max_accel_to_decel = config.getfloat(
'max_accel_to_decel', self.max_accel * 0.5
, above=0., maxval=self.max_accel)
self.junction_deviation = config.getfloat(
'junction_deviation', 0.02, above=0.)
self.move_queue = MoveQueue(self.extruder.lookahead)
self.move_queue = MoveQueue()
self.commanded_pos = [0., 0., 0., 0.]
# Print time tracking
self.buffer_time_low = config.getfloat(
@@ -207,121 +205,108 @@ class ToolHead:
self.move_flush_time = config.getfloat(
'move_flush_time', 0.050, above=0.)
self.print_time = 0.
self.last_print_end_time = self.reactor.monotonic()
self.need_check_stall = -1.
self.print_stall = 0
self.synch_print_time = True
self.forced_synch = False
self.sync_print_time = True
self.last_flush_from_idle = False
self.flush_timer = self.reactor.register_timer(self._flush_handler)
self.move_queue.set_flush_time(self.buffer_time_high)
# Motor off tracking
self.motor_off_time = config.getfloat(
'motor_off_time', 600.000, minval=0.)
self.need_motor_off = False
self.motor_off_time = config.getfloat('motor_off_time', 600., above=0.)
self.motor_off_timer = self.reactor.register_timer(
self._motor_off_handler)
# Determine the maximum velocity a cartesian axis could have
# before cornering. The 8. was determined experimentally.
xy_halt = math.sqrt(8. * self.junction_deviation * self.max_accel)
self.kin.set_max_jerk(xy_halt, self.max_speed, self.max_accel)
self.extruder.set_max_jerk(xy_halt, self.max_speed, self.max_accel)
self._motor_off_handler, self.reactor.NOW)
# Create kinematics class
self.extruder = extruder.DummyExtruder()
self.move_queue.set_extruder(self.extruder)
kintypes = {'cartesian': cartesian.CartKinematics,
'corexy': corexy.CoreXYKinematics,
'delta': delta.DeltaKinematics}
self.kin = config.getchoice('kinematics', kintypes)(
self, printer, config)
# Print time tracking
def update_move_time(self, movetime):
self.print_time += movetime
flush_to_time = self.print_time - self.move_flush_time
self.printer.mcu.flush_moves(flush_to_time)
for m in self.all_mcus:
m.flush_moves(flush_to_time)
def get_next_move_time(self):
if self.synch_print_time:
curtime = self.reactor.monotonic()
if self.print_time:
buffer_time = self.printer.mcu.get_print_buffer_time(
curtime, self.print_time)
self.print_time += max(self.buffer_time_start - buffer_time, 0.)
if self.forced_synch:
self.print_stall += 1
self.forced_synch = False
else:
self.printer.mcu.set_print_start_time(curtime)
self.print_time = self.buffer_time_start
self._reset_motor_off()
self.reactor.update_timer(self.flush_timer, self.reactor.NOW)
self.synch_print_time = False
if not self.sync_print_time:
return self.print_time
self.sync_print_time = False
est_print_time = self.mcu.estimated_print_time(self.reactor.monotonic())
if self.last_flush_from_idle and self.print_time > est_print_time:
self.print_stall += 1
self.last_flush_from_idle = False
self.need_motor_off = True
self.print_time = max(
self.print_time, est_print_time + self.buffer_time_start)
self.reactor.update_timer(self.flush_timer, self.reactor.NOW)
return self.print_time
def _flush_lookahead(self, must_synch=False):
synch_print_time = self.synch_print_time
def _flush_lookahead(self, must_sync=False):
sync_print_time = self.sync_print_time
self.move_queue.flush()
if synch_print_time or must_synch:
self.synch_print_time = True
self.last_flush_from_idle = False
if sync_print_time or must_sync:
self.sync_print_time = True
self.move_queue.set_flush_time(self.buffer_time_high)
self.printer.mcu.flush_moves(self.print_time)
self.need_check_stall = -1.
self.reactor.update_timer(self.flush_timer, self.reactor.NEVER)
for m in self.all_mcus:
m.flush_moves(self.print_time)
def get_last_move_time(self):
self._flush_lookahead()
return self.get_next_move_time()
def reset_print_time(self):
self._flush_lookahead(must_synch=True)
self.print_time = 0.
self.last_print_end_time = self.reactor.monotonic()
self.need_check_stall = -1.
self.forced_synch = False
self._reset_motor_off()
def reset_print_time(self, min_print_time=0.):
self._flush_lookahead(must_sync=True)
self.print_time = max(min_print_time, self.mcu.estimated_print_time(
self.reactor.monotonic()))
def _check_stall(self):
eventtime = self.reactor.monotonic()
if not self.print_time:
if self.sync_print_time:
# Building initial queue - make sure to flush on idle input
self.reactor.update_timer(self.flush_timer, eventtime + 0.100)
return
# Check if there are lots of queued moves and stall if so
while 1:
buffer_time = self.printer.mcu.get_print_buffer_time(
eventtime, self.print_time)
est_print_time = self.mcu.estimated_print_time(eventtime)
buffer_time = self.print_time - est_print_time
stall_time = buffer_time - self.buffer_time_high
if stall_time <= 0.:
break
eventtime = self.reactor.pause(eventtime + stall_time)
if not self.print_time:
if self.mcu.is_fileoutput():
self.need_check_stall = self.reactor.NEVER
return
self.need_check_stall = self.print_time - stall_time + 0.100
eventtime = self.reactor.pause(eventtime + min(1., stall_time))
self.need_check_stall = est_print_time + self.buffer_time_high + 0.100
def _flush_handler(self, eventtime):
try:
if not self.print_time:
# Input idled before filling lookahead queue - flush it
self._flush_lookahead()
if not self.print_time:
return self.reactor.NEVER
print_time = self.print_time
buffer_time = self.printer.mcu.get_print_buffer_time(
eventtime, print_time)
buffer_time = print_time - self.mcu.estimated_print_time(eventtime)
if buffer_time > self.buffer_time_low:
# Running normally - reschedule check
return eventtime + buffer_time - self.buffer_time_low
# Under ran low buffer mark - flush lookahead queue
self._flush_lookahead(must_synch=True)
self._flush_lookahead(must_sync=True)
if print_time != self.print_time:
# Flushed something - retry
self.forced_synch = True
return self.reactor.NOW
if buffer_time > 0.:
# Wait for buffer to fully empty
return eventtime + buffer_time
self.reset_print_time()
self.last_flush_from_idle = True
except:
logging.exception("Exception in flush_handler")
self.force_shutdown()
self.printer.invoke_shutdown("Exception in flush_handler")
return self.reactor.NEVER
# Motor off timer
def _reset_motor_off(self):
if not self.print_time:
waketime = self.reactor.monotonic() + self.motor_off_time
else:
waketime = self.reactor.NEVER
self.reactor.update_timer(self.motor_off_timer, waketime)
def _motor_off_handler(self, eventtime):
if not self.need_motor_off or not self.sync_print_time:
return eventtime + self.motor_off_time
elapsed_time = self.mcu.estimated_print_time(eventtime) - self.print_time
if elapsed_time < self.motor_off_time:
return eventtime + self.motor_off_time - elapsed_time
try:
self.motor_off()
self.reset_print_time()
except:
logging.exception("Exception in motor_off_handler")
self.force_shutdown()
return self.reactor.NEVER
self.printer.invoke_shutdown("Exception in motor_off_handler")
return eventtime + self.motor_off_time
# Movement commands
def get_position(self):
return list(self.commanded_pos)
@@ -330,7 +315,7 @@ class ToolHead:
self.commanded_pos[:] = newpos
self.kin.set_position(newpos)
def move(self, newpos, speed):
speed = min(speed, self.max_speed)
speed = min(speed, self.max_velocity)
move = Move(self, self.commanded_pos, newpos, speed)
if not move.move_d:
return
@@ -354,31 +339,52 @@ class ToolHead:
self.kin.motor_off(last_move_time)
self.extruder.motor_off(last_move_time)
self.dwell(STALL_TIME)
logging.debug('; Max time of %f' % (last_move_time,))
self.need_motor_off = False
logging.debug('; Max time of %f', last_move_time)
def wait_moves(self):
self._flush_lookahead()
if self.mcu.is_fileoutput():
return
eventtime = self.reactor.monotonic()
while self.print_time:
while (not self.sync_print_time
or self.print_time >= self.mcu.estimated_print_time(eventtime)):
eventtime = self.reactor.pause(eventtime + 0.100)
def query_endstops(self):
def query_endstops(self, query_flags=""):
last_move_time = self.get_last_move_time()
return self.kin.query_endstops(last_move_time)
return self.kin.query_endstops(last_move_time, query_flags)
def set_extruder(self, extruder):
last_move_time = self.get_last_move_time()
self.extruder.set_active(last_move_time, False)
extrude_pos = extruder.set_active(last_move_time, True)
self.extruder = extruder
self.move_queue.set_extruder(extruder)
self.commanded_pos[3] = extrude_pos
# Misc commands
def check_active(self, eventtime):
for m in self.all_mcus:
m.check_active(self.print_time, eventtime)
if not self.sync_print_time:
return True
return self.print_time + 60. > self.mcu.estimated_print_time(eventtime)
def stats(self, eventtime):
buffer_time = 0.
print_time = self.print_time
if print_time:
is_active = True
buffer_time = max(0., self.printer.mcu.get_print_buffer_time(
eventtime, print_time))
else:
is_active = eventtime < self.last_print_end_time + 60.
return is_active, "print_time=%.3f buffer_time=%.3f print_stall=%d" % (
print_time, buffer_time, self.print_stall)
def force_shutdown(self):
est_print_time = self.mcu.estimated_print_time(eventtime)
buffer_time = max(0., self.print_time - est_print_time)
return "print_time=%.3f buffer_time=%.3f print_stall=%d" % (
self.print_time, buffer_time, self.print_stall)
def do_shutdown(self):
try:
self.printer.mcu.force_shutdown()
self.move_queue.reset()
self.reset_print_time()
except:
logging.exception("Exception in force_shutdown")
logging.exception("Exception in do_shutdown")
def get_max_velocity(self):
return self.max_velocity, self.max_accel
def get_max_axis_halt(self):
# Determine the maximum velocity a cartesian axis could halt
# at due to the junction_deviation setting. The 8.0 was
# determined experimentally.
return min(self.max_velocity,
math.sqrt(8. * self.junction_deviation * self.max_accel))
def add_printer_objects(printer, config):
printer.add_object('toolhead', ToolHead(printer, config))
+5 -5
View File
@@ -43,8 +43,8 @@ def get_cpu_info():
data = f.read()
f.close()
except OSError:
logging.debug("Exception on read /proc/cpuinfo: %s" % (
traceback.format_exc(),))
logging.debug("Exception on read /proc/cpuinfo: %s",
traceback.format_exc())
return "?"
lines = [l.split(':', 1) for l in data.split('\n')]
lines = [(l[0].strip(), l[1].strip()) for l in lines if len(l) == 2]
@@ -54,16 +54,16 @@ def get_cpu_info():
def get_git_version():
# Obtain version info from "git" program
gitdir = os.path.join(sys.path[0], '..', '.git')
gitdir = os.path.join(sys.path[0], '..')
if not os.path.exists(gitdir):
logging.debug("No '.git' file/directory found")
return "?"
prog = "git --git-dir=%s describe --tags --long --dirty" % (gitdir,)
prog = "git -C %s describe --tags --long --dirty" % (gitdir,)
try:
process = subprocess.Popen(shlex.split(prog), stdout=subprocess.PIPE)
output = process.communicate()[0]
retcode = process.poll()
except OSError:
logging.debug("Exception on run: %s" % (traceback.format_exc(),))
logging.debug("Exception on run: %s", traceback.format_exc())
return "?"
return output.strip()
+12 -4
View File
@@ -3,14 +3,22 @@ This directory contains external library code.
The pjrc_usb_serial directory contains code from:
http://www.pjrc.com/teensy/usb_serial.html
version 1.7 (extracted on 20160605). It has been modified to compile
on recent versions of gcc. See usb_serial.patch for the modifications.
on recent versions of gcc, to support asynchronous notification of
incoming data, and to not use SOF interrupts. See usb_serial.patch for
the modifications.
The cmsis-sam3x8e directory contains code from the Arduino project:
https://www.arduino.cc/
version 1.5.1 (extracted on 20160608). It has been modified to
compile with gcc's LTO feature. See cmsis-sam3x8e.patch for the
modifications.
version 1.5.1 (extracted on 20160608). It has been modified to compile
with gcc's LTO feature. See cmsis-sam3x8e.patch for the modifications.
The hub-ctrl directory contains code from:
https://github.com/codazoda/hub-ctrl.c/
revision 42095e522859059e8a5f4ec05c1e3def01a870a9.
The pru_rpmsg directory contains code from:
https://github.com/dinuxbg/pru-gcc-examples
revision 425a42d82006cf0aa24be27b483d2f6a41607489. The code is taken
from the repo's hc-sr04-range-sensor directory. It has been modified
so that the IEP definitions compile correctly. See pru_rpmsg.patch for
the modifications.
+10 -2
View File
@@ -325,7 +325,7 @@ void usb_init(void)
UDCON = 0; // enable attach resistor
usb_configuration = 0;
cdc_line_rtsdtr = 0;
UDIEN = (1<<EORSTE)|(1<<SOFE);
UDIEN = (1<<EORSTE);
sei();
}
@@ -359,6 +359,7 @@ int16_t usb_serial_getchar(void)
UEINTX = 0x6B;
goto retry;
}
UEIENX = (1<<RXOUTE);
SREG = intr_state;
return -1;
}
@@ -775,7 +776,14 @@ static inline void usb_ack_out(void)
//
ISR(USB_COM_vect)
{
uint8_t intbits;
uint8_t intbits = UEINT;
if (intbits & (1<<CDC_RX_ENDPOINT)) {
UENUM = CDC_RX_ENDPOINT;
UEIENX = 0;
extern void sched_wake_tasks(void);
sched_wake_tasks();
return;
}
const uint8_t *list;
const uint8_t *cfg;
uint8_t i, n, len, en;
+36 -3
View File
@@ -1,5 +1,5 @@
--- usb_serial.c 2011-04-19 05:54:12.000000000 -0400
+++ usb_serial.c 2016-06-04 23:48:52.590001697 -0400
--- ../../../lib/pjrc/usb_serial/usb_serial.c 2011-04-19 05:54:12.000000000 -0400
+++ usb_serial.c 2017-08-07 11:32:47.106357362 -0400
@@ -30,6 +30,7 @@
// Version 1.6: fix zero length packet bug
// Version 1.7: fix usb_serial_set_control
@@ -62,7 +62,24 @@
uint16_t wValue;
uint16_t wIndex;
const uint8_t *addr;
@@ -646,7 +647,9 @@
@@ -324,7 +325,7 @@
UDCON = 0; // enable attach resistor
usb_configuration = 0;
cdc_line_rtsdtr = 0;
- UDIEN = (1<<EORSTE)|(1<<SOFE);
+ UDIEN = (1<<EORSTE);
sei();
}
@@ -358,6 +359,7 @@
UEINTX = 0x6B;
goto retry;
}
+ UEIENX = (1<<RXOUTE);
SREG = intr_state;
return -1;
}
@@ -646,7 +648,9 @@
// communication
uint32_t usb_serial_get_baud(void)
{
@@ -73,3 +90,19 @@
}
uint8_t usb_serial_get_stopbits(void)
{
@@ -772,7 +776,14 @@
//
ISR(USB_COM_vect)
{
- uint8_t intbits;
+ uint8_t intbits = UEINT;
+ if (intbits & (1<<CDC_RX_ENDPOINT)) {
+ UENUM = CDC_RX_ENDPOINT;
+ UEIENX = 0;
+ extern void sched_wake_tasks(void);
+ sched_wake_tasks();
+ return;
+ }
const uint8_t *list;
const uint8_t *cfg;
uint8_t i, n, len, en;
+25
View File
@@ -0,0 +1,25 @@
Programmable Real-time Unit (PRU) Software Support Package
------------------------------------------------------------
============================================================
INCLUDE
============================================================
DESCRIPTION
This directory provides header files for PRU firmware.
For more details about these header files, visit:
http://processors.wiki.ti.com/index.php/PRU-ICSS_Header_Files
ADDITIONAL RESOURCES
For more information about the PRU, visit:
PRU-ICSS Wiki - http://processors.wiki.ti.com/index.php/PRU-ICSS
PRU Training Slides - http://www.ti.com/sitarabootcamp
PRU Evaluation Hardware - http://www.ti.com/tool/PRUCAPE
Support - http://e2e.ti.com
+249
View File
@@ -0,0 +1,249 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PRU_CFG_H_
#define _PRU_CFG_H_
/* PRU_CFG register set */
typedef struct {
/* PRU_CFG_REVID register bit field */
union {
volatile uint32_t REVID;
volatile struct {
unsigned REVID : 32;
} REVID_bit;
}; // 0x0
/* PRU_CFG_SYSCFG register bit field */
union {
volatile uint32_t SYSCFG;
volatile struct {
unsigned IDLE_MODE : 2;
unsigned STANDBY_MODE : 2;
unsigned STANDBY_INIT : 1;
unsigned SUB_MWAIT : 1;
unsigned rsvd6 : 26;
} SYSCFG_bit;
}; // 0x4
/* PRU_CFG_GPCFG0 register bit field */
union {
volatile uint32_t GPCFG0;
volatile struct {
unsigned PRU0_GPI_MODE : 2; // 1:0
unsigned PRU0_GPI_CLK_MODE : 1; // 2
unsigned PRU0_GPI_DIV0 : 5; // 7:3
unsigned PRU0_GPI_DIV1 : 5; // 12:8
unsigned PRU0_GPI_SB : 1; // 13
unsigned PRU0_GPO_MODE : 1; // 14
unsigned PRU0_GPO_DIV0 : 5; // 19:15
unsigned PRU0_GPO_DIV1 : 5; // 24:20
unsigned PRU0_GPO_SH_SEL : 1; // 25
unsigned rsvd26 : 6; // 31:26
} GPCFG0_bit;
}; // 0x8
/* PRU_CFG_GPCFG1 register bit field */
union {
volatile uint32_t GPCFG1;
volatile struct {
unsigned PRU1_GPI_MODE : 2; // 1:0
unsigned PRU1_GPI_CLK_MODE : 1; // 2
unsigned PRU1_GPI_DIV0 : 5; // 7:3
unsigned PRU1_GPI_DIV1 : 5; // 12:8
unsigned PRU1_GPI_SB : 1; // 13
unsigned PRU1_GPO_MODE : 1; // 14
unsigned PRU1_GPO_DIV0 : 5; // 19:15
unsigned PRU1_GPO_DIV1 : 5; // 24:20
unsigned PRU1_GPO_SH_SEL : 1; // 25
unsigned rsvd26 : 6; // 31:26
} GPCFG1_bit;
}; // 0xC
/* PRU_CFG_CGR register bit field */
union {
volatile uint32_t CGR;
volatile struct {
unsigned PRU0_CLK_STOP_REQ : 1; // 0
unsigned PRU0_CLK_STOP_ACK : 1; // 1
unsigned PRU0_CLK_EN : 1; // 2
unsigned PRU1_CLK_STOP_REQ : 1; // 3
unsigned PRU1_CLK_STOP_ACK : 1; // 4
unsigned PRU1_CLK_EN : 1; // 5
unsigned INTC_CLK_STOP_REQ : 1; // 6
unsigned INTC_CLK_STOP_ACK : 1; // 7
unsigned INTC_CLK_EN : 1; // 8
unsigned UART_CLK_STOP_REQ : 1; // 9
unsigned UART_CLK_STOP_ACK : 1; // 10
unsigned UART_CLK_EN : 1; // 11
unsigned ECAP_CLK_STOP_REQ : 1; // 12
unsigned ECAP_CLK_STOP_ACK : 1; // 13
unsigned ECAP_CLK_EN : 1; // 14
unsigned IEP_CLK_STOP_REQ : 1; // 15
unsigned IEP_CLK_STOP_ACK : 1; // 16
unsigned IEP_CLK_EN : 1; // 17
unsigned rsvd18 : 14; // 31:18
} CGR_bit;
}; // 0x10
/* PRU_CFG_ISRP register bit field */
union {
volatile uint32_t ISRP;
volatile struct {
unsigned PRU0_IMEM_PE_RAW : 4; // 3:0
unsigned PRU0_DMEM_PE_RAW : 4; // 7:4
unsigned PRU1_IMEM_PE_RAW : 4; // 11:8
unsigned PRU1_DMEM_PE_RAW : 4; // 15:12
unsigned RAM_PE_RAW : 4; // 19:16
unsigned rsvd20 : 12; // 31:20
} ISRP_bit;
}; // 0x14
/* PRU_CFG_ISP register bit field */
union {
volatile uint32_t ISP;
volatile struct {
unsigned PRU0_IMEM_PE : 4; // 3:0
unsigned PRU0_DMEM_PE : 4; // 7:4
unsigned PRU1_IMEM_PE : 4; // 11:8
unsigned PRU1_DMEM_PE : 4; // 15:12
unsigned RAM_PE : 4; // 19:16
unsigned rsvd20 : 12; // 31:20
} ISP_bit;
}; // 0x18
/* PRU_CFG_IESP register bit field */
union {
volatile uint32_t IESP;
volatile struct {
unsigned PRU0_IMEM_PE_SET : 4; // 3:0
unsigned PRU0_DMEM_PE_SET : 4; // 7:4
unsigned PRU1_IMEM_PE_SET : 4; // 11:8
unsigned PRU1_DMEM_PE_SET : 4; // 15:12
unsigned RAM_PE_SET : 4; // 19:16
unsigned rsvd20 : 12; // 31:20
} IESP_bit;
}; // 0x1C
/* PRU_CFG_IECP register bit field */
union {
volatile uint32_t IECP;
volatile struct {
unsigned PRU0_IMEM_PE_CLR : 4; // 3:0
unsigned PRU0_DMEM_PE_CLR : 4; // 7:4
unsigned PRU1_IMEM_PE_CLR : 4; // 11:8
unsigned PRU1_DMEM_PE_CLR : 4; // 15:12
unsigned rsvd16 : 16; // 31:16
} IECP_bit;
}; // 0x20
uint32_t rsvd24; // 0x24
/* PRU_CFG_PMAO register bit field */
union {
volatile uint32_t PMAO;
volatile struct {
unsigned PMAO_PRU0 : 1; // 0
unsigned PMAO_PRU1 : 1; // 1
unsigned rsvd2 : 30; // 31:2
} PMAO_bit;
}; // 0x28
uint32_t rsvd2c[1]; // 0x2C
/* PRU_CFG_IEPCLK register bit field */
union {
volatile uint32_t IEPCLK;
volatile struct {
unsigned OCP_EN : 1; // 0
unsigned rsvd1 : 31; // 31:1
} IEPCLK_bit;
}; // 0x30
/* PRU_CFG_SPP register bit field */
union {
volatile uint32_t SPP;
volatile struct {
unsigned PRU1_PAD_HP_EN : 1; // 0
unsigned XFR_SHIFT_EN : 1; // 1
unsigned rsvd2 : 30; // 31:2
} SPP_bit;
}; // 0x34
uint32_t rsvd38[2]; // 0x38 - 0x3C
union {
volatile uint32_t PIN_MX;
volatile struct {
unsigned PIN_MUX_SEL : 8; // 7:0
unsigned rsvd2 : 24; // 31:8
} PIN_MX_bit;
}; //0x40
} pruCfg;
#ifdef __GNUC__
static volatile pruCfg *__CT_CFG = (void *)0x00026000;
#define CT_CFG (*__CT_CFG)
#else
volatile __far pruCfg CT_CFG __attribute__((cregister("PRU_CFG", near), peripheral));
#endif
#endif /* _PRU_CFG_H_ */
+155
View File
@@ -0,0 +1,155 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PRU_CTRL_H_
#define _PRU_CTRL_H_
/* PRU_CTRL register set */
typedef struct {
/* PRU_CTRL_CTRL register bit field */
union {
volatile uint32_t CTRL;
volatile struct {
unsigned SOFT_RST_N : 1;
unsigned EN : 1;
unsigned SLEEPING : 1;
unsigned CTR_EN : 1;
unsigned rsvd4 : 4;
unsigned SINGLE_STEP : 1;
unsigned rsvd9 : 6;
unsigned RUNSTATE : 1;
unsigned PCTR_RST_VAL : 16;
} CTRL_bit;
}; // 0x0
/* PRU_CTRL_STS register bit field */
union {
volatile uint32_t STS;
volatile struct {
unsigned PCTR : 16;
unsigned rsvd16 : 16;
} STS_bit;
}; // 0x4
/* PRU_CTRL_WAKEUP_EN register bit field */
union {
volatile uint32_t WAKEUP_EN;
volatile struct {
unsigned BITWISE_ENS : 32;
} WAKEUP_EN_bit;
}; // 0x8
/* PRU_CTRL_CYCLE register bit field */
union {
volatile uint32_t CYCLE;
volatile struct {
unsigned CYCLECOUNT : 32;
} CYCLE_bit;
}; // 0xC
/* PRU_CTRL_STALL register bit field */
union {
volatile uint32_t STALL;
volatile struct {
unsigned STALLCOUNT : 32;
} STALL_bit;
}; // 0x10
uint32_t rsvd14[3]; // 0x14 - 0x1C
/* PRU_CTRL_CTBIR0 register bit field */
union {
volatile uint32_t CTBIR0;
volatile struct {
unsigned C24_BLK_IDX : 8;
unsigned rsvd8 : 8;
unsigned C25_BLK_IDX : 8;
unsigned rsvd24 : 8;
} CTBIR0_bit;
}; // 0x20
/* PRU_CTRL_CTBIR1 register bit field */
union {
volatile uint32_t CTBIR1;
volatile struct {
unsigned C26_BLK_IDX : 8;
unsigned rsvd8 : 8;
unsigned C27_BLK_IDX : 8;
unsigned rsvd24 : 8;
} CTBIR1_bit;
}; // 0x24
/* PRU_CTRL_CTPPR0 register bit field */
union {
volatile uint32_t CTPPR0;
volatile struct {
unsigned C28_BLK_POINTER : 16;
unsigned C29_BLK_POINTER : 16;
} CTPPR0_bit;
}; // 0x28
/* PRU_CTRL_CTPPR1 register bit field */
union {
volatile uint32_t CTPPR1;
volatile struct {
unsigned C30_BLK_POINTER : 16;
unsigned C31_BLK_POINTER : 16;
} CTPPR1_bit;
}; // 0x2C
} pruCtrl;
/* Definition of control register structures. */
#define PRU0_CTRL (*((volatile pruCtrl*)0x22000))
#define PRU1_CTRL (*((volatile pruCtrl*)0x24000))
#endif /* _PRU_CTRL_H_ */
+128
View File
@@ -0,0 +1,128 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PRU_ECAP_H_
#define _PRU_ECAP_H_
/* PRU_ECAP register set */
typedef struct {
/* PRU_ECAP_TSCTR register bit field */
union {
volatile uint32_t TSCTR;
volatile struct {
unsigned TSCTR : 32; //31:0
} TSCTR_bit;
}; // 0x0
/* PRU_ECAP_CTRPHS register bit field */
union {
volatile uint32_t CTRPHS;
volatile struct {
unsigned CTRPHS : 32; //31:0
} CTRPHS_bit;
}; // 0x4
/* PRU_ECAP_CAP1 register bit field */
union {
volatile uint32_t CAP1;
volatile struct {
unsigned CAP1 : 32; //31:0
} CAP1_bit;
}; // 0x8
/* PRU_ECAP_CAP2 register bit field */
union {
volatile uint32_t CAP2;
volatile struct {
unsigned CAP2 : 32; //31:0
} CAP2_bit;
}; // 0xC
/* PRU_ECAP_CAP3 register bit field */
union {
volatile uint32_t CAP3;
volatile struct {
unsigned CAP3 : 32; //31:0
} CAP3_bit;
}; // 0x10
/* PRU_ECAP_CAP4 register bit field */
union {
volatile uint32_t CAP4;
volatile struct {
unsigned CAP4 : 32; //31:0
} CAP4_bit;
}; // 0x14
uint32_t rsvd118[4]; // 0x118 - 0x124
/* PRU_ECAP_ECCTL1 register bit field */
volatile uint16_t ECCTL1; // 0x28
/* PRU_ECAP_ECCTL2 register bit field */
volatile uint16_t ECCTL2; // 0x2A
/* PRU_ECAP_ECEINT register bit field */
volatile uint16_t ECEINT; // 0x2C
/* PRU_ECAP_ECFLG register bit field */
volatile uint16_t ECFLG; // 0x2E
/* PRU_ECAP_ECCLR register bit field */
volatile uint16_t ECCLR; // 0x30
/* PRU_ECAP_ECFRC register bit field */
volatile uint16_t ECFRC; // 0x32
uint32_t rsvd34[10]; // 0x34 - 0x58
/* PRU_ECAP_REVID register bit field */
union {
volatile uint32_t REVID;
volatile struct {
unsigned REV : 32; //31:0
} REVID_bit;
}; // 0x5C
} pruEcap;
volatile __far pruEcap CT_ECAP __attribute__((cregister("PRU_ECAP", near), peripheral));
#endif /* _PRU_ECAP_H_ */
+261
View File
@@ -0,0 +1,261 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PRU_IEP_H_
#define _PRU_IEP_H_
/* PRU IEP register set */
typedef struct {
/* PRU_IEP_TMR_GLB_CFG register bit field */
union {
volatile uint32_t TMR_GLB_CFG;
volatile struct {
unsigned CNT_EN : 1; // 0
unsigned rsvd1 : 3; // 3:1
unsigned DEFAULT_INC : 4; // 7:4
unsigned CMP_INC : 12; // 19:8
unsigned rsvd12 : 12; // 31:20
} TMR_GLB_CFG_bit;
}; // 0x0
/* PRU_IEP_TMR_GLB_STS register bit field */
union {
volatile uint32_t TMR_GLB_STS;
volatile struct {
unsigned CNT_OVF : 1; // 0
unsigned rsvd1 : 31; // 31:1
} TMR_GLB_STS_bit;
}; // 0x4
/* PRU_IEP_TMR_COMPEN register bit field */
union {
volatile uint32_t TMR_COMPEN;
volatile struct {
unsigned COMPEN_CNT : 24; // 23:0
unsigned rsvd24 : 8; // 31:24
} TMR_COMPEN_bit;
}; // 0x8
/* PRU_IEP_TMR_CNT register bit field */
union {
volatile uint32_t TMR_CNT;
volatile struct {
unsigned COUNT : 32; // 31:0
} TMR_CNT_bit;
}; // 0xC
uint32_t rsvd10[12]; // 0x10 - 0x3C
/* PRU_IEP_TMR_CMP_CFG register bit field */
union {
volatile uint32_t TMR_CMP_CFG;
volatile struct {
unsigned CMP0_RST_CNT_EN : 1; // 0
unsigned CMP_EN : 8; // 8:1
unsigned rsvd9 : 23; // 31:9
} TMR_CMP_CFG_bit;
}; // 0x40
/* PRU_IEP_TMR_CMP_STS register bit field */
union {
volatile uint32_t TMR_CMP_STS;
volatile struct {
unsigned CMP_HIT : 8; // 7:0
unsigned rsvd8 : 24; // 31:8
} TMR_CMP_STS_bit;
}; // 0x44
/* PRU_IEP_TMR_CMP0 register bit field */
union {
volatile uint32_t TMR_CMP0;
volatile struct {
unsigned CMP0 : 32; // 31:0
} TMR_CMP0_bit;
}; // 0x48
/* PRU_IEP_TMR_CMP1 register bit field */
union {
volatile uint32_t TMR_CMP1;
volatile struct {
unsigned CMP1 : 32; // 31:0
} TMR_CMP1_bit;
}; // 0x4C
/* PRU_IEP_TMR_CMP2 register bit field */
union {
volatile uint32_t TMR_CMP2;
volatile struct {
unsigned CMP2 : 32; // 31:0
} TMR_CMP2_bit;
}; // 0x50
/* PRU_IEP_TMR_CMP3 register bit field */
union {
volatile uint32_t TMR_CMP3;
volatile struct {
unsigned CMP3 : 32; // 31:0
} TMR_CMP3_bit;
}; // 0x54
/* PRU_IEP_TMR_CMP4 register bit field */
union {
volatile uint32_t TMR_CMP4;
volatile struct {
unsigned CMP4 : 32; // 31:0
} TMR_CMP4_bit;
}; // 0x58
/* PRU_IEP_TMR_CMP5 register bit field */
union {
volatile uint32_t TMR_CMP5;
volatile struct {
unsigned CMP5 : 32; // 31:0
} TMR_CMP5_bit;
}; // 0x5C
/* PRU_IEP_TMR_CMP6 register bit field */
union {
volatile uint32_t TMR_CMP6;
volatile struct {
unsigned CMP6 : 32; // 31:0
} TMR_CMP6_bit;
}; // 0x60
/* PRU_IEP_TMR_CMP7 register bit field */
union {
volatile uint32_t TMR_CMP7;
volatile struct {
unsigned CMP7 : 32; // 31:0
} TMR_CMP7_bit;
}; // 0x64
uint32_t rsvd68[166]; // 0x68 - 0x2FF
/* PRU_IEP_DIGIO_CTRL register bit field */
union {
volatile uint32_t DIGIO_CTRL;
volatile struct {
unsigned RESERVED0 : 4; // 3:0
unsigned IN_MODE : 1; // 4
unsigned RESERVED5 : 27; // 31:5
} DIGIO_CTRL_bit;
}; // 0x300
uint32_t rsvd304[1]; // 0x304
/* PRU_IEP_DIGIO_DATA_IN register bit field */
union {
volatile uint32_t DIGIO_DATA_IN;
volatile struct {
unsigned DATA_IN : 32; // 31:0
} DIGIO_DATA_IN_bit;
}; // 0x308
/* PRU_IEP_DIGIO_DATA_IN_RAW register bit field */
union {
volatile uint32_t DIGIO_DATA_IN_RAW;
volatile struct {
unsigned DATA_IN_RAW : 32; // 31:0
} DIGIO_DATA_IN_RAW_bit;
}; // 0x30C
/* PRU_IEP_DIGIO_DATA_OUT register bit field */
union {
volatile uint32_t DIGIO_DATA_OUT;
volatile struct {
unsigned DATA_OUT : 32; // 31:0
} DIGIO_DATA_OUT_bit;
}; // 0x310
/* PRU_IEP_DIGIO_DATA_OUT_EN register bit field */
union {
volatile uint32_t DIGIO_DATA_OUT_EN;
volatile struct {
unsigned DATA_OUT_EN : 32; // 31:0
} DIGIO_DATA_OUT_EN_bit;
}; // 0x314
/* PRU_IEP_DIGIO_EXP register bit field */
union {
volatile uint32_t DIGIO_EXP;
volatile struct {
unsigned SW_DATA_OUT_UPDATE : 1; // 0
unsigned OUTVALID_OVR_EN : 1; // 1
unsigned RESERVED2 : 30; // 31:2
} DIGIO_EXP_bit;
}; // 0x318
} pruIep;
#ifdef __GNUC__
static volatile pruIep *__CT_IEP = (void *)0x0002e000;
#define CT_IEP (*__CT_IEP)
#else
volatile __far pruIep CT_IEP __attribute__((cregister("PRU_IEP", far), peripheral));
#endif
#endif /* _PRU_IEP_H_ */
+912
View File
@@ -0,0 +1,912 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PRU_INTC_H_
#define _PRU_INTC_H_
/* PRU INTC register set */
typedef struct {
/* PRU_INTC_REVID register bit field */
union {
volatile uint32_t REVID;
volatile struct {
unsigned REV_MINOR : 6; // 5:0
unsigned REV_CUSTOM : 2; // 7:6
unsigned REV_MAJOR : 3; // 10:8
unsigned REV_RTL : 5; // 15:11
unsigned REV_MODULE : 12; // 27:16
unsigned rsvd28 : 2; // 29:28
unsigned REV_SCHEME : 2; // 31:30
} REVID_bit;
}; // 0x0
/* PRU_INTC_CR register bit field */
union {
volatile uint32_t CR;
volatile struct {
unsigned rsvd0 : 2; // 1:0
unsigned NEST_MODE : 2; // 3:2
unsigned rsvd4 : 28; // 31:4
} CR_bit;
}; // 0x4
uint32_t rsvd8[2]; // 0x8 - 0xC
/* PRU_INTC_GER register bit field */
union {
volatile uint32_t GER;
volatile struct {
unsigned EN_HINT_ANY : 1; // 0
unsigned rsvd1 : 31; // 31:1
} GER_bit;
}; // 0x10
uint32_t rsvd14[2]; // 0x14 - 0x18
/* PRU_INTC_GNLR register bit field */
union {
volatile uint32_t GNLR;
volatile struct {
unsigned GLB_NEST_LEVEL : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} GNLR_bit;
}; // 0x1C
/* PRU_INTC_SISR register bit field */
union {
volatile uint32_t SISR;
volatile struct {
unsigned STS_SET_IDX : 10; // 9:0
unsigned rsvd10 : 22; // 31:10
} SISR_bit;
}; // 0x20
/* PRU_INTC_SICR register bit field */
union {
volatile uint32_t SICR;
volatile struct {
unsigned STS_CLR_IDX : 10; // 9:0
unsigned rsvd10 : 22; // 31:10
} SICR_bit;
}; // 0x24
/* PRU_INTC_EISR register bit field */
union {
volatile uint32_t EISR;
volatile struct {
unsigned EN_SET_IDX : 10; // 9:0
unsigned rsvd10 : 22; // 31:10
} EISR_bit;
}; // 0x28
/* PRU_INTC_EICR register bit field */
union {
volatile uint32_t EICR;
volatile struct {
unsigned EN_CLR_IDX : 10; // 9:0
unsigned rsvd10 : 22; // 31:10
} EICR_bit;
}; // 0x2C
uint32_t rsvd30; // 0x30
/* PRU_INTC_HIEISR register bit field */
union {
volatile uint32_t HIEISR;
volatile struct {
unsigned HINT_EN_SET_IDX : 4; // 3:0
unsigned rsvd4 : 28; // 31:4
} HIEISR_bit;
}; // 0x34
/* PRU_INTC_HIDISR register bit field */
union {
volatile uint32_t HIDISR;
volatile struct {
unsigned HINT_EN_CLR_IDX : 4; // 3:0
unsigned rsvd4 : 28; // 31:4
} HIDISR_bit;
}; // 0x38
uint32_t rsvd3C[17]; // 0x3C - 0x7C
/* PRU_INTC_GPIR register bit field */
union {
volatile uint32_t GPIR;
volatile struct {
unsigned GLB_PRI_INTR : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned GLB_NONE : 1; // 31
} GPIR_bit;
}; // 0x80
uint32_t rsvd84[95]; // 0x84 - 0x1FC
/* PRU_INTC_SRSR0 register bit field */
union {
volatile uint32_t SRSR0;
volatile struct {
unsigned RAW_STS_31_0 : 32; // 31:0
} SRSR0_bit;
}; // 0x200
/* PRU_INTC_SRSR1 register bit field */
union {
volatile uint32_t SRSR1;
volatile struct {
unsigned RAW_STS_63_32 : 32; // 31:0
} SRSR1_bit;
}; // 0x204
uint32_t rsvd208[30]; // 0x208 - 0x27C
/* PRU_INTC_SECR0 register bit field */
union {
volatile uint32_t SECR0;
volatile struct {
unsigned ENA_STS_31_0 : 32; // 31:0
} SECR0_bit;
}; // 0x280
/* PRU_INTC_SECR1 register bit field */
union {
volatile uint32_t SECR1;
volatile struct {
unsigned ENA_STS_63_32 : 32; // 31:0
} SECR1_bit;
}; // 0x284
uint32_t rsvd288[30]; // 0x288 - 0x2FC
/* PRU_INTC_ESR0 register bit field */
union {
volatile uint32_t ESR0;
volatile struct {
unsigned EN_SET_31_0 : 32; // 31:0
} ESR0_bit;
}; // 0x300
/* PRU_INTC_ESR1 register bit field */
union {
volatile uint32_t ESR1;
volatile struct {
unsigned EN_SET_63_32 : 32; // 31:0
} ESR1_bit;
}; // 0x304
uint32_t rsvd308[30]; // 0x308 - 0x37C
/* PRU_INTC_ECR0 register bit field */
union {
volatile uint32_t ECR0;
volatile struct {
unsigned EN_CLR_31_0 : 32; // 31:0
} ECR0_bit;
}; // 0x380
/* PRU_INTC_ECR1 register bit field */
union {
volatile uint32_t ECR1;
volatile struct {
unsigned EN_CLR_63_32 : 32; // 31:0
} ECR1_bit;
}; // 0x384
uint32_t rsvd388[30]; // 0x388 - 0x3FC
/* PRU_INTC_CMR0 register bit field */
union {
volatile uint32_t CMR0;
volatile struct {
unsigned CH_MAP_0 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_1 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_2 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_3 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR0_bit;
}; // 0x400
/* PRU_INTC_CMR1 register bit field */
union {
volatile uint32_t CMR1;
volatile struct {
unsigned CH_MAP_4 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_5 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_6 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_7 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR1_bit;
}; // 0x404
/* PRU_INTC_CMR2 register bit field */
union {
volatile uint32_t CMR2;
volatile struct {
unsigned CH_MAP_8 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_9 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_10 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_11 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR2_bit;
}; // 0x408
/* PRU_INTC_CMR3 register bit field */
union {
volatile uint32_t CMR3;
volatile struct {
unsigned CH_MAP_12 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_13 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_14 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_15 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR3_bit;
}; // 0x40C
/* PRU_INTC_CMR4 register bit field */
union {
volatile uint32_t CMR4;
volatile struct {
unsigned CH_MAP_16 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_17 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_18 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_19 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR4_bit;
}; // 0x410
/* PRU_INTC_CMR5 register bit field */
union {
volatile uint32_t CMR5;
volatile struct {
unsigned CH_MAP_20 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_21 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_22 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_23 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR5_bit;
}; // 0x414
/* PRU_INTC_CMR6 register bit field */
union {
volatile uint32_t CMR6;
volatile struct {
unsigned CH_MAP_24 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_25 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_26 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_27 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR6_bit;
}; // 0x418
/* PRU_INTC_CMR7 register bit field */
union {
volatile uint32_t CMR7;
volatile struct {
unsigned CH_MAP_28 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_29 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_30 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_31 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR7_bit;
}; // 0x41C
/* PRU_INTC_CMR8 register bit field */
union {
volatile uint32_t CMR8;
volatile struct {
unsigned CH_MAP_32 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_33 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_34 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_35 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR8_bit;
}; // 0x420
/* PRU_INTC_CMR9 register bit field */
union {
volatile uint32_t CMR9;
volatile struct {
unsigned CH_MAP_36 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_37 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_38 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_39 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR9_bit;
}; // 0x424
/* PRU_INTC_CMR10 register bit field */
union {
volatile uint32_t CMR10;
volatile struct {
unsigned CH_MAP_40 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_41 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_42 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_43 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR10_bit;
}; // 0x428
/* PRU_INTC_CMR11 register bit field */
union {
volatile uint32_t CMR11;
volatile struct {
unsigned CH_MAP_44 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_45 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_46 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_47 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR11_bit;
}; // 0x42C
/* PRU_INTC_CMR12 register bit field */
union {
volatile uint32_t CMR12;
volatile struct {
unsigned CH_MAP_48 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_49 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_50 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_51 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR12_bit;
}; // 0x430
/* PRU_INTC_CMR13 register bit field */
union {
volatile uint32_t CMR13;
volatile struct {
unsigned CH_MAP_52 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_53 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_54 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_55 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR13_bit;
}; // 0x434
/* PRU_INTC_CMR14 register bit field */
union {
volatile uint32_t CMR14;
volatile struct {
unsigned CH_MAP_56 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_57 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_58 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_59 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR14_bit;
}; // 0x438
/* PRU_INTC_CMR15 register bit field */
union {
volatile uint32_t CMR15;
volatile struct {
unsigned CH_MAP_60 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned CH_MAP_61 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned CH_MAP_62 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned CH_MAP_63 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} CMR15_bit;
}; // 0x43C
uint32_t rsvd440[240]; // 0x440 - 0x7FC
/* PRU_INTC_HMR0 register bit field */
union {
volatile uint32_t HMR0;
volatile struct {
unsigned HINT_MAP_0 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned HINT_MAP_1 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned HINT_MAP_2 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned HINT_MAP_3 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} HMR0_bit;
}; // 0x800
/* PRU_INTC_HMR1 register bit field */
union {
volatile uint32_t HMR1;
volatile struct {
unsigned HINT_MAP_4 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned HINT_MAP_5 : 4; // 11:8
unsigned rsvd12 : 4; // 15:12
unsigned HINT_MAP_6 : 4; // 19:16
unsigned rsvd20 : 4; // 23:20
unsigned HINT_MAP_7 : 4; // 27:24
unsigned rsvd28 : 4; // 31:28
} HMR1_bit;
}; // 0x804
/* PRU_INTC_HMR2 register bit field */
union {
volatile uint32_t HMR2;
volatile struct {
unsigned HINT_MAP_8 : 4; // 3:0
unsigned rsvd4 : 4; // 7:4
unsigned HINT_MAP_9 : 4; // 11:8
unsigned rsvd12 : 20; // 31:12
} HMR2_bit;
}; // 0x808
uint32_t rsvd80C[61]; // 0x80C - 0x8FC
/* PRU_INTC_HIPIR0 register bit field */
union {
volatile uint32_t HIPIR0;
volatile struct {
unsigned PRI_HINT_0 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_0 : 1; // 31
} HIPIR0_bit;
}; // 0x900
/* PRU_INTC_HIPIR1 register bit field */
union {
volatile uint32_t HIPIR1;
volatile struct {
unsigned PRI_HINT_1 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_1 : 1; // 31
} HIPIR1_bit;
}; // 0x904
/* PRU_INTC_HIPIR2 register bit field */
union {
volatile uint32_t HIPIR2;
volatile struct {
unsigned PRI_HINT_2 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_2 : 1; // 31
} HIPIR2_bit;
}; // 0x908
/* PRU_INTC_HIPIR3 register bit field */
union {
volatile uint32_t HIPIR3;
volatile struct {
unsigned PRI_HINT_3 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_3 : 1; // 31
} HIPIR3_bit;
}; // 0x90C
/* PRU_INTC_HIPIR4 register bit field */
union {
volatile uint32_t HIPIR4;
volatile struct {
unsigned PRI_HINT_4 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_4 : 1; // 31
} HIPIR4_bit;
}; // 0x910
/* PRU_INTC_HIPIR5 register bit field */
union {
volatile uint32_t HIPIR5;
volatile struct {
unsigned PRI_HINT_5 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_5 : 1; // 31
} HIPIR5_bit;
}; // 0x914
/* PRU_INTC_HIPIR6 register bit field */
union {
volatile uint32_t HIPIR6;
volatile struct {
unsigned PRI_HINT_6 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_6 : 1; // 31
} HIPIR6_bit;
}; // 0x918
/* PRU_INTC_HIPIR7 register bit field */
union {
volatile uint32_t HIPIR7;
volatile struct {
unsigned PRI_HINT_7 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_7 : 1; // 31
} HIPIR7_bit;
}; // 0x91C
/* PRU_INTC_HIPIR8 register bit field */
union {
volatile uint32_t HIPIR8;
volatile struct {
unsigned PRI_HINT_8 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_8 : 1; // 31
} HIPIR8_bit;
}; // 0x920
/* PRU_INTC_HIPIR9 register bit field */
union {
volatile uint32_t HIPIR9;
volatile struct {
unsigned PRI_HINT_9 : 10; // 9:0
unsigned rsvd10 : 21; // 30:10
unsigned NONE_HINT_9 : 1; // 31
} HIPIR9_bit;
}; // 0x924
uint32_t rsvd928[246]; // 0x928 - 0xCFC
/* PRU_INTC_SIPR0 register bit field */
union {
volatile uint32_t SIPR0;
volatile struct {
unsigned POLARITY_31_0 : 32; // 31:0
} SIPR0_bit;
}; // 0xD00
/* PRU_INTC_SIPR1 register bit field */
union {
volatile uint32_t SIPR1;
volatile struct {
unsigned POLARITY_63_32 : 32; // 31:0
} SIPR1_bit;
}; // 0xD04
uint32_t rsvdD08[30]; // 0xD08 - 0xD7C
/* PRU_INTC_SITR0 register bit field */
union {
volatile uint32_t SITR0;
volatile struct {
unsigned TYPE_31_0 : 32; // 31:0
} SITR0_bit;
}; // 0xD80
/* PRU_INTC_SITR1 register bit field */
union {
volatile uint32_t SITR1;
volatile struct {
unsigned TYPE_63_32 : 32; // 31:0
} SITR1_bit;
}; // 0xD84
uint32_t rsvdD84[222]; // 0xD88 - 0x10FC
/* PRU_INTC_HINLR0 register bit field */
union {
volatile uint32_t HINLR0;
volatile struct {
unsigned NEST_HINT_0 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR0_bit;
}; // 0x1100
/* PRU_INTC_HINLR1 register bit field */
union {
volatile uint32_t HINLR1;
volatile struct {
unsigned NEST_HINT_1 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR1_bit;
}; // 0x1104
/* PRU_INTC_HINLR2 register bit field */
union {
volatile uint32_t HINLR2;
volatile struct {
unsigned NEST_HINT_2 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR2_bit;
}; // 0x1108
/* PRU_INTC_HINLR3 register bit field */
union {
volatile uint32_t HINLR3;
volatile struct {
unsigned NEST_HINT_3 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR3_bit;
}; // 0x110C
/* PRU_INTC_HINLR4 register bit field */
union {
volatile uint32_t HINLR4;
volatile struct {
unsigned NEST_HINT_4 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR4_bit;
}; // 0x1110
/* PRU_INTC_HINLR5 register bit field */
union {
volatile uint32_t HINLR5;
volatile struct {
unsigned NEST_HINT_5 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR5_bit;
}; // 0x1114
/* PRU_INTC_HINLR6 register bit field */
union {
volatile uint32_t HINLR6;
volatile struct {
unsigned NEST_HINT_6 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR6_bit;
}; // 0x1118
/* PRU_INTC_HINLR7 register bit field */
union {
volatile uint32_t HINLR7;
volatile struct {
unsigned NEST_HINT_7 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR7_bit;
}; // 0x111C
/* PRU_INTC_HINLR8 register bit field */
union {
volatile uint32_t HINLR8;
volatile struct {
unsigned NEST_HINT_8 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR8_bit;
}; // 0x1120
/* PRU_INTC_HINLR9 register bit field */
union {
volatile uint32_t HINLR9;
volatile struct {
unsigned NEST_HINT_9 : 9; // 8:0
unsigned rsvd9 : 22; // 30:9
unsigned AUTO_OVERRIDE : 1; // 31
} HINLR9_bit;
}; // 0x1124
uint32_t rsvd1128[246]; // 0x1128 - 0x14FC
/* PRU_INTC_HIER register bit field */
union {
volatile uint32_t HIER;
volatile struct {
unsigned EN_HINT : 10; // 9:0
unsigned rsvd9 : 22; // 31:10
} HIER_bit;
}; // 0x1500
} pruIntc;
#ifdef __GNUC__
static volatile pruIntc *__CT_INTC = (void *)0x00020000;
#define CT_INTC (*__CT_INTC)
#else
volatile __far pruIntc CT_INTC __attribute__((cregister("PRU_INTC", far), peripheral));
#endif
#endif /* _PRU_INTC_H_ */
+285
View File
@@ -0,0 +1,285 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PRU_UART_H_
#define _PRU_UART_H_
/* UART Register set */
typedef struct {
/*
* RBR and THR register pair
* This is a unique register pair in that RBR and THR
* share the same address. RBR is read-only while THR is
* write-only.
*
* Additionally, RBR and THR share an address with DLL. To
* read/write RBR/THR write 0 to the DLAB bit in the LCR
* register. To modify DLL write a 1.
*
* DLL also has a dedicated
* address which does not require toggling the DLAB bit.
*/
union {
/* PRU_UART_RBR register bit field */
union {
volatile uint32_t RBR;
volatile struct {
unsigned DATA : 8; // 7:0
unsigned rsvd8 : 24; // 31:8
} RBR_bit;
};
/* PRU_UART_THR register bit field */
union {
volatile uint32_t THR;
volatile struct {
unsigned DATA : 8; // 7:0
unsigned rsvd8 : 24; // 31:8
} THR_bit;
};
}; // 0x0
/* PRU_UART_IER register bit field */
/*
* IER shares an address with DLH. To modify IER write 0
* to the DLAB bit in the LCR register. To modify DLH write a 1.
*
* DLH also has a dedicated address which does not require
* toggling the DLAB bit.
*/
union {
volatile uint32_t IER;
volatile struct {
unsigned ERBI : 1; // 0
unsigned ETBEI : 1; // 1
unsigned ELSI : 1; // 2
unsigned EDSSI : 1; // 3
unsigned rsvd4 : 28; // 31:4
} IER_bit;
}; // 0x4
/*
* IIR and FCR register pair
* This is a unique register pair in that IIR and FCR
* share the same address. IIR is read-only while FCR is
* write-only.
*/
union {
/* PRU_UART_IIR register bit field */
union {
volatile uint32_t IIR;
volatile struct {
unsigned IPEND : 1; // 0
unsigned INTID : 3; // 3:1
unsigned rsvd4 : 2; // 5:4
unsigned FIFOEN : 2; // 7:6
unsigned rsvd8 : 24; // 31:8
} IIR_bit;
};
/* PRU_UART_FCR register bit field */
union {
volatile uint32_t FCR;
volatile struct {
unsigned FIFOEN : 1; // 0
unsigned RXCLR : 1; // 1
unsigned TXCLR : 1; // 2
unsigned DMAMODE1 : 1; // 3
unsigned rsvd4 : 2; // 5:4
unsigned RXFIFTL : 2; // 7:6
unsigned rsvd8 : 24; // 31:8
} FCR_bit;
};
}; // 0x8
/* PRU_UART_LCR register bit field */
union {
volatile uint32_t LCR;
volatile struct {
unsigned WLS : 2; // 1:0
unsigned STB : 1; // 2
unsigned PEN : 1; // 3
unsigned EPS : 1; // 4
unsigned SP : 1; // 5
unsigned BC : 1; // 6
unsigned DLAB : 1; // 7
unsigned rsvd8 : 24; // 31:8
} LCR_bit;
}; // 0xC
/* PRU_UART_MCR register bit field */
union {
volatile uint32_t MCR;
volatile struct {
unsigned rsvd0 : 1; // 0
unsigned RTS : 1; // 1
unsigned OUT1 : 1; // 2
unsigned OUT2 : 1; // 3
unsigned LOOP : 1; // 4
unsigned AFE : 1; // 5
unsigned rsvd8 : 26; // 31:6
} MCR_bit;
}; // 0x10
/* PRU_UART_LSR register bit field */
union {
volatile uint32_t LSR;
volatile struct {
unsigned DR : 1; // 0
unsigned OE : 1; // 1
unsigned PE : 1; // 2
unsigned FE : 1; // 3
unsigned BI : 1; // 4
unsigned THRE : 1; // 5
unsigned TEMT : 1; // 6
unsigned RXFIFOE : 1; // 7
unsigned rsvd8 : 24; // 31:8
} LSR_bit;
}; // 0x14
/* PRU_UART_MSR register bit field */
union {
volatile uint32_t MSR;
volatile struct {
unsigned DCTS : 1; // 0
unsigned DDSR : 1; // 1
unsigned TERI : 1; // 2
unsigned DCD : 1; // 3
unsigned CTS : 1; // 4
unsigned DSR : 1; // 5
unsigned RI : 1; // 6
unsigned CD : 1; // 7
unsigned rsvd8 : 24; // 31:8
} MSR_bit;
}; // 0x18
/* PRU_UART_SCR register bit field */
union {
volatile uint32_t SCR;
volatile struct {
unsigned SCR : 8; // 7:0
unsigned rsvd8 : 24; // 31:8
} SCR_bit;
}; // 0x1C
/* PRU_UART_DLL register bit field */
union {
volatile uint32_t DLL;
volatile struct {
unsigned DLL : 8; // 7:0
unsigned rsvd8 : 24; // 31:8
} DLL_bit;
}; // 0x20
/* PRU_UART_DLH register bit field */
union {
volatile uint32_t DLH;
volatile struct {
unsigned DLH : 8; // 7:0
unsigned rsvd8 : 24; // 31:8
} DLH_bit;
}; // 0x24
/* PRU_UART_REVID1 register bit field */
union {
volatile uint32_t REVID1;
volatile struct {
unsigned REVID1 : 32; // 31:0
} REVID1_bit;
}; // 0x28
/* PRU_UART_REVID2 register bit field */
union {
volatile uint32_t REVID2;
volatile struct {
unsigned REVID2 : 8; // 7:0
unsigned rsvd8 : 24; // 31:8
} REVID2_bit;
}; // 0x2C
/* PRU_UART_PWREMU_MGMT register bit field */
union {
volatile uint32_t PWREMU_MGMT;
volatile struct {
unsigned FREE : 1; // 0
unsigned rsvd1 : 12; // 12:1
unsigned URRST : 1; // 13
unsigned UTRST : 1; // 14
unsigned rsvd15 : 17; // 31:15
} PWREMU_MGMT_bit;
}; // 0x30
/* PRU_UART_MDR register bit field */
union {
volatile uint32_t MDR;
volatile struct {
unsigned OSM_SEL : 1; // 0
unsigned rsvd1 : 31; // 31:1
} MDR_bit;
}; // 0x34
} pruUart;
volatile __far pruUart CT_UART __attribute__((cregister("PRU_UART", near), peripheral));
#endif /* _PRU_UART_H_ */
+210
View File
@@ -0,0 +1,210 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SYS_MAILBOX_H_
#define _SYS_MAILBOX_H_
/* SYS_MAILBOX register set */
typedef struct {
/* SYS_MAILBOX_REVISION register bit field */
union {
volatile uint32_t REVISION;
volatile struct {
unsigned MINOR : 6; //5:0
unsigned CUSTOM : 2; //7:6
unsigned MAJOR : 3; //10:8
unsigned RTL : 5; //15:11
unsigned FUNC : 12; //27:16
unsigned rsvd28 : 2; //29:28
unsigned SCHEME : 2; //31:30
} REVISION_bit;
}; // 0x0
uint32_t rsvd4[3]; // 0x4 - 0xC
/* SYS_MAILBOX_SYSCONFIG register bit field */
union {
volatile uint32_t SYSCONFIG;
volatile struct {
unsigned SOFTRESET : 1; //0
unsigned rsvd : 1; //1
unsigned SLIDLEMODE : 2; //3:2
unsigned rsvd1 : 28; //31:4
} SYSCONFIG_bit;
}; // 0x10
uint32_t rsvd14[11]; // 0x14 - 0x3C
/* SYS_MAILBOX_MESSAGE register bit fields */
union {
volatile uint32_t MESSAGE[8];
volatile struct {
unsigned MESSAGE : 32; //31:0
} MESSAGE_bit[8];
}; // 0x40-0x5C
uint32_t rsvd60[8]; // 0x60 - 0x7C
/* SYS_MAILBOX_FIFOSTATUS register bit fields */
union {
volatile uint32_t FIFOSTATUS[8];
volatile struct {
unsigned FIFOFULL : 1; //0
unsigned rsvd : 31; //31:1
} FIFOSTATUS_bit[8];
}; // 0x80-0x9C
uint32_t rsvdA0[8]; // 0xA0 - 0xBC
/* SYS_MAILBOX_MSGSTATUS register bit fields */
union {
volatile uint32_t MSGSTATUS[8];
volatile struct {
unsigned NBOFMSG : 3; //2:0
unsigned rsvd : 29; //31:3
} MSGSTATUS_bit[8];
}; // 0xC0-DC
uint32_t rsvdE0[8]; // 0xE0 - 0xFC
volatile struct {
union {
volatile uint32_t STATUS_RAW;
volatile struct {
unsigned NEWMSGSTATUSMB0 : 1; //0
unsigned NOTFULLSTATUSMB0 : 1; //1
unsigned NEWMSGSTATUSMB1 : 1; //2
unsigned NOTFULLSTATUSMB1 : 1; //3
unsigned NEWMSGSTATUSMB2 : 1; //4
unsigned NOTFULLSTATUSMB2 : 1; //5
unsigned NEWMSGSTATUSMB3 : 1; //6
unsigned NOTFULLSTATUSMB3 : 1; //7
unsigned NEWMSGSTATUSMB4 : 1; //8
unsigned NOTFULLSTATUSMB4 : 1; //9
unsigned NEWMSGSTATUSMB5 : 1; //10
unsigned NOTFULLSTATUSMB5 : 1; //11
unsigned NEWMSGSTATUSMB6 : 1; //12
unsigned NOTFULLSTATUSMB6 : 1; //13
unsigned NEWMSGSTATUSMB7 : 1; //14
unsigned NOTFULLSTATUSMB7 : 1; //15
unsigned rsvd : 16; //31:16
} STATUS_RAW_bit;
};
union {
volatile uint32_t STATUS_CLR;
volatile struct {
unsigned NEWMSGSTATUSMB0 : 1; //0
unsigned NOTFULLSTATUSMB0 : 1; //1
unsigned NEWMSGSTATUSMB1 : 1; //2
unsigned NOTFULLSTATUSMB1 : 1; //3
unsigned NEWMSGSTATUSMB2 : 1; //4
unsigned NOTFULLSTATUSMB2 : 1; //5
unsigned NEWMSGSTATUSMB3 : 1; //6
unsigned NOTFULLSTATUSMB3 : 1; //7
unsigned NEWMSGSTATUSMB4 : 1; //8
unsigned NOTFULLSTATUSMB4 : 1; //9
unsigned NEWMSGSTATUSMB5 : 1; //10
unsigned NOTFULLSTATUSMB5 : 1; //11
unsigned NEWMSGSTATUSMB6 : 1; //12
unsigned NOTFULLSTATUSMB6 : 1; //13
unsigned NEWMSGSTATUSMB7 : 1; //14
unsigned NOTFULLSTATUSMB7 : 1; //15
unsigned rsvd : 16; //31:16
} STATUS_CLR_bit;
};
union {
volatile uint32_t ENABLE_SET;
volatile struct {
unsigned NEWMSGSTATUSMB0 : 1; //0
unsigned NOTFULLSTATUSMB0 : 1; //1
unsigned NEWMSGSTATUSMB1 : 1; //2
unsigned NOTFULLSTATUSMB1 : 1; //3
unsigned NEWMSGSTATUSMB2 : 1; //4
unsigned NOTFULLSTATUSMB2 : 1; //5
unsigned NEWMSGSTATUSMB3 : 1; //6
unsigned NOTFULLSTATUSMB3 : 1; //7
unsigned NEWMSGSTATUSMB4 : 1; //8
unsigned NOTFULLSTATUSMB4 : 1; //9
unsigned NEWMSGSTATUSMB5 : 1; //10
unsigned NOTFULLSTATUSMB5 : 1; //11
unsigned NEWMSGSTATUSMB6 : 1; //12
unsigned NOTFULLSTATUSMB6 : 1; //13
unsigned NEWMSGSTATUSMB7 : 1; //14
unsigned NOTFULLSTATUSMB7 : 1; //15
unsigned rsvd : 16; //31:16
} ENABLE_SET_bit;
};
union {
volatile uint32_t ENABLE_CLR;
volatile struct {
unsigned NEWMSGSTATUSMB0 : 1; //0
unsigned NOTFULLSTATUSMB0 : 1; //1
unsigned NEWMSGSTATUSMB1 : 1; //2
unsigned NOTFULLSTATUSMB1 : 1; //3
unsigned NEWMSGSTATUSMB2 : 1; //4
unsigned NOTFULLSTATUSMB2 : 1; //5
unsigned NEWMSGSTATUSMB3 : 1; //6
unsigned NOTFULLSTATUSMB3 : 1; //7
unsigned NEWMSGSTATUSMB4 : 1; //8
unsigned NOTFULLSTATUSMB4 : 1; //9
unsigned NEWMSGSTATUSMB5 : 1; //10
unsigned NOTFULLSTATUSMB5 : 1; //11
unsigned NEWMSGSTATUSMB6 : 1; //12
unsigned NOTFULLSTATUSMB6 : 1; //13
unsigned NEWMSGSTATUSMB7 : 1; //14
unsigned NOTFULLSTATUSMB7 : 1; //15
unsigned rsvd : 16; //31:16
} ENABLE_CLR_bit;
};
} IRQ[4];
} sysMailbox;
#ifdef __GNUC__
static volatile sysMailbox *__CT_MBX = (void *)0x480C8000;
#define CT_MBX (*__CT_MBX)
#else
volatile __far sysMailbox CT_MBX __attribute__((cregister("MBX0", far), peripheral));
#endif
#endif /* _SYS_MAILBOX_H_ */
+446
View File
@@ -0,0 +1,446 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SYS_PWMSS_H_
#define _SYS_PWMSS_H_
/* SYS_PWMSS register set */
typedef struct {
/***************************/
/* PWM Subsystem Registers */
/***************************/
/* SYS_PWMSS_IDVER register bit field */
union {
volatile uint32_t IDVER;
volatile struct {
unsigned Y_MINOR : 6; //5:0
unsigned CUSTOM : 2; //7:6
unsigned X_MAJOR : 3; //10:8
unsigned R_RTL : 5; //15:11
unsigned FUNC : 12; //27:16
unsigned rsvd28 : 2; //29:28
unsigned SCHEME : 2; //31:30
} IDVER_bit;
}; // 0x0
/* SYS_PWMSS_SYSCONFIG register bit field */
union {
volatile uint32_t SYSCONFIG;
volatile struct {
unsigned SOFTRESET : 1; //0
unsigned FREEEMU : 1; //1
unsigned IDLEMODE : 2; //3:2
unsigned STANDBYMODE : 2; //5:4
unsigned rsvd6 : 26; //31:6
} SYSCONFIG_bit;
}; // 0x4
/* SYS_PWMSS_CLKCONFIG register bit field */
union {
volatile uint32_t CLKCONFIG;
volatile struct {
unsigned ECAPCLK_EN : 1; //0
unsigned ECAPCLKSTOP_REQ : 1; //1
unsigned rsvd2 : 2; //3:2
unsigned EQEPCLK_EN : 1; //4
unsigned EQEPCLKSTOP_REQ : 1; //5
unsigned rsvd6 : 2; //7:6
unsigned EPWMCLK_EN : 1; //8
unsigned EPWMCLKSTOP_REQ : 1; //9
unsigned rsvd10 : 22; //31:10
} CLKCONFIG_bit;
}; // 0x8
/* SYS_PWMSS_CLKSTATUS register bit field */
union {
volatile uint32_t CLKSTATUS;
volatile struct {
unsigned ECAPCLK_EN_ACK : 1; //0
unsigned ECAPCLKSTOP_ACK : 1; //1
unsigned rsvd2 : 2; //3:2
unsigned EQEPCLK_EN_ACK : 1; //4
unsigned EQEPCLKSTOP_ACK : 1; //5
unsigned rsvd6 : 2; //7:6
unsigned EPWMCLK_EN_ACK : 1; //8
unsigned EPWMCLKSTOP_ACK : 1; //9
unsigned rsvd10 : 22; //31:10
} CLKSTATUS_bit;
}; // 0xC
uint32_t rsvd10[60]; // 0x10 - 0xFC
/*************************/
/* eCAP Module Registers */
/*************************/
/* SYS_PWMSS_ECAP_TSCTR register bit field */
union {
volatile uint32_t ECAP_TSCTR;
volatile struct {
unsigned TSCTR : 32; //31:0
} ECAP_TSCTR_bit;
}; // 0x100
/* SYS_PWMSS_ECAP_CTRPHS register bit field */
union {
volatile uint32_t ECAP_CTRPHS;
volatile struct {
unsigned CTRPHS : 32; //31:0
} ECAP_CTRPHS_bit;
}; // 0x104
/* SYS_PWMSS_ECAP_CAP1 register bit field */
union {
volatile uint32_t ECAP_CAP1;
volatile struct {
unsigned CAP1 : 32; //31:0
} ECAP_CAP1_bit;
}; // 0x108
/* SYS_PWMSS_ECAP_CAP2 register bit field */
union {
volatile uint32_t ECAP_CAP2;
volatile struct {
unsigned CAP2 : 32; //31:0
} ECAP_CAP2_bit;
}; // 0x10C
/* SYS_PWMSS_ECAP_CAP3 register bit field */
union {
volatile uint32_t ECAP_CAP3;
volatile struct {
unsigned CAP3 : 32; //31:0
} ECAP_CAP3_bit;
}; // 0x110
/* SYS_PWMSS_ECAP_CAP4 register bit field */
union {
volatile uint32_t ECAP_CAP4;
volatile struct {
unsigned CAP4 : 32; //31:0
} ECAP_CAP4_bit;
}; // 0x114
uint32_t rsvd118[4]; // 0x118 - 0x124
/* SYS_PWMSS_ECAP_ECCTL1 register bit field */
volatile uint16_t ECAP_ECCTL1; // 0x128
/* SYS_PWMSS_ECAP_ECCTL2 register bit field */
volatile uint16_t ECAP_ECCTL2; // 0x12A
/* SYS_PWMSS_ECAP_ECEINT register bit field */
volatile uint16_t ECAP_ECEINT; // 0x12C
/* SYS_PWMSS_ECAP_ECFLG register bit field */
volatile uint16_t ECAP_ECFLG; // 0x12E
/* SYS_PWMSS_ECAP_ECCLR register bit field */
volatile uint16_t ECAP_ECCLR; // 0x130
/* SYS_PWMSS_ECAP_ECFRC register bit field */
volatile uint16_t ECAP_ECFRC; // 0x132
uint32_t rsvd134[10]; // 0x134 - 0x158
/* SYS_PWMSS_ECAP_REVID register bit field */
union {
volatile uint32_t ECAP_REVID;
volatile struct {
unsigned REV : 32; //31:0
} ECAP_REVID_bit;
}; // 0x15C
uint32_t rsvd160[8]; // 0x160 - 0x17C
/*************************/
/* eQEP Module Registers */
/*************************/
/* SYS_PWMSS_EQEP_QPOSCNT register bit field */
union {
volatile uint32_t EQEP_QPOSCNT;
volatile struct {
unsigned QPOSCNT : 32; //31:0
} EQEP_QPOSCNT_bit;
}; // 0x180
/* SYS_PWMSS_EQEP_QPOSINIT register bit field */
union {
volatile uint32_t EQEP_QPOSINIT;
volatile struct {
unsigned QPOSINIT : 32; //31:0
} EQEP_QPOSINIT_bit;
}; // 0x184
/* SYS_PWMSS_EQEP_QPOSMAX register bit field */
union {
volatile uint32_t EQEP_QPOSMAX;
volatile struct {
unsigned QPOSMAX : 32; //31:0
} EQEP_QPOSMAX_bit;
}; // 0x188
/* SYS_PWMSS_EQEP_QPOSCMP register bit field */
union {
volatile uint32_t EQEP_QPOSCMP;
volatile struct {
unsigned QPOSCMP : 32; //31:0
} EQEP_QPOSCMP_bit;
}; // 0x18C
/* SYS_PWMSS_EQEP_QPOSILAT register bit field */
union {
volatile uint32_t EQEP_QPOSILAT;
volatile struct {
unsigned QPOSILAT : 32; //31:0
} EQEP_QPOSILAT_bit;
}; // 0x190
/* SYS_PWMSS_EQEP_QPOSSLAT register bit field */
union {
volatile uint32_t EQEP_QPOSSLAT;
volatile struct {
unsigned QPOSSLAT : 32; //31:0
} EQEP_QPOSSLAT_bit;
}; // 0x194
/* SYS_PWMSS_EQEP_QPOSLAT register bit field */
union {
volatile uint32_t EQEP_QPOSLAT;
volatile struct {
unsigned QPOSLAT : 32; //31:0
} EQEP_QPOSLAT_bit;
}; // 0x198
/* SYS_PWMSS_EQEP_QUTMR register bit field */
union {
volatile uint32_t EQEP_QUTMR;
volatile struct {
unsigned QUTMR : 32; //31:0
} EQEP_QUTMR_bit;
}; // 0x19C
/* SYS_PWMSS_EQEP_QUPRD register bit field */
union {
volatile uint32_t EQEP_QUPRD;
volatile struct {
unsigned QUPRD : 32; //31:0
} EQEP_QUPRD_bit;
}; // 0x1A0
/* SYS_PWMSS_EQEP_QWDTMR register bit field */
volatile uint16_t EQEP_QWDTMR; // 0x1A4
/* SYS_PWMSS_EQEP_QWDPRD register bit field */
volatile uint16_t EQEP_QWDPRD; // 0x1A6
/* SYS_PWMSS_EQEP_QDECCTL register bit field */
volatile uint16_t EQEP_QDECCTL; // 0x1A8
/* SYS_PWMSS_EQEP_QEPCTL register bit field */
volatile uint16_t EQEP_QEPCTL; // 0x1AA
/* SYS_PWMSS_EQEP_QCAPCTL register bit field */
volatile uint16_t EQEP_QCAPCTL; // 0x1AC
/* SYS_PWMSS_EQEP_QPOSCTL register bit field */
volatile uint16_t EQEP_QPOSCTL; // 0x1AE
/* SYS_PWMSS_EQEP_QEINT register bit field */
volatile uint16_t EQEP_QEINT; // 0x1B0
/* SYS_PWMSS_EQEP_QFLG register bit field */
volatile uint16_t EQEP_QFLG; // 0x1B2
/* SYS_PWMSS_EQEP_QCLR register bit field */
volatile uint16_t EQEP_QCLR; // 0x1B4
/* SYS_PWMSS_EQEP_QFRC register bit field */
volatile uint16_t EQEP_QFRC; // 0x1B6
/* SYS_PWMSS_EQEP_QEPSTS register bit field */
volatile uint16_t EQEP_QEPSTS; // 0x1B8
/* SYS_PWMSS_EQEP_QCTMR register bit field */
volatile uint16_t EQEP_QCTMR; // 0x1BA
/* SYS_PWMSS_EQEP_QCPRD register bit field */
volatile uint16_t EQEP_QCPRD; // 0x1BC
/* SYS_PWMSS_EQEP_QCTMRLAT register bit field */
volatile uint16_t EQEP_QCTMRLAT; // 0x1BE
/* SYS_PWMSS_EQEP_QCPRDLAT register bit field */
volatile uint16_t EQEP_QCPRDLAT; // 0x1C0
uint16_t rsvd1C2[1]; // 0x1C2 - 0x1C3
uint32_t rsvd1C4[6]; // 0x1C4 - 0x1D8
/* SYS_PWMSS_EQEP_REVID register bit field */
union {
volatile uint32_t EQEP_REVID;
volatile struct {
unsigned REVID : 32; //31:0
} EQEP_REVID_bit;
}; // 0x1DC
uint32_t rsvd1E0[8]; // 0x1E0 - 0x1FC
/*************************/
/* ePWM Module Registers */
/*************************/
/* SYS_PWMSS_EPWM_TBCTL register bit field */
volatile uint16_t EPWM_TBCTL; // 0x200
/* SYS_PWMSS_EPWM_TBSTS register bit field */
volatile uint16_t EPWM_TBSTS; // 0x202
/* SYS_PWMSS_EPWM_TBPHSHR register bit field */
volatile uint16_t EPWM_TBPHSHR; // 0x204
/* SYS_PWMSS_EPWM_TBPHS register bit field */
volatile uint16_t EPWM_TBPHS; // 0x206
/* SYS_PWMSS_EPWM_TBCNT register bit field */
volatile uint16_t EPWM_TBCNT; // 0x208
/* SYS_PWMSS_EPWM_TBPRD register bit field */
volatile uint16_t EPWM_TBPRD; // 0x20A
uint16_t rsvd20C[1]; // 0x20C - 0x20D
/* SYS_PWMSS_EPWM_CMPCTL register bit field */
volatile uint16_t EPWM_CMPCTL; // 0x20E
/* SYS_PWMSS_EPWM_CMPAHR register bit field */
volatile uint16_t EPWM_CMPAHR; // 0x210
/* SYS_PWMSS_EPWM_CMPA register bit field */
volatile uint16_t EPWM_CMPA; // 0x212
/* SYS_PWMSS_EPWM_CMPB register bit field */
volatile uint16_t EPWM_CMPB; // 0x214
/* SYS_PWMSS_EPWM_AQCTLA register bit field */
volatile uint16_t EPWM_AQCTLA; // 0x216
/* SYS_PWMSS_EPWM_AQCTLB register bit field */
volatile uint16_t EPWM_AQCTLB; // 0x218
/* SYS_PWMSS_EPWM_AQSFRC register bit field */
volatile uint16_t EPWM_AQSFRC; // 0x21A
/* SYS_PWMSS_EPWM_AQCSFRC register bit field */
volatile uint16_t EPWM_AQCSFRC; // 0x21C
/* SYS_PWMSS_EPWM_DBCTL register bit field */
volatile uint16_t EPWM_DBCTL; // 0x21E
/* SYS_PWMSS_EPWM_DBRED register bit field */
volatile uint16_t EPWM_DBRED; // 0x220
/* SYS_PWMSS_EPWM_DBFED register bit field */
volatile uint16_t EPWM_DBFED; // 0x222
/* SYS_PWMSS_EPWM_TZSEL register bit field */
volatile uint16_t EPWM_TZSEL; // 0x224
uint16_t rsvd226[1]; // 0x226 - 0x227
/* SYS_PWMSS_EPWM_TZCTL register bit field */
volatile uint16_t EPWM_TZCTL; // 0x228
/* SYS_PWMSS_EPWM_TZEINT register bit field */
volatile uint16_t EPWM_TZEINT; // 0x22A
/* SYS_PWMSS_EPWM_TZFLG register bit field */
volatile uint16_t EPWM_TZFLG; // 0x22C
/* SYS_PWMSS_EPWM_TZCLR register bit field */
volatile uint16_t EPWM_TZCLR; // 0x22E
/* SYS_PWMSS_EPWM_TZFRC register bit field */
volatile uint16_t EPWM_TZFRC; // 0x230
/* SYS_PWMSS_EPWM_ETSEL register bit field */
volatile uint16_t EPWM_ETSEL; // 0x232
/* SYS_PWMSS_EPWM_ETPS register bit field */
volatile uint16_t EPWM_ETPS; // 0x234
/* SYS_PWMSS_EPWM_ETFLG register bit field */
volatile uint16_t EPWM_ETFLG; // 0x236
/* SYS_PWMSS_EPWM_ETCLR register bit field */
volatile uint16_t EPWM_ETCLR; // 0x238
/* SYS_PWMSS_EPWM_ETFRC register bit field */
volatile uint16_t EPWM_ETFRC; // 0x23A
/* SYS_PWMSS_EPWM_PCCTL register bit field */
volatile uint16_t EPWM_PCCTL; // 0x23C
uint16_t rsvd23E[1]; // 0x23E - 0x23F
uint32_t rsvd240[32]; // 0x240 - 0x2BC
/* SYS_PWMSS_EPWM_HRCNGF register bit field */
volatile uint16_t EPWM_HRCNGF; // 0x2C0
} sysPwmss;
volatile __far sysPwmss PWMSS0 __attribute__((cregister("PWMSS0", far), peripheral));
volatile __far sysPwmss PWMSS1 __attribute__((cregister("PWMSS1", far), peripheral));
volatile __far sysPwmss PWMSS2 __attribute__((cregister("PWMSS2", far), peripheral));
#endif /* _SYS_PWMSS_H_ */
+268
View File
@@ -0,0 +1,268 @@
/*
* Copyright (C) 2016 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* File : pru_rpmsg.h
*
* Summary : An RPMsg interface for the PRU to use while communicating with
* the ARM host.
*
* Notes :
* - This file creates a structure (pru_rpmsg_transport) that contains
* pointers to two pru_virtqueue structures. This structure is used as the
* underlying transport layer of all RPMsg communication. Only one
* pru_rpmsg_transport structure is needed because multiple logical channels
* can use the same underlying transport.
* - This pru_rpmsg interface is meant to sit on top of the pru_virtqueue
* interface and abstract the communication even further away from the
* underlying data structures. The goal is to make the communication as
* simple as possible at the user application level.
* - The logic for the PRU side is summarized below:
*
* PRU Slave:
* - To receive buffer from the ARM host:
* pru_rpmsg_receive(*transport, *src, *dst, *data, *len);
* - To send buffer to the host:
* pru_rpmsg_send(*transport, src, dst, *data, len);
*/
#ifndef _PRU_RPMSG_H_
#define _PRU_RPMSG_H_
#include <pru_virtqueue.h>
#include <pru_virtio_ring.h>
/* Return value indicating no kick was sent */
#define PRU_RPMSG_NO_KICK 1
/* Return value indicating success */
#define PRU_RPMSG_SUCCESS 0
/* Return value indicating there were no available buffers */
#define PRU_RPMSG_NO_BUF_AVAILABLE -1
/* Return value indicating that the buffer from the virtqueue was too small */
#define PRU_RPMSG_BUF_TOO_SMALL -2
/* Return value indicating that an invalid head index was given */
#define PRU_RPMSG_INVALID_HEAD -3
/* Return value indication that an invalid event number was given */
#define PRU_RPMSG_INVALID_EVENT -4
/* Max PRU-ICSS system event number for pru_mst_intr */
#define MAX_VALID_EVENT 31
/* Min PRU-ICSS system event number for pru_mst_intr */
#define MIN_VALID_EVENT 16
/* The maximum size of the channel name and description */
#define RPMSG_NAME_SIZE 32
/* The maximum size of the buffer (including the header) */
#define RPMSG_BUF_SIZE 512
enum pru_rpmsg_ns_flags {
RPMSG_NS_CREATE = 0,
RPMSG_NS_DESTROY = 1
};
/**
* Summary : pru_rpmsg_transport is a structure that groups together the
* two pru_virtqueues that are needed for two-way communication
* with the ARM. This structure provides a logical wrapper for
* the transport layer of the application. NOTE: Multiple
* (logical) channels can be implemented on top of the same
* transport layer.
*
* Variables : virtqueue0: contains the pru_virtqueue that is used for the
* PRU->ARM communication
* virtqueue1: contains the pru_virtqueue that is used for
* the ARM->PRU communication
*/
struct pru_rpmsg_transport {
struct pru_virtqueue virtqueue0;
struct pru_virtqueue virtqueue1;
};
/**
* Summary : pru_rpmsg_init initializes the underlying transport layer
* data structures.
*
* Parameters : transport: a pointer to the transport data structure that
* contains the underlying data structures to be
* initialized
* vring0: a pointer to vring0 which is provided by the ARM
* core through the resource table
* vring1: a pointer to vring1 which is provided by the ARM
* core through the resource table
* to_arm_event: the number of the PRU-ICSS system event
* that is specified in the device tree that
* is used to 'kick' the ARM core
* from_arm_event: the number of the PRU-ICSS system event
* that is specified in the device tree
* that is used to receive 'kicks' from the
* ARM core
*
* Description : pru_rpmsg_init takes the vrings and the events provided
* through the resource table and initializes the transport
* layer. Once this function call is successful RPMsg
* channels can be created and used.
*
* Return Value : Returns PRU_RPMSG_INVALID_EVENT if the values provided
* in to_arm_event or from_arm_event are outside of the
* allowable range of events. Returns PRU_RPMSG_SUCCESS
* if the initialization is successful.
*/
int16_t pru_rpmsg_init(
struct pru_rpmsg_transport *transport,
struct fw_rsc_vdev_vring *vring0,
struct fw_rsc_vdev_vring *vring1,
uint32_t to_arm_event,
uint32_t from_arm_event
);
/**
* Summary : pru_rpmsg_receive receives a message, if available, from
* the ARM host.
*
* Parameters : transport: a pointer to the transport layer from which the
* message should be received
* src: a pointer that is populated with the source address
* where the message originated
* dst: a pointer that is populated with the destination
* address where the message was sent (can help determine
* for which channel the message is intended on the PRU)
* data: a pointer that is populated with a local data buffer
* containing the message payload
* len: a pointer that is populated with the length of the
* message payload
*
* Description : pru_rpmsg_receive uses the pru_virtqueue interface to get
* an available buffer, copy the buffer into local memory,
* add the buffer as a used buffer to the vring, and then kick
* the remote processor if necessary. The src, dst, data, and
* len pointers are populated with the information about the
* message and local buffer data if the reception is
* successful.
*
* Return Value : Returns PRU_RPMSG_NO_BUF_AVAILABLE if there is currently no
* buffer available for receive. Returns PRU_RPMSG_INVALID_HEAD
* if the head index returned for the available buffer is
* invalid. Returns PRU_RPMSG_SUCCESS if the message is
* successfully received.
*/
int16_t pru_rpmsg_receive(
struct pru_rpmsg_transport *transport,
uint16_t *src,
uint16_t *dst,
void *data,
uint16_t *len
);
/**
* Summary : pru_rpmsg_send sends a message to the ARM host using the
* virtqueues in the pru_rpmsg_transport structure. The
* source and destination address of the message are passed
* in as parameters to the function. The data to be sent and
* its length are passed in the data and len parameters.
*
* Parameters : transport: a pointer to the transport layer from which the
* message should be sent
* src: the source address where this message will originate
* dst: the destination address where the message will be sent
* data: a pointer to a local data buffer containing the
* message payload
* len: the length of the message payload
*
* Description : pru_rpmsg_send sends a message to the src parameter and
* from the dst parameter. The transport structure defines the
* underlying transport mechanism that will be used. The
* data parameter is a pointer to a local buffer that should
* be sent to the destination address and the len parameter is
* the length of that buffer.
*
* Return Value : Returns PRU_RPMSG_NO_BUF_AVAILABLE if there is currently no
* buffer available for send. Returns PRU_RPMSG_BUF_TOO_SMALL
* if the buffer from the vring is too small to hold the
* message payload being sent. Returns PRU_RPMSG_INVALID_HEAD
* if the head index returned for the send buffer is invalid.
* Returns PRU_RPMSG_SUCCESS if the message is successfully
* sent.
*/
int16_t pru_rpmsg_send(
struct pru_rpmsg_transport *transport,
uint32_t src,
uint32_t dst,
void *data,
uint16_t len
);
/**
* Summary : pru_rpmsg_channel uses an RPMsg Name Service Announcment
* to either create or destroy an RPMsg channel depending on
* the pru_rpmsg_ns_flags parameter that is specified.
*
* Parameters : flags: an enum that is used to create (RPMSG_NS_CREATE) or
* destroy (RPMSG_NS_DESTROY) an RPMsg channel
* transport: a pointer to the transport layer on which this
* Name Service Announcement will be sent
* name: the name of the channel being created or destroyed
* ******* The name of the channel is very important as
* ******* it is the method that Linux on the ARM uses
* ******* to connect a PRU firmware with a corresponding
* ******* Linux driver
* desc: the description of the RPMsg channel being created
* or destroyed
* port: the local source address of the RPMsg channel. This
* is the address where PRU messages destined for the
* ARM host will originate
*
* Description : pru_rpmsg_channel sends a message letting the ARM
* host know that a channel is to be created or destroyed. If
* a channel is to be created then this message will notify
* the name server on the ARM host to create a new channel. If
* a channel is to be destroyed this will tear down this
* logical channel of communication between the PRU and the
* ARM host.
*
* Return Value : Returns PRU_RPMSG_NO_BUF_AVAILABLE if there is currently no
* buffer available for send. Returns PRU_RPMSG_BUF_TOO_SMALL
* if the buffer from the vring is too small to hold the
* message payload being sent. Returns PRU_RPMSG_INVALID_HEAD
* if the head index returned for the send buffer is invalid.
* Returns PRU_RPMSG_SUCCESS if the message is successfully
* sent.
*/
int16_t pru_rpmsg_channel(
enum pru_rpmsg_ns_flags flags,
struct pru_rpmsg_transport *transport,
char *name,
char *desc,
int32_t port
);
#endif /* _PRU_RPMSG_H_ */
+83
View File
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PRU_TYPES_H_
#define _PRU_TYPES_H_
/* Custom Resource info: Must match drivers/remoteproc/pru_rproc.h */
#define TYPE_PRU_INTS 1
/**
* struct ch_map - sysevts-to-channel mapping
*
* @evt: the number of the sysevt
* @ch: channel number assigned to a given @sysevt
*
* PRU system events are mapped to channels, and these channels are mapped to
* hosts. Events can be mapped to channels in a one-to-one or many-to-one ratio
* (multiple events per channel), and channels can be mapped to hosts in a
* one-to-one or many-to-one ratio (multiple events per channel).
*
* @evt is the number of the sysevt, and @ch is the number of the channel to be
* mapped.
*/
struct ch_map {
uint8_t evt;
uint8_t ch;
};
/**
* struct fw_rsc_custom_ints - custom resource to define PRU interrupts
* @version: revision number of the custom ints type
* @channel_host: assignment of PRU channels to hosts
* @num_evts: device address of INTC
* @event_channel: mapping of sysevts to channels
*
* PRU system events are mapped to channels, and these channels are mapped to
* hosts. Events can be mapped to channels in a one-to-one or many-to-one ratio
* (multiple events per channel), and channels can be mapped to hosts in a
* one-to-one or many-to-one ratio (multiple events per channel).
*
* @da is the device address of the interrupt controller, @channel_map is
* used to specify to which channel, if any, an event is mapped, and @host_map
* specifies to which host, if any, a channel is mapped.
*/
struct fw_rsc_custom_ints {
uint16_t version;
uint8_t channel_host[10];
uint32_t num_evts;
struct ch_map *event_channel;
};
#endif /* _PRU_TYPES_H_ */
+42
View File
@@ -0,0 +1,42 @@
#ifndef _LINUX_VIRTIO_IDS_H
#define _LINUX_VIRTIO_IDS_H
/*
* Virtio IDs
*
* This header is BSD licensed so anyone can use the definitions to implement
* compatible drivers/servers.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of IBM nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. */
#define VIRTIO_ID_NET 1 /* virtio net */
#define VIRTIO_ID_BLOCK 2 /* virtio block */
#define VIRTIO_ID_CONSOLE 3 /* virtio console */
#define VIRTIO_ID_RNG 4 /* virtio rng */
#define VIRTIO_ID_BALLOON 5 /* virtio balloon */
#define VIRTIO_ID_RPMSG 7 /* virtio remote processor messaging */
#define VIRTIO_ID_SCSI 8 /* virtio scsi */
#define VIRTIO_ID_9P 9 /* 9p virtio console */
#define VIRTIO_ID_RPROC_SERIAL 11 /* virtio remoteproc serial link */
#endif /* _LINUX_VIRTIO_IDS_H */
+163
View File
@@ -0,0 +1,163 @@
#ifndef _UAPI_LINUX_VIRTIO_RING_H
#define _UAPI_LINUX_VIRTIO_RING_H
/* An interface for efficient virtio implementation, currently for use by KVM
* and lguest, but hopefully others soon. Do NOT change this since it will
* break existing servers and clients.
*
* This header is BSD licensed so anyone can use the definitions to implement
* compatible drivers/servers.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of IBM nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Copyright Rusty Russell IBM Corporation 2007. */
#include <stdint.h>
/* This marks a buffer as continuing via the next field. */
#define VRING_DESC_F_NEXT 1
/* This marks a buffer as write-only (otherwise read-only). */
#define VRING_DESC_F_WRITE 2
/* This means the buffer contains a list of buffer descriptors. */
#define VRING_DESC_F_INDIRECT 4
/* The Host uses this in used->flags to advise the Guest: don't kick me when
* you add a buffer. It's unreliable, so it's simply an optimization. Guest
* will still kick if it's out of buffers. */
#define VRING_USED_F_NO_NOTIFY 1
/* The Guest uses this in avail->flags to advise the Host: don't interrupt me
* when you consume a buffer. It's unreliable, so it's simply an
* optimization. */
#define VRING_AVAIL_F_NO_INTERRUPT 1
/* We support indirect buffer descriptors */
#define VIRTIO_RING_F_INDIRECT_DESC 28
/* The Guest publishes the used index for which it expects an interrupt
* at the end of the avail ring. Host should ignore the avail->flags field. */
/* The Host publishes the avail index for which it expects a kick
* at the end of the used ring. Guest should ignore the used->flags field. */
#define VIRTIO_RING_F_EVENT_IDX 29
/* Virtio ring descriptors: 16 bytes. These can chain together via "next". */
struct vring_desc {
/* Address (guest-physical). */
uint64_t addr;
/* Length. */
uint32_t len;
/* The flags as indicated above. */
uint16_t flags;
/* We chain unused descriptors via this, too */
uint16_t next;
};
struct vring_avail {
uint16_t flags;
uint16_t idx;
uint16_t ring[];
};
/* u32 is used here for ids for padding reasons. */
struct vring_used_elem {
/* Index of start of used descriptor chain. */
uint32_t id;
/* Total length of the descriptor chain which was used (written to) */
uint32_t len;
};
struct vring_used {
uint16_t flags;
uint16_t idx;
struct vring_used_elem ring[];
};
struct vring {
uint32_t num;
struct vring_desc *desc;
struct vring_avail *avail;
struct vring_used *used;
};
/* The standard layout for the ring is a continuous chunk of memory which looks
* like this. We assume num is a power of 2.
*
* struct vring
* {
* // The actual descriptors (16 bytes each)
* struct vring_desc desc[num];
*
* // A ring of available descriptor heads with free-running index.
* __u16 avail_flags;
* __u16 avail_idx;
* __u16 available[num];
* __u16 used_event_idx;
*
* // Padding to the next align boundary.
* char pad[];
*
* // A ring of used descriptor heads with free-running index.
* __u16 used_flags;
* __u16 used_idx;
* struct vring_used_elem used[num];
* __u16 avail_event_idx;
* };
*/
/* We publish the used event index at the end of the available ring, and vice
* versa. They are at the end for backwards compatibility. */
#define vring_used_event(vr) ((vr)->avail->ring[(vr)->num])
#define vring_avail_event(vr) (*(__u16 *)&(vr)->used->ring[(vr)->num])
static inline void vring_init(struct vring *vr, uint32_t num, void *p,
uint64_t align)
{
vr->num = num;
vr->desc = p;
vr->avail = (void *)((char *)p + num*sizeof(struct vring_desc));
vr->used = (void *)(uintptr_t)(((uintptr_t)&vr->avail->ring[num]
+ sizeof(uint16_t) + align-1) & ~(align - 1));
}
static inline unsigned vring_size(uint16_t num, uint64_t align)
{
return ((sizeof(struct vring_desc) * num + sizeof(uint16_t) * (3 + num)
+ align - 1) & ~(align - 1))
+ sizeof(uint16_t) * 3 + sizeof(struct vring_used_elem) * num;
}
/* The following is used with USED_EVENT_IDX and AVAIL_EVENT_IDX */
/* Assuming a given event_idx value from the other size, if
* we have just incremented index from old to new_idx,
* should we trigger an event? */
static inline int vring_need_event(uint16_t event_idx, uint16_t new_idx, uint16_t old)
{
/* Note: Xen has similar logic for notification hold-off
* in include/xen/interface/io/ring.h with req_event and req_prod
* corresponding to event_idx + 1 and new_idx respectively.
* Note also that req_event and req_prod in Xen start at 1,
* event indexes in virtio start at 0. */
return (uint16_t)(new_idx - event_idx - 1) < (uint16_t)(new_idx - old);
}
#endif /* _UAPI_LINUX_VIRTIO_RING_H */
+211
View File
@@ -0,0 +1,211 @@
/*
* Copyright (C) 2016 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* File : pru_virtqueue.h
*
* Summary : A virtual queue interface to simplify vring usage.
*
* Notes :
* - This file implements the vring functions needed by the PRU core
* - The PRU core is considered the slave and the ARM core is considered the
* host
* - The ARM host always adds *available* buffers to send/receive, while the
* PRU slave always adds *used* buffers to send/receive.
* - The logic for the PRU side is summarized below:
*
* PRU Slave:
* - To receive buffer from the ARM host:
* virtqueue_getAvailBuf(vq_slave);
* >> empty data from buf <<
* virtqueue_addUsedBuf(vq_slave);
* virtqueue_kick(vq_slave);
* - To send buffer to the host:
* virtqueue_getAvailBuf(vq_host);
* >> copy data into buf <<
* virtqueue_addUsedBuf(vq_host);
* virtqueue_kick(vq_host);
*/
#ifndef _PRU_VIRTQUEUE_H_
#define _PRU_VIRTQUEUE_H_
#include <rsc_types.h>
#include <pru_virtio_ring.h>
/* Return value indicating no kick was sent */
#define PRU_VIRTQUEUE_NO_KICK 1
/* Return value indicating success */
#define PRU_VIRTQUEUE_SUCCESS 0
/* Return value indicating there were no available buffers */
#define PRU_VIRTQUEUE_NO_BUF_AVAILABLE -1
/* Return value indicating that an invalid head index was given */
#define PRU_VIRTQUEUE_INVALID_HEAD -2
/**
* Summary : pru_virtqueue is a structure that encapsulates everything
* needed for a 'virtual queue'. This structure wraps a vring
* with extra information that is needed by the application
* in order to use the vring.
*
* Variables : id: The notification ID of the vring.
* to_arm_event: The PRU-ICSS system event that signals the ARM.
* from_arm_event: The PRU-ICSS system event that the ARM uses to
* signal the PRU.
* last_avail_idx: A local running counter that is used by the
* PRU to determine whether or not a new
* available buffer has been added to the
* vring.
* vring: The underlying virtio structure that is being used
* to pass buffers back and forth between the ARM and
* PRU. See pru_virtio_ring.h.
*/
struct pru_virtqueue {
uint32_t id;
uint32_t to_arm_event;
uint32_t from_arm_event;
uint16_t last_avail_idx;
struct vring vring;
};
/**
* Summary : pru_virtqueue_init initializes the pru_virtqueue structure
* with values from the resource table.
*
* Parameters : vq: a pointer to a pru_virtqueue structure that will be
* initialized
* vring: a pointer to a vring that is populated and returned
* by the ARM host through the resource table (the id,
* number of descriptors, address of the vring, and
* alignment information are contained in this vring
* pointer's structure
* to_arm_event: the PRU-ICSS system event to trigger in order to
* 'kick' the ARM host when sending data
* from_arm_event: the PRU-ICSS system event to check
* for data arriving from the ARM host
*
* Description : This function initializes the pru_virtqueue (vq) with input
* values from the vring in the resource table. This function
* should be called once for each virtqueue/vring. After
* initialization the pru_virtqueue pointer, vq, should be
* passed to the other functions in this header file.
*
* Return Value : No return value.
*/
void pru_virtqueue_init(
struct pru_virtqueue *vq,
struct fw_rsc_vdev_vring *vring,
uint32_t to_arm_event,
uint32_t from_arm_event
);
/**
* Summary : pru_virtqueue_get_avail_buf - gets the next available
* buffer from the pru_virtqueue specified in vq.
*
* Parameters : vq: pointer to the pru_virtqueue from which the available
* buffer should be retrieved
* buf: pointer to be filled with the address of the available
* buffer
* len: pointer to be filled with the length of the available
* buffer
*
* Description : This function compares our last_avail_idx running counter
* against the vring.avail->idx value to see if there is a
* buffer available that we have not used. If our last
* available index running counter matches the vring.avail->idx
* value then there have been no new available buffers added
* by the host. If the two indices do not match then the host
* has added new buffers and and we can set @buf to point to
* the available buffer and @len to match the available buffers
* length. If an available buffer is found we increment out
* last_avail_idx to show that we used another buffer.
*
* Return Value : PRU_VIRTQUEUE_NO_BUF_AVAILABLE if no buffer available.
* Returns the vring.desc index of the available buffer
* otherwise.
*/
int16_t pru_virtqueue_get_avail_buf(
struct pru_virtqueue *vq,
void **buf,
uint32_t *len
);
/**
* Summary : pru_virtqueue_add_used_buf adds a used buffer to the
* pru_virtqueue specified in vq.
*
* Parameters : vq: pointer to the pru_virtqueue where the used buffer
* should be added
* head: vring.desc[] index of the used buffer
* len: length of the used buffer being added
*
* Description : This function makes sure that the head vring.desc index
* (head) is a valid index. If the index is valid, then the
* buffer is added to the used list in the vring contained by
* the pru_virtqueue (vq).
*
* Return Value : PRU_VIRTQUEUE_INVALID_HEAD if head is an invalid index for
* the vring.desc array. Returns PRU_VIRTQUEUE_SUCCESS
* otherwise.
*/
int16_t pru_virtqueue_add_used_buf(
struct pru_virtqueue *vq,
int16_t head,
uint32_t len
);
/**
* Summary : pru_virtqueue_kick sends a notification to the remote
* processor that the PRU has added a buffer to the
* pru_virtqueue.
*
* Parameters : vq: pointer to the pru_virtqueue that is to be kicked
*
* Description : This function is used by the PRU to notify the ARM host in
* two situations:
* 1. That the PRU has consumed a buffer that the ARM
* host sent through the slave pru_virtqueue
* 2. That the PRU has sent a buffer to the ARM through
* the host pru_virtqueue
* If the pru_virtqueue's VRING_AVAIL_F_NO_INTERRUPT flag is
* set then the pru does not kick the pru_virtqueue.
*
* Return Value : PRU_VIRTQUEUE_NO_KICK if the VRING_AVAIL_F_NO_INTERRUPT
* flag is set or PRU_VIRTQUEUE_SUCCESS otherwise.
*/
int16_t pru_virtqueue_kick(
struct pru_virtqueue *vq
);
#endif /* _PRU_VIRTQUEUE_H_ */
+347
View File
@@ -0,0 +1,347 @@
/*
* Copyright(c) 2011 Texas Instruments, Inc.
* Copyright(c) 2011 Google, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name Texas Instruments nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _RSC_TYPES_H_
#define _RSC_TYPES_H_
#include <stdint.h>
#include <pru_types.h>
/* Size constants must match those used on host */
#define SZ_4K (0x00001000)
#define SZ_8K (0x00002000)
/* Resource info: Must match include/linux/remoteproc.h: */
#define TYPE_CARVEOUT 0
#define TYPE_DEVMEM 1
#define TYPE_TRACE 2
#define TYPE_VDEV 3
#define TYPE_INTMEM 4
#define TYPE_CUSTOM 5
union fw_custom {
/* add custom resources here */
struct fw_rsc_custom_ints pru_ints;
/* maintain reserved as the last element */
uint32_t reserved;
};
/* Common Resource Structure Types */
/**
* struct resource_table - firmware resource table header
* @ver: version number
* @num: number of resource entries
* @reserved: reserved (must be zero)
*
* A resource table is essentially a list of system resources required
* by the remote processor. It may also include configuration entries.
* If needed, the remote processor firmware should contain this table
* as a dedicated ".resource_table" ELF section.
*
* Some resources entries are mere announcements, where the host is informed
* of specific remoteproc configuration. Other entries require the host to
* do something (e.g. allocate a system resource). Sometimes a negotiation
* is expected, where the firmware requests a resource, and once allocated,
* the host should provide back its details (e.g. address of an allocated
* memory region).
*
* The header of the resource table, as expressed by this structure,
* contains a version number (should we need to change this format in the
* future), the number of available resource entries, and their offsets
* in the table.
*
* Immediately following this header are the resource entries themselves,
* each of which begins with a resource entry header (as described below).
*/
struct resource_table {
uint32_t ver;
uint32_t num;
uint32_t reserved[2];
};
/**
* struct fw_rsc_carveout - physically contiguous memory request
* @type: type of resource
* @da: device address
* @pa: physical address
* @len: length (in bytes)
* @flags: iommu protection flags
* @reserved: reserved (must be zero)
* @name: human-readable name of the requested memory region
*
* This resource entry requests the host to allocate a physically contiguous
* memory region.
*
* These request entries should precede other firmware resource entries,
* as other entries might request placing other data objects inside
* these memory regions (e.g. data/code segments, trace resource entries, ...).
*
* Allocating memory this way helps utilizing the reserved physical memory
* (e.g. CMA) more efficiently, and also minimizes the number of TLB entries
* needed to map it (in case @rproc is using an IOMMU). Reducing the TLB
* pressure is important; it may have a substantial impact on performance.
*
* If the firmware is compiled with static addresses, then @da should specify
* the expected device address of this memory region. If @da is set to
* FW_RSC_ADDR_ANY, then the host will dynamically allocate it, and then
* overwrite @da with the dynamically allocated address.
*
* We will always use @da to negotiate the device addresses, even if it
* isn't using an iommu. In that case, though, it will obviously contain
* physical addresses.
*
* Some remote processors needs to know the allocated physical address
* even if they do use an iommu. This is needed, e.g., if they control
* hardware accelerators which access the physical memory directly (this
* is the case with OMAP4 for instance). In that case, the host will
* overwrite @pa with the dynamically allocated physical address.
* Generally we don't want to expose physical addresses if we don't have to
* (remote processors are generally _not_ trusted), so we might want to
* change this to happen _only_ when explicitly required by the hardware.
*
* @flags is used to provide IOMMU protection flags, and @name should
* (optionally) contain a human readable name of this carveout region
* (mainly for debugging purposes).
*/
struct fw_rsc_carveout {
uint32_t type;
uint32_t da;
uint32_t pa;
uint32_t len;
uint32_t flags;
uint32_t reserved;
uint8_t name[32];
};
/**
* struct fw_rsc_devmem - iommu mapping request
* @type: type of resource
* @da: device address
* @pa: physical address
* @len: length (in bytes)
* @flags: iommu protection flags
* @reserved: reserved (must be zero)
* @name: human-readable name of the requested region to be mapped
*
* This resource entry requests the host to iommu map a physically contiguous
* memory region. This is needed in case the remote processor requires
* access to certain memory-based peripherals; _never_ use it to access
* regular memory.
*
* This is obviously only needed if the remote processor is accessing memory
* via an iommu.
*
* @da should specify the required device address, @pa should specify
* the physical address we want to map, @len should specify the size of
* the mapping and @flags is the IOMMU protection flags. As always, @name may
* (optionally) contain a human readable name of this mapping (mainly for
* debugging purposes).
*
* Note: at this point we just "trust" those devmem entries to contain valid
* physical addresses, but this isn't safe and will be changed: eventually we
* want remoteproc implementations to provide us ranges of physical addresses
* the firmware is allowed to request, and not allow firmwares to request
* access to physical addresses that are outside those ranges.
*/
struct fw_rsc_devmem {
uint32_t type;
uint32_t da;
uint32_t pa;
uint32_t len;
uint32_t flags;
uint32_t reserved;
uint8_t name[32];
};
/**
* struct fw_rsc_trace - trace buffer declaration
* @type: type of resource
* @da: device address
* @len: length (in bytes)
* @reserved: reserved (must be zero)
* @name: human-readable name of the trace buffer
*
* This resource entry provides the host information about a trace buffer
* into which the remote processor will write log messages.
*
* @da specifies the device address of the buffer, @len specifies
* its size, and @name may contain a human readable name of the trace buffer.
*
* After booting the remote processor, the trace buffers are exposed to the
* user via debugfs entries (called trace0, trace1, etc..).
*/
struct fw_rsc_trace {
uint32_t type;
uint32_t da;
uint32_t len;
uint32_t reserved;
uint8_t name[32];
};
/**
* struct fw_rsc_vdev_vring - vring descriptor entry
* @da: device address
* @align: the alignment between the consumer and producer parts of the vring
* @num: num of buffers supported by this vring (must be power of two)
* @notifyid is a unique rproc-wide notify index for this vring. This notify
* index is used when kicking a remote processor, to let it know that this
* vring is triggered.
* @reserved: reserved (must be zero)
*
* This descriptor is not a resource entry by itself; it is part of the
* vdev resource type (see below).
*
* Note that @da should either contain the device address where
* the remote processor is expecting the vring, or indicate that
* dynamically allocation of the vring's device address is supported.
*/
struct fw_rsc_vdev_vring {
uint32_t da;
uint32_t align;
uint32_t num;
uint32_t notifyid;
uint32_t reserved;
};
/**
* struct fw_rsc_vdev - virtio device header
* @type: type of resource
* @id: virtio device id (as in virtio_ids.h)
* @notifyid is a unique rproc-wide notify index for this vdev. This notify
* index is used when kicking a remote processor, to let it know that the
* status/features of this vdev have changes.
* @dfeatures specifies the virtio device features supported by the firmware
* @gfeatures is a place holder used by the host to write back the
* negotiated features that are supported by both sides.
* @config_len is the size of the virtio config space of this vdev. The config
* space lies in the resource table immediate after this vdev header.
* @status is a place holder where the host will indicate its virtio progress.
* @num_of_vrings indicates how many vrings are described in this vdev header
* @reserved: reserved (must be zero)
* @vring is an array of @num_of_vrings entries of 'struct fw_rsc_vdev_vring'.
*
* This resource is a virtio device header: it provides information about
* the vdev, and is then used by the host and its peer remote processors
* to negotiate and share certain virtio properties.
*
* By providing this resource entry, the firmware essentially asks remoteproc
* to statically allocate a vdev upon registration of the rproc (dynamic vdev
* allocation is not yet supported).
*
* Note: unlike virtualization systems, the term 'host' here means
* the Linux side which is running remoteproc to control the remote
* processors. We use the name 'gfeatures' to comply with virtio's terms,
* though there isn't really any virtualized guest OS here: it's the host
* which is responsible for negotiating the final features.
* Yeah, it's a bit confusing.
*
* Note: immediately following this structure is the virtio config space for
* this vdev (which is specific to the vdev; for more info, read the virtio
* spec). the size of the config space is specified by @config_len.
*/
struct fw_rsc_vdev {
uint32_t type;
uint32_t id;
uint32_t notifyid;
uint32_t dfeatures;
uint32_t gfeatures;
uint32_t config_len;
uint8_t status;
uint8_t num_of_vrings;
uint8_t reserved[2];
struct fw_rsc_vdev_vring vring[0];
};
/**
* struct fw_rsc_intmem - internal memory publishing request
* @type: type of resource
* @da: device address
* @pa: physical address
* @len: length (in bytes)
* @reserved: reserved (must be zero)
* @name: human-readable name of the region being published
*
* This resource entry allows a remote processor to publish an internal
* memory region to the host. This resource type allows a remote processor
* to publish the whole or just a portion of certain internal memories,
* while it owns and manages any unpublished portion (eg: a shared L1
* memory that can be split configured as RAM and/or cache). This is
* primarily provided to allow a host to load code/data into internal
* memories, the memory for which is neither allocated nor required to
* be mapped into an iommu.
*
* @da should specify the required address as accessible by the device
* without going through an iommu, @pa should specify the physical address
* for the region as seen on the bus, @len should specify the size of the
* memory region. As always, @name may (optionally) contain a human readable
* name of this mapping (mainly for debugging purposes).
*
* Note: at this point we just "trust" these intmem entries to contain valid
* physical bus addresses. these are not currently intended to be managed
* as host-controlled heaps, as it is much better to do that from the remote
* processor side.
*/
struct fw_rsc_intmem {
uint32_t type;
uint32_t da;
uint32_t pa;
uint32_t len;
uint32_t reserved[2];
char name[32];
};
/**
* struct fw_rsc_custom - used for custom resource types
* @type: type of resource
* @sub_type: type of custom resource
* @rsc_size: size of @rsc (in bytes)
* @rsc: the custom resource
*
* This resource allows for custom resources specific to an architecture or
* device.
*
* @type is the generic CUSTOM type, @sub_type is the specific custom resource,
* @rsc_size is the length of @rsc (in bytes), and @rsc is the actual
* parameters. These will be interpreted by the host-side device-specific
* driver.
*/
struct fw_rsc_custom {
uint32_t type;
uint32_t sub_type;
uint32_t rsc_size;
union fw_custom rsc;
};
#endif /* _RSC_TYPES_H_ */
+18
View File
@@ -0,0 +1,18 @@
/*
* types.h - standard redefined types
*/
#ifndef _TYPES_H_
#define _TYPES_H_
typedef uint8_t __u8;
typedef uint16_t __u16;
typedef uint32_t __u32;
typedef uint64_t __u64;
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
#endif /* _TYPES_H_ */
+186
View File
@@ -0,0 +1,186 @@
/*
* Copyright (C) 2016 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* File : pru_rpmsg.c
*
* Summary : An RPMsg implementation for the PRU to use while communicating
* with the ARM host.
*
* Notes :
* - Implementaion of the interface described in "pru_rpmsg.h"
*/
#include <string.h>
#include <pru_rpmsg.h>
struct pru_rpmsg_hdr {
uint32_t src;
uint32_t dst;
uint32_t reserved;
uint16_t len;
uint16_t flags;
uint8_t data[0];
};
struct pru_rpmsg_ns_msg {
char name[RPMSG_NAME_SIZE];
char desc[RPMSG_NAME_SIZE];
uint32_t addr;
uint32_t flags;
};
int16_t pru_rpmsg_init(
struct pru_rpmsg_transport *transport,
struct fw_rsc_vdev_vring *vring0,
struct fw_rsc_vdev_vring *vring1,
uint32_t to_arm_event,
uint32_t from_arm_event
)
{
if (to_arm_event > MAX_VALID_EVENT || to_arm_event < MIN_VALID_EVENT)
return PRU_RPMSG_INVALID_EVENT;
if (from_arm_event > MAX_VALID_EVENT || from_arm_event < MIN_VALID_EVENT)
return PRU_RPMSG_INVALID_EVENT;
pru_virtqueue_init(&transport->virtqueue0, vring0, to_arm_event, from_arm_event);
pru_virtqueue_init(&transport->virtqueue1, vring1, to_arm_event, from_arm_event);
return PRU_RPMSG_SUCCESS;
}
int16_t pru_rpmsg_send(
struct pru_rpmsg_transport *transport,
uint32_t src,
uint32_t dst,
void *data,
uint16_t len
)
{
struct pru_rpmsg_hdr *msg;
uint32_t msg_len;
int16_t head;
struct pru_virtqueue *virtqueue;
/*
* The length of our payload is larger than the maximum RPMsg buffer size
* allowed
*/
if (len > (RPMSG_BUF_SIZE - sizeof(struct pru_rpmsg_hdr)))
return PRU_RPMSG_BUF_TOO_SMALL;
virtqueue = &transport->virtqueue0;
/* Get an available buffer */
head = pru_virtqueue_get_avail_buf(virtqueue, (void **)&msg, &msg_len);
if (head < 0)
return PRU_RPMSG_NO_BUF_AVAILABLE;
/* Copy local data buffer to the descriptor buffer address */
memcpy(msg->data, data, len);
msg->len = len;
msg->dst = dst;
msg->src = src;
msg->flags = 0;
msg->reserved = 0;
/* Add the used buffer */
if (pru_virtqueue_add_used_buf(virtqueue, head, msg_len) < 0)
return PRU_RPMSG_INVALID_HEAD;
/* Kick the ARM host */
pru_virtqueue_kick(virtqueue);
return PRU_RPMSG_SUCCESS;
}
int16_t pru_rpmsg_receive(
struct pru_rpmsg_transport *transport,
uint16_t *src,
uint16_t *dst,
void *data,
uint16_t *len
)
{
int16_t head;
struct pru_rpmsg_hdr *msg;
uint32_t msg_len;
struct pru_virtqueue *virtqueue;
virtqueue = &transport->virtqueue1;
/* Get an available buffer */
head = pru_virtqueue_get_avail_buf(virtqueue, (void **)&msg, &msg_len);
if (head < 0)
return PRU_RPMSG_NO_BUF_AVAILABLE;
/* Copy the message payload to the local data buffer provided */
memcpy(data, msg->data, msg->len);
*src = msg->src;
*dst = msg->dst;
*len = msg->len;
/* Add the used buffer */
if (pru_virtqueue_add_used_buf(virtqueue, head, msg_len) < 0)
return PRU_RPMSG_INVALID_HEAD;
/* Kick the ARM host */
pru_virtqueue_kick(virtqueue);
return PRU_RPMSG_SUCCESS;
}
int16_t pru_rpmsg_channel(
enum pru_rpmsg_ns_flags flags,
struct pru_rpmsg_transport *transport,
char *name,
char *desc,
int32_t port
)
{
struct pru_rpmsg_ns_msg ns_msg;
uint8_t i;
for (i = 0; i < RPMSG_NAME_SIZE; i++) {
ns_msg.name[i] = name[i];
ns_msg.desc[i] = desc[i];
}
ns_msg.addr = port;
ns_msg.flags = flags;
return pru_rpmsg_send(transport, port, 53, &ns_msg, sizeof(ns_msg));
}
+16
View File
@@ -0,0 +1,16 @@
diff --git a/lib/pru_rpmsg/include/am335x/pru_iep.h b/lib/pru_rpmsg/include/am335x/pru_iep.h
index d877ddd..064fb42 100644
--- a/lib/pru_rpmsg/include/am335x/pru_iep.h
+++ b/lib/pru_rpmsg/include/am335x/pru_iep.h
@@ -251,6 +251,11 @@ typedef struct {
} pruIep;
+#ifdef __GNUC__
+static volatile pruIntc *__CT_IEP = (void *)0x0002e000;
+#define CT_IEP (*__CT_INTC)
+#else
volatile __far pruIep CT_IEP __attribute__((cregister("PRU_IEP", far), peripheral));
+#endif
#endif /* _PRU_IEP_H_ */
+149
View File
@@ -0,0 +1,149 @@
/*
* Copyright (C) 2016 Texas Instruments Incorporated - http://www.ti.com/
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* File : pru_virtqueue.c
*
* Summary : A virtual queue implementation to simplify vring usage.
*
* Notes :
* - Implementaion of the interface described in "pru_virtqueue.h"
*/
#include <pru_virtqueue.h>
#ifndef __GNUC__
volatile register uint32_t __R31;
#else
#include <pru/io.h>
#endif
/* bit 5 is the valid strobe to generate system events with __R31 */
#define INT_ENABLE (1 << 5)
/* __R31[3:0] can generate 15-0 which maps to system events 31-16
* e.g. to generate PRU-ICSS System Event 17 (pru_mst_intr[1])
* __R31 = (INT_ENABLE | (17 - INT_OFFSET));
*/
#define INT_OFFSET 16
void pru_virtqueue_init(
struct pru_virtqueue *vq,
struct fw_rsc_vdev_vring *vring,
uint32_t to_arm_event,
uint32_t from_arm_event
)
{
vq->id = vring->notifyid;
vq->to_arm_event = to_arm_event;
vq->from_arm_event = from_arm_event;
vq->last_avail_idx = 0;
vring_init(&vq->vring, vring->num, (void*)vring->da, vring->align);
}
int16_t pru_virtqueue_get_avail_buf(
struct pru_virtqueue *vq,
void **buf,
uint32_t *len
)
{
int16_t head;
struct vring_desc desc;
struct vring_avail *avail;
avail = vq->vring.avail;
/* There's nothing available */
if (vq->last_avail_idx == avail->idx)
return PRU_VIRTQUEUE_NO_BUF_AVAILABLE;
/*
* Grab the next descriptor number the ARM host is advertising, and
* increment the last available index we've seen.
*/
head = avail->ring[vq->last_avail_idx++ & (vq->vring.num - 1)];
desc = vq->vring.desc[head];
*buf = (void *)(uint32_t)desc.addr;
*len = desc.len;
return (head);
}
int16_t pru_virtqueue_add_used_buf(
struct pru_virtqueue *vq,
int16_t head,
uint32_t len
)
{
struct vring_used_elem *used_elem;
uint32_t num;
struct vring_used *used;
num = vq->vring.num;
used = vq->vring.used;
if (head > (int)num)
return PRU_VIRTQUEUE_INVALID_HEAD;
/*
* The virtqueue's vring contains a ring of used buffers. Get a pointer to
* the next entry in that used ring.
*/
used_elem = &used->ring[used->idx++ & (num - 1)];
used_elem->id = head;
used_elem->len = len;
return PRU_VIRTQUEUE_SUCCESS;
}
int16_t pru_virtqueue_kick(
struct pru_virtqueue *vq
)
{
unsigned int r31;
/* If requested, do not kick the ARM host */
if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)
return PRU_VIRTQUEUE_NO_KICK;
/* Generate a system event to kick the ARM */
r31 = (INT_ENABLE | (vq->to_arm_event - INT_OFFSET));
#ifdef __GNUC__
write_r31(r31);
#else
__R31 = r31;
#endif
return PRU_VIRTQUEUE_SUCCESS;
}
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# Script to interact with simulavr by simulating a serial port.
#
# Copyright (C) 2015 Kevin O'Connor <kevin@koconnor.net>
+100 -37
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# Script to handle build time requests embedded in C code.
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
@@ -13,8 +13,10 @@ import msgproto
FILEHEADER = """
/* DO NOT EDIT! This is an autogenerated file. See scripts/buildcommands.py. */
#include "board/irq.h"
#include "board/pgm.h"
#include "command.h"
#include "compiler.h"
"""
def error(msg):
@@ -27,8 +29,6 @@ def error(msg):
######################################################################
def build_parser(parser, iscmd, all_param_types):
if parser.name == "#empty":
return "\n // Empty message\n .max_size=0,"
if parser.name == "#output":
comment = "Output: " + parser.msgformat
else:
@@ -52,27 +52,89 @@ def build_parser(parser, iscmd, all_param_types):
+ types.count('PT_buffer'))
out += " .num_args=%d," % (num_args,)
else:
max_size = min(msgproto.MESSAGE_MAX - msgproto.MESSAGE_MIN
, 1 + sum([t.max_length for t in parser.param_types]))
max_size = min(msgproto.MESSAGE_MAX,
(msgproto.MESSAGE_MIN + 1
+ sum([t.max_length for t in parser.param_types])))
out += " .max_size=%d," % (max_size,)
return out
def build_parsers(parsers, msg_to_id, all_param_types):
pcode = []
for msgname, msg in parsers:
def build_encoders(encoders, msg_to_id, all_param_types):
encoder_defs = []
output_code = []
encoder_code = []
did_output = {}
for msgname, msg in encoders:
msgid = msg_to_id[msg]
if msgid in did_output:
continue
s = msg
did_output[msgid] = True
code = (' if (__builtin_strcmp(str, "%s") == 0)\n'
' return &command_encoder_%s;\n' % (s, msgid))
if msgname is None:
parser = msgproto.OutputFormat(msgid, msg)
output_code.append(code)
else:
parser = msgproto.MessageFormat(msgid, msg)
encoder_code.append(code)
parsercode = build_parser(parser, 0, all_param_types)
pcode.append("{%s\n}, " % (parsercode,))
encoder_defs.append(
"const struct command_encoder command_encoder_%s PROGMEM = {"
" %s\n};\n" % (
msgid, parsercode))
fmt = """
const struct command_encoder command_encoders[] PROGMEM = {
%s
};
const __always_inline struct command_encoder *
ctr_lookup_encoder(const char *str)
{
%s
return NULL;
}
const __always_inline struct command_encoder *
ctr_lookup_output(const char *str)
{
%s
return NULL;
}
"""
return fmt % ("".join(pcode).strip(),)
return fmt % ("".join(encoder_defs).strip(), "".join(encoder_code).strip(),
"".join(output_code).strip())
STATIC_STRING_MIN = 2
def build_static_strings(static_strings):
code = []
for i, s in enumerate(static_strings):
code.append(' if (__builtin_strcmp(str, "%s") == 0)\n'
' return %d;\n' % (s, i + STATIC_STRING_MIN))
fmt = """
uint8_t __always_inline
ctr_lookup_static_string(const char *str)
{
%s
return 0xff;
}
"""
return fmt % ("".join(code).strip(),)
def build_call_lists(call_lists):
code = []
for funcname, funcs in call_lists.items():
func_code = [' extern void %s(void);\n %s();' % (f, f)
for f in funcs]
if funcname == 'ctr_run_taskfuncs':
func_code = [' irq_poll();\n' + fc for fc in func_code]
fmt = """
void
%s(void)
{
%s
}
"""
code.append(fmt % (funcname, "\n".join(func_code).strip()))
return "".join(code)
def build_param_types(all_param_types):
sorted_param_types = sorted([(i, a) for a, i in all_param_types.items()])
@@ -88,37 +150,31 @@ def build_param_types(all_param_types):
def build_commands(cmd_by_id, messages_by_name, all_param_types):
max_cmd_msgid = max(cmd_by_id.keys())
index = []
parsers = []
externs = {}
for msgid in range(max_cmd_msgid+1):
if msgid not in cmd_by_id:
index.append(" 0,")
index.append(" {\n},")
continue
funcname, flags, msgname = cmd_by_id[msgid]
msg = messages_by_name[msgname]
externs[funcname] = 1
parsername = 'parser_%s' % (funcname,)
index.append(" &%s," % (parsername,))
parser = msgproto.MessageFormat(msgid, msg)
parsercode = build_parser(parser, 1, all_param_types)
parsers.append("const struct command_parser %s PROGMEM = {"
" %s\n .flags=%s,\n .func=%s\n};" % (
parsername, parsercode, flags, funcname))
index = "\n".join(index)
index.append(" {%s\n .flags=%s,\n .func=%s\n}," % (
parsercode, flags, funcname))
index = "".join(index).strip()
externs = "\n".join(["extern void "+funcname+"(uint32_t*);"
for funcname in sorted(externs)])
fmt = """
%s
%s
const struct command_parser * const command_index[] PROGMEM = {
const struct command_parser command_index[] PROGMEM = {
%s
};
const uint8_t command_index_size PROGMEM = ARRAY_SIZE(command_index);
"""
return fmt % (externs, '\n'.join(parsers), index)
return fmt % (externs, index)
######################################################################
@@ -133,7 +189,8 @@ def build_identify(cmd_by_id, msg_to_id, responses, static_strings
data['messages'] = messages
data['commands'] = sorted(cmd_by_id.keys())
data['responses'] = sorted(responses)
data['static_strings'] = static_strings
data['static_strings'] = { i + STATIC_STRING_MIN: static_strings[i]
for i in range(len(static_strings)) }
data['config'] = constants
data['version'] = version
@@ -150,7 +207,8 @@ const uint8_t command_identify_data[] PROGMEM = {%s
};
// Identify size = %d (%d uncompressed)
const uint32_t command_identify_size PROGMEM = ARRAY_SIZE(command_identify_data);
const uint32_t command_identify_size PROGMEM
= ARRAY_SIZE(command_identify_data);
"""
return data, fmt % (''.join(out), len(zdata), len(data))
@@ -222,9 +280,10 @@ def main():
commands = {}
messages_by_name = dict((m.split()[0], m)
for m in msgproto.DefaultMessages.values())
parsers = []
encoders = []
static_strings = []
constants = {}
call_lists = {'ctr_run_initfuncs': []}
# Parse request file
f = open(incmdfile, 'rb')
data = f.read()
@@ -246,18 +305,15 @@ def main():
if m is not None and m != msg:
error("Conflicting definition for command '%s'" % msgname)
messages_by_name[msgname] = msg
elif cmd == '_DECL_PARSER':
if len(parts) == 1:
msgname = msg = "#empty"
else:
msgname = parts[1]
elif cmd == '_DECL_ENCODER':
msgname = parts[1]
m = messages_by_name.get(msgname)
if m is not None and m != msg:
error("Conflicting definition for message '%s'" % msgname)
messages_by_name[msgname] = msg
parsers.append((msgname, msg))
encoders.append((msgname, msg))
elif cmd == '_DECL_OUTPUT':
parsers.append((None, msg))
encoders.append((None, msg))
elif cmd == '_DECL_STATIC_STR':
static_strings.append(req[17:])
elif cmd == '_DECL_CONSTANT':
@@ -268,19 +324,25 @@ def main():
if name in constants and constants[name] != value:
error("Conflicting definition for constant '%s'" % name)
constants[name] = value
elif cmd == '_DECL_CALLLIST':
funcname, callname = parts[1:]
cl = call_lists.setdefault(funcname, [])
cl.append(callname)
else:
error("Unknown build time command '%s'" % cmd)
# Create unique ids for each message type
msgid = max(msgproto.DefaultMessages.keys())
msg_to_id = dict((m, i) for i, m in msgproto.DefaultMessages.items())
for msgname in commands.keys() + [m for n, m in parsers]:
for msgname in commands.keys() + [m for n, m in encoders]:
msg = messages_by_name.get(msgname, msgname)
if msg not in msg_to_id:
msgid += 1
msg_to_id[msg] = msgid
# Create message definitions
all_param_types = {}
parsercode = build_parsers(parsers, msg_to_id, all_param_types)
parsercode = build_encoders(encoders, msg_to_id, all_param_types)
static_strings_code = build_static_strings(static_strings)
call_lists_code = build_call_lists(call_lists)
# Create command definitions
cmd_by_id = dict((msg_to_id[messages_by_name.get(msgname, msgname)], cmd)
for msgname, cmd in commands.items())
@@ -295,7 +357,8 @@ def main():
, static_strings, constants, version)
# Write output
f = open(outcfile, 'wb')
f.write(FILEHEADER + paramcode + parsercode + cmdcode + icode)
f.write(FILEHEADER + call_lists_code + static_strings_code
+ paramcode + parsercode + cmdcode + icode)
f.close()
# Write data dictionary
+21 -19
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# Script that tries to find how much stack space each function in an
# object is using.
#
@@ -135,8 +135,7 @@ def main():
continue
m = re_asm.match(line)
if m is None:
if funcaddr not in datalines:
datalines[funcaddr] = line.split()
datalines.setdefault(funcaddr, []).append(line)
#print("other", repr(line))
continue
insn = m.group('insn')
@@ -171,10 +170,10 @@ def main():
ref = m.group('ref')
if '+' in ref:
# Inter-function jump.
pass
continue
elif insn.startswith('ld') or insn.startswith('st'):
# memory access
pass
continue
elif insn in ('rjmp', 'jmp', 'brne', 'brcs'):
# Tail call
cur.noteCall(insnaddr, calladdr, 0)
@@ -191,22 +190,25 @@ def main():
for info in funcs.values():
funcnameroot = info.funcname.split('.')[0]
funcsbyname[funcnameroot] = info
mainfunc = funcsbyname.get('sched_main')
cmdfunc = funcsbyname.get('command_task')
cmdfunc = funcsbyname.get('sched_main')
command_index = funcsbyname.get('command_index')
if command_index is not None and cmdfunc is not None:
for line in datalines[command_index.funcaddr]:
parts = line.split()
if len(parts) < 9:
continue
calladdr = int(parts[8]+parts[7], 16) * 2
numparams = int(parts[2], 16)
stackusage = cmdfunc.basic_stack_usage + 2 + numparams * 4
cmdfunc.noteCall(0, calladdr, stackusage)
if len(parts) < 17:
continue
calladdr = int(parts[16]+parts[15], 16) * 2
numparams = int(parts[10], 16)
stackusage = cmdfunc.basic_stack_usage + 2 + numparams * 4
cmdfunc.noteCall(0, calladdr, stackusage)
eventfunc = funcsbyname.get('__vector_13', funcsbyname.get('__vector_17'))
for funcnameroot, info in funcsbyname.items():
if (funcnameroot.startswith('_DECL_taskfuncs_')
or funcnameroot.startswith('_DECL_initfuncs_')
or funcnameroot.startswith('_DECL_shutdownfuncs_')):
funcname = funcnameroot[funcnameroot.index('_', 7)+1:]
f = funcsbyname[funcname]
mainfunc.noteCall(0, f.funcaddr, mainfunc.basic_stack_usage + 2)
if funcnameroot.startswith('parser_'):
f = funcsbyname.get(funcnameroot[7:])
if f is not None:
numparams = int(datalines[info.funcaddr][2], 16)
stackusage = cmdfunc.basic_stack_usage + 2 + numparams * 4
cmdfunc.noteCall(0, f.funcaddr, stackusage)
if funcnameroot.endswith('_event') and eventfunc is not None:
eventfunc.noteCall(0, info.funcaddr, eventfunc.basic_stack_usage + 2)
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# This script installs the Linux MCU code to /usr/local/bin/
if [ "$EUID" -ne 0 ]; then
echo "This script must be run as root"
exit -1
fi
set -e
# Install new micro-controller code
echo "Installing mirco-controller code to /usr/local/bin/"
rm -f /usr/local/bin/klipper_mcu
cp out/klipper.elf /usr/local/bin/klipper_mcu
sync
# Restart (if system install script present)
if [ -f /etc/init.d/klipper_pru ]; then
echo "Attempting host MCU restart..."
service klipper_pru restart
fi
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# This script installs the PRU firmware on a beaglebone machine.
if [ "$EUID" -ne 0 ]; then
echo "This script must be run as root"
exit -1
fi
set -e
# Install new firmware
echo "Installing firmware to /lib/firmware/"
cp out/pru0.elf /lib/firmware/am335x-pru0-fw
cp out/pru1.elf /lib/firmware/am335x-pru1-fw
sync
# Restart (if system install script present)
if [ -f /etc/init.d/klipper_pru ]; then
echo "Attempting PRU restart..."
service klipper_pru restart
fi
+12 -4
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# Script to parse a logging file, extract the stats, and graph them
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
@@ -9,6 +9,8 @@ import matplotlib.pyplot as plt, matplotlib.dates as mdates
MAXBANDWIDTH=25000.
MAXBUFFER=2.
STATS_INTERVAL=5.
TASK_MAX=0.0025
def parse_log(logname):
f = open(logname, 'rb')
@@ -48,7 +50,7 @@ def find_print_restarts(data):
sample_resets[st] = 1
return sample_resets
def plot_mcu(data, maxbw, outname):
def plot_mcu(data, maxbw, outname, graph_awake=False):
# Generate data for plot
basetime = lasttime = data[0]['#sampletime']
lastbw = float(data[0]['bytes_write']) + float(data[0]['bytes_retransmit'])
@@ -56,6 +58,7 @@ def plot_mcu(data, maxbw, outname):
times = []
bwdeltas = []
loads = []
awake = []
hostbuffers = []
for d in data:
st = d['#sampletime']
@@ -78,7 +81,8 @@ def plot_mcu(data, maxbw, outname):
hostbuffers.append(hb)
times.append(datetime.datetime.utcfromtimestamp(st))
bwdeltas.append(100. * (bw - lastbw) / (maxbw * timedelta))
loads.append(100. * load / .001)
loads.append(100. * load / TASK_MAX)
awake.append(100. * float(d.get('mcu_awake', 0.)) / STATS_INTERVAL)
lasttime = st
lastbw = bw
@@ -87,6 +91,8 @@ def plot_mcu(data, maxbw, outname):
ax1.set_title("MCU bandwidth and load utilization")
ax1.set_xlabel('Time')
ax1.set_ylabel('Usage (%)')
if graph_awake:
ax1.plot_date(times, awake, 'b', label='Awake time')
ax1.plot_date(times, bwdeltas, 'g', label='Bandwidth')
ax1.plot_date(times, loads, 'r', label='MCU load')
ax1.plot_date(times, hostbuffers, 'c', label='Host buffer')
@@ -99,6 +105,8 @@ def plot_mcu(data, maxbw, outname):
def main():
usage = "%prog [options] <logfile> <outname>"
opts = optparse.OptionParser(usage)
opts.add_option("-a", "--awake", action="store_true"
, help="graph mcu awake time")
options, args = opts.parse_args()
if len(args) != 2:
opts.error("Incorrect number of arguments")
@@ -106,7 +114,7 @@ def main():
data = parse_log(logname)
if not data:
return
plot_mcu(data, MAXBANDWIDTH, outname)
plot_mcu(data, MAXBANDWIDTH, outname, graph_awake=options.awake)
if __name__ == '__main__':
main()
+73
View File
@@ -0,0 +1,73 @@
#!/bin/bash
# This script installs Klipper on a Beaglebone running Debian Jessie
# for use with its PRU micro-controller.
# Step 1: Do main install
install_main()
{
# Run the octopi script - raspbian is close enough to debian for
# this to work.
${SRCDIR}/scripts/install-octopi.sh
}
# Step 2: Install additional system packages
install_packages()
{
# Install desired packages
PKGLIST="gcc-pru"
report_status "Installing beaglebone packages..."
sudo apt-get install --yes ${PKGLIST}
}
# Step 3: Install startup script
install_script()
{
report_status "Installing pru start script..."
sudo cp "${SRCDIR}/scripts/klipper-pru-start.sh" /etc/init.d/klipper_pru
sudo update-rc.d klipper_pru defaults
}
# Step 4: Install pru udev rule
install_udev()
{
report_status "Installing pru udev rule..."
sudo /bin/sh -c "cat > /etc/udev/rules.d/pru.rules" <<EOF
KERNEL=="rpmsg_pru30", GROUP="tty", MODE="0660"
EOF
}
# Step 5: Add user to tty group
install_groups()
{
report_status "Adding $USER to tty group..."
sudo adduser $USER tty
}
# Helper functions
report_status()
{
echo -e "\n\n###### $1"
}
verify_ready()
{
if [ "$EUID" -eq 0 ]; then
echo "This script must not run as root"
exit -1
fi
}
# Force script to exit if an error occurs
set -e
# Find SRCDIR from the pathname of this script
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
# Run installation steps defined above
verify_ready
install_main
install_packages
install_script
install_udev
install_groups
+1 -1
View File
@@ -8,7 +8,7 @@ PYTHONDIR="${HOME}/klippy-env"
install_packages()
{
# Packages for python cffi
PKGLIST="libffi-dev"
PKGLIST="python-virtualenv libffi-dev"
# kconfig requirements
PKGLIST="${PKGLIST} libncurses-dev"
# hub-ctrl
+117
View File
@@ -0,0 +1,117 @@
#!/bin/sh
# System startup script to start the PRU firmware
### BEGIN INIT INFO
# Provides: klipper_pru
# Required-Start: $local_fs
# Required-Stop:
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: Klipper_PRU daemon
# Description: Starts the PRU for Klipper.
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
DESC="klipper_pru startup"
NAME="klipper_pru"
KLIPPER_HOST_MCU=/usr/local/bin/klipper_mcu
KLIPPER_HOST_ARGS="-w -r"
PIDFILE=/var/run/klipper_mcu.pid
. /lib/lsb/init-functions
pru_stop()
{
# Shutdown existing Klipper instance (if applicable). The goal is to
# put the GPIO pins in a safe state.
if [ -c /dev/rpmsg_pru30 ]; then
log_daemon_msg "Attempting to shutdown PRU..."
set -e
( echo "FORCE_SHUTDOWN" > /dev/rpmsg_pru30 ) 2> /dev/null || ( log_action_msg "Firmware busy! Please shutdown Klipper and then retry." && exit 1 )
sleep 1
( echo "FORCE_SHUTDOWN" > /dev/rpmsg_pru30 ) 2> /dev/null || ( log_action_msg "Firmware busy! Please shutdown Klipper and then retry." && exit 1 )
sleep 1
set +e
fi
log_daemon_msg "Stopping pru"
echo 4a334000.pru0 > /sys/bus/platform/drivers/pru-rproc/unbind
echo 4a338000.pru1 > /sys/bus/platform/drivers/pru-rproc/unbind
}
pru_start()
{
if [ -c /dev/rpmsg_pru30 ]; then
pru_stop
else
echo 4a334000.pru0 > /sys/bus/platform/drivers/pru-rproc/unbind
echo 4a338000.pru1 > /sys/bus/platform/drivers/pru-rproc/unbind
fi
sleep 1
log_daemon_msg "Starting pru"
echo 4a334000.pru0 > /sys/bus/platform/drivers/pru-rproc/bind
echo 4a338000.pru1 > /sys/bus/platform/drivers/pru-rproc/bind
log_daemon_msg "Loading ADC module"
echo 'BB-ADC' > /sys/devices/platform/bone_capemgr/slots
}
mcu_host_stop()
{
# Shutdown existing Klipper instance (if applicable). The goal is to
# put the GPIO pins in a safe state.
if [ -c /tmp/klipper_host_mcu ]; then
log_daemon_msg "Attempting to shutdown host mcu..."
set -e
( echo "FORCE_SHUTDOWN" > /tmp/klipper_host_mcu ) 2> /dev/null || ( log_action_msg "Firmware busy! Please shutdown Klipper and then retry." && exit 1 )
sleep 1
( echo "FORCE_SHUTDOWN" > /tmp/klipper_host_mcu ) 2> /dev/null || ( log_action_msg "Firmware busy! Please shutdown Klipper and then retry." && exit 1 )
sleep 1
set +e
fi
log_daemon_msg "Stopping klipper host mcu" $NAME
killproc -p $PIDFILE $KLIPPER_HOST_MCU
}
mcu_host_start()
{
[ -x $KLIPPER_HOST_MCU ] || return
if [ -c /tmp/klipper_host_mcu ]; then
mcu_host_stop
fi
log_daemon_msg "Starting klipper MCU" $NAME
start-stop-daemon --start --quiet --exec $KLIPPER_HOST_MCU \
--background --pidfile $PIDFILE --make-pidfile \
-- $KLIPPER_HOST_ARGS
log_end_msg $?
}
case "$1" in
start)
pru_start
mcu_host_start
;;
stop)
pru_stop
mcu_host_stop
;;
restart)
$0 stop
$0 start
;;
reload|force-reload)
log_daemon_msg "Reloading configuration not supported" $NAME
log_end_msg 1
;;
status)
status_of_proc -p $PIDFILE $KLIPPER_HOST_MCU $NAME && exit 0 || exit $?
;;
*) log_action_msg "Usage: /etc/init.d/klipper {start|stop|status|restart|reload|force-reload}"
exit 2
;;
esac
exit 0
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# Script to calculate stats for each stepper from a log of messages
#
# Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
+10
View File
@@ -8,16 +8,25 @@ choice
bool "Atmega AVR"
config MACH_SAM3X8E
bool "SAM3x8e (Arduino Due)"
config MACH_PRU
bool "Beaglebone PRU"
config MACH_LINUX
bool "Linux process"
config MACH_SIMU
bool "Host simulator"
endchoice
source "src/avr/Kconfig"
source "src/sam3x8e/Kconfig"
source "src/pru/Kconfig"
source "src/linux/Kconfig"
source "src/simulator/Kconfig"
# The HAVE_GPIO_x options allow boards to disable support for some
# commands if the hardware does not support the feature.
config HAVE_GPIO
bool
default n
config HAVE_GPIO_ADC
bool
default n
@@ -38,4 +47,5 @@ config NO_UNSTEP_DELAY
config INLINE_STEPPER_HACK
# Enables gcc to inline stepper_event() into the main timer irq handler
bool
depends on HAVE_GPIO
default y
+2 -1
View File
@@ -1,6 +1,7 @@
# Main code build rules
src-y += sched.c command.c stepper.c basecmd.c gpiocmds.c endstop.c
src-y += sched.c command.c basecmd.c debugcmds.c
src-$(CONFIG_HAVE_GPIO) += gpiocmds.c stepper.c endstop.c
src-$(CONFIG_HAVE_GPIO_ADC) += adccmds.c
src-$(CONFIG_HAVE_GPIO_SPI) += spicmds.c
src-$(CONFIG_HAVE_GPIO_HARD_PWM) += pwmcmds.c
+13 -5
View File
@@ -18,6 +18,8 @@ struct analog_in {
uint8_t state, sample_count;
};
static struct task_wake analog_wake;
static uint_fast8_t
analog_in_event(struct timer *timer)
{
@@ -41,7 +43,8 @@ analog_in_event(struct timer *timer)
return SF_RESCHEDULE;
}
if (a->value < a->min_value || a->value > a->max_value)
shutdown("adc out of range");
try_shutdown("ADC out of range");
sched_wake_task(&analog_wake);
a->next_begin_time += a->rest_time;
a->timer.waketime = a->next_begin_time;
return SF_RESCHEDULE;
@@ -80,11 +83,10 @@ DECL_COMMAND(command_query_analog_in,
"query_analog_in oid=%c clock=%u sample_ticks=%u sample_count=%c"
" rest_ticks=%u min_value=%hu max_value=%hu");
static void
void
analog_in_task(void)
{
static uint16_t next;
if (!sched_check_periodic(3, &next))
if (!sched_check_wake(&analog_wake))
return;
uint8_t oid;
struct analog_in *a;
@@ -106,13 +108,19 @@ analog_in_task(void)
}
DECL_TASK(analog_in_task);
static void
void
analog_in_shutdown(void)
{
uint8_t i;
struct analog_in *a;
foreach_oid(i, a, command_config_analog_in) {
gpio_adc_cancel_sample(a->pin);
if (a->sample_count) {
a->state = a->sample_count + 1;
a->next_begin_time += a->rest_time;
a->timer.waketime = a->next_begin_time;
sched_add_timer(&a->timer);
}
}
}
DECL_SHUTDOWN(analog_in_shutdown);
+38 -17
View File
@@ -5,6 +5,7 @@ if MACH_AVR
config AVR_SELECT
bool
default y
select HAVE_GPIO
select HAVE_GPIO_ADC
select HAVE_GPIO_SPI
select HAVE_GPIO_HARD_PWM
@@ -16,21 +17,27 @@ config BOARD_DIRECTORY
choice
prompt "Processor model"
config MACH_atmega168
bool "atmega168"
config MACH_atmega644p
bool "atmega644p"
config MACH_at90usb1286
bool "at90usb1286"
config MACH_atmega1280
bool "atmega1280"
config MACH_atmega2560
bool "atmega2560"
config MACH_atmega1280
bool "atmega1280"
config MACH_at90usb1286
bool "at90usb1286"
config MACH_atmega1284p
bool "atmega1284p"
config MACH_atmega644p
bool "atmega644p"
config MACH_atmega328
bool "atmega328"
config MACH_atmega168
bool "atmega168"
endchoice
config MCU
string
default "atmega168" if MACH_atmega168
default "atmega328" if MACH_atmega328
default "atmega1284p" if MACH_atmega1284p
default "atmega644p" if MACH_atmega644p
default "at90usb1286" if MACH_at90usb1286
default "atmega1280" if MACH_atmega1280
@@ -38,12 +45,13 @@ config MCU
choice
prompt "Processor speed"
config AVR_FREQ_8000000
bool "8Mhz"
config AVR_FREQ_16000000
bool "16Mhz"
config AVR_FREQ_20000000
bool "20Mhz"
depends on MACH_atmega168 || MACH_atmega328 || MACH_atmega644p || MACH_atmega1284p
config AVR_FREQ_16000000
bool "16Mhz"
config AVR_FREQ_8000000
bool "8Mhz"
endchoice
config CLOCK_FREQ
@@ -54,7 +62,8 @@ config CLOCK_FREQ
config CLEAR_PRESCALER
bool "Manually clear the CPU prescaler field at startup"
default n
depends on MACH_at90usb1286
default y
help
Some AVR chips ship with a "clock prescaler" that causes the
chip to run at 1/8th speed. Enable this setting to clear the
@@ -72,10 +81,10 @@ config AVR_STACK_SIZE
default 128
config AVR_WATCHDOG
bool "Support for automated reset on watchdog timeout"
bool
default y
config AVR_USBSERIAL
bool
bool "Use USB for communication (instead of serial)"
depends on MACH_at90usb1286
default y
config AVR_SERIAL
@@ -87,8 +96,20 @@ config SERIAL_BAUD
int "Baud rate for serial port"
default 250000
config SERIAL_BAUD_U2X
depends on AVR_SERIAL
bool "Use AVR Baud 2X mode"
depends on AVR_SERIAL && !SIMULAVR
bool
default y
config SIMULAVR
depends on MACH_atmega168 || MACH_atmega328 || MACH_atmega644p || MACH_atmega1284p
bool "Compile for simulavr software emulation"
default n
help
Compile the code to run on simulavr software emulation
instead of for real hardware. This disables support for "U2X
baud" mode and for the watchdog timer which are not supported
on simulavr.
If unsure, select "N".
endif
+4 -3
View File
@@ -5,16 +5,16 @@ CROSS_PREFIX=avr-
dirs-y += src/avr lib/pjrc_usb_serial
CFLAGS-y += -mmcu=$(CONFIG_MCU)
CFLAGS += -mmcu=$(CONFIG_MCU)
# Add avr source files
src-y += avr/main.c avr/timer.c avr/gpio.c avr/misc.c
src-y += avr/main.c avr/timer.c avr/gpio.c
src-$(CONFIG_AVR_WATCHDOG) += avr/watchdog.c
src-$(CONFIG_AVR_USBSERIAL) += avr/usbserial.c ../lib/pjrc_usb_serial/usb_serial.c
src-$(CONFIG_AVR_SERIAL) += avr/serial.c
# Suppress broken "misspelled signal handler" warnings on gcc 4.8.1
CFLAGS_klipper.o := $(if $(filter 4.8.1, $(shell $(CC) -dumpversion)), -w)
CFLAGS_klipper.elf := $(CFLAGS_klipper.elf) $(if $(filter 4.8.1, $(shell $(CC) -dumpversion)), -w)
# Build the additional hex output file
target-y += $(OUT)klipper.elf.hex
@@ -25,4 +25,5 @@ $(OUT)klipper.elf.hex: $(OUT)klipper.elf
flash: $(OUT)klipper.elf.hex
@echo " Flashing $(FLASH_DEVICE) via avrdude"
$(Q)if [ -z $(FLASH_DEVICE) ]; then echo "Please specify FLASH_DEVICE"; exit 1; fi
$(Q)avrdude -p$(CONFIG_MCU) -cwiring -P"$(FLASH_DEVICE)" -D -U"flash:w:$(OUT)klipper.elf.hex:i"
+14 -7
View File
@@ -126,6 +126,8 @@ static const struct gpio_pwm_info pwm_regs[] PROGMEM = {
#ifdef OCR3A
{ &OCR3A, &TCCR3A, &TCCR3B, 1<<COM3A1, 0 },
{ &OCR3B, &TCCR3A, &TCCR3B, 1<<COM3B1, 0 },
#endif
#ifdef OCR3C
{ &OCR3C, &TCCR3A, &TCCR3B, 1<<COM3C1, 0 },
#endif
#ifdef OCR4A
@@ -139,14 +141,17 @@ static const struct gpio_pwm_info pwm_regs[] PROGMEM = {
};
static const uint8_t pwm_pins[ARRAY_SIZE(pwm_regs)] PROGMEM = {
#if CONFIG_MACH_atmega168
#if CONFIG_MACH_atmega168 || CONFIG_MACH_atmega328
GPIO('D', 6), GPIO('D', 5),
GPIO('B', 1), GPIO('B', 2),
GPIO('B', 3), GPIO('D', 3),
#elif CONFIG_MACH_atmega644p
#elif CONFIG_MACH_atmega644p || CONFIG_MACH_atmega1284p
GPIO('B', 3), GPIO('B', 4),
GPIO('D', 5), GPIO('D', 4),
GPIO('D', 7), GPIO('D', 6),
# ifdef OCR3A
GPIO('B', 6), GPIO('B', 7),
# endif
#elif CONFIG_MACH_at90usb1286
GPIO('B', 7), GPIO('D', 0),
GPIO('B', 5), GPIO('B', 6), GPIO('B', 7),
@@ -162,6 +167,8 @@ static const uint8_t pwm_pins[ARRAY_SIZE(pwm_regs)] PROGMEM = {
#endif
};
DECL_CONSTANT(PWM_MAX, 255);
struct gpio_pwm
gpio_pwm_setup(uint8_t pin, uint32_t cycle_time, uint8_t val)
{
@@ -239,10 +246,10 @@ gpio_pwm_write(struct gpio_pwm g, uint8_t val)
****************************************************************/
static const uint8_t adc_pins[] PROGMEM = {
#if CONFIG_MACH_atmega168
#if CONFIG_MACH_atmega168 || CONFIG_MACH_atmega328
GPIO('C', 0), GPIO('C', 1), GPIO('C', 2), GPIO('C', 3),
GPIO('C', 4), GPIO('C', 5), GPIO('E', 0), GPIO('E', 1),
#elif CONFIG_MACH_atmega644p
#elif CONFIG_MACH_atmega644p || CONFIG_MACH_atmega1284p
GPIO('A', 0), GPIO('A', 1), GPIO('A', 2), GPIO('A', 3),
GPIO('A', 4), GPIO('A', 5), GPIO('A', 6), GPIO('A', 7),
#elif CONFIG_MACH_at90usb1286
@@ -258,7 +265,7 @@ static const uint8_t adc_pins[] PROGMEM = {
static const uint8_t ADMUX_DEFAULT = 0x40;
DECL_CONSTANT(ADC_MAX, 1024);
DECL_CONSTANT(ADC_MAX, 1023);
struct gpio_adc
gpio_adc_setup(uint8_t pin)
@@ -341,9 +348,9 @@ gpio_adc_cancel_sample(struct gpio_adc g)
* Serial Peripheral Interface (SPI) hardware
****************************************************************/
#if CONFIG_MACH_atmega168
#if CONFIG_MACH_atmega168 || CONFIG_MACH_atmega328
static const uint8_t SS = GPIO('B', 2), SCK = GPIO('B', 5), MOSI = GPIO('B', 3);
#elif CONFIG_MACH_atmega644p
#elif CONFIG_MACH_atmega644p || CONFIG_MACH_atmega1284p
static const uint8_t SS = GPIO('B', 4), SCK = GPIO('B', 7), MOSI = GPIO('B', 5);
#elif CONFIG_MACH_at90usb1286 || CONFIG_MACH_atmega1280 || CONFIG_MACH_atmega2560
static const uint8_t SS = GPIO('B', 0), SCK = GPIO('B', 1), MOSI = GPIO('B', 2);
+7
View File
@@ -28,4 +28,11 @@ static inline void irq_restore(irqstatus_t flag) {
SREG = flag;
}
static inline void irq_wait(void) {
asm("sei\n sleep\n cli" : : : "memory");
}
static inline void irq_poll(void) {
}
#endif // irq.h
+60 -1
View File
@@ -1,16 +1,75 @@
// Main starting point for AVR boards.
//
// Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <avr/io.h> // AVR_STACK_POINTER_REG
#include <util/crc16.h> // _crc_ccitt_update
#include "autoconf.h" // CONFIG_MCU
#include "board/misc.h" // dynmem_start
#include "command.h" // DECL_CONSTANT
#include "irq.h" // irq_enable
#include "sched.h" // sched_main
DECL_CONSTANT(MCU, CONFIG_MCU);
/****************************************************************
* Dynamic memory
****************************************************************/
// Return the start of memory available for dynamic allocations
void *
dynmem_start(void)
{
extern char _end;
return &_end;
}
// Return the end of memory available for dynamic allocations
void *
dynmem_end(void)
{
return (void*)ALIGN(AVR_STACK_POINTER_REG, 256) - CONFIG_AVR_STACK_SIZE;
}
/****************************************************************
* Misc functions
****************************************************************/
// Initialize the clock prescaler (if necessary)
void
prescaler_init(void)
{
if (CONFIG_AVR_CLKPR != -1 && (uint8_t)CONFIG_AVR_CLKPR != CLKPR) {
irqstatus_t flag = irq_save();
CLKPR = 0x80;
CLKPR = CONFIG_AVR_CLKPR;
irq_restore(flag);
}
}
DECL_INIT(prescaler_init);
// The "sleep" instruction should cause the processor to enter "idle mode"
void
sleep_init(void)
{
SMCR = 0x01;
}
DECL_INIT(sleep_init);
// Optimized crc16_ccitt for the avr processor
uint16_t
crc16_ccitt(char *buf, uint8_t len)
{
uint16_t crc = 0xFFFF;
while (len--)
crc = _crc_ccitt_update(crc, *buf++);
return crc;
}
// Main entry point for avr code.
int
main(void)
-37
View File
@@ -1,37 +0,0 @@
// AVR miscellaneous platform code
//
// Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <avr/io.h> // AVR_STACK_POINTER_REG
#include <stdlib.h> // __malloc_heap_end
#include <util/crc16.h> // _crc_ccitt_update
#include "autoconf.h" // CONFIG_AVR_STACK_SIZE
#include "board/misc.h" // alloc_maxsize
#include "compiler.h" // ALIGN
// Optimized crc16_ccitt for the avr processor
uint16_t
crc16_ccitt(char *buf, uint8_t len)
{
uint16_t crc = 0xFFFF;
while (len--)
crc = _crc_ccitt_update(crc, *buf++);
return crc;
}
// Return the maximum allocation size that can succeed up to 'reqsize'
size_t
alloc_maxsize(size_t reqsize)
{
uint16_t memend = ALIGN(AVR_STACK_POINTER_REG, 256);
__malloc_heap_end = (void*)memend - CONFIG_AVR_STACK_SIZE;
extern char *__brkval;
int16_t maxsize = __malloc_heap_end - __brkval - 2;
if (maxsize < 0)
return 0;
if (reqsize < maxsize)
return reqsize;
return maxsize;
}
+74 -50
View File
@@ -1,6 +1,6 @@
// AVR serial port code.
//
// Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
@@ -8,10 +8,11 @@
#include <string.h> // memmove
#include "autoconf.h" // CONFIG_SERIAL_BAUD
#include "board/io.h" // readb
#include "board/misc.h" // console_get_input
#include "board/misc.h" // console_sendf
#include "command.h" // DECL_CONSTANT
#include "sched.h" // DECL_INIT
#include "irq.h" // irq_save
#include "pgm.h" // READP
#include "sched.h" // DECL_INIT
static char receive_buf[192];
static uint8_t receive_pos;
@@ -25,33 +26,47 @@ static uint8_t transmit_pos, transmit_max;
DECL_CONSTANT(SERIAL_BAUD, CONFIG_SERIAL_BAUD);
static void
// Define serial port registers on AT90USB1286
#if !defined(UCSR0A) && defined(UCSR1A)
#define UCSR0A UCSR1A
#define UCSR0B UCSR1B
#define UCSR0C UCSR1C
#define UBRR0 UBRR1
#define UDR0 UDR1
#define UCSZ01 UCSZ11
#define UCSZ00 UCSZ10
#define U2X0 U2X1
#define RXEN0 RXEN1
#define TXEN0 TXEN1
#define RXCIE0 RXCIE1
#define UDRIE0 UDRIE1
#define USART0_RX_vect USART1_RX_vect
#define USART0_UDRE_vect USART1_UDRE_vect
#endif
// Define serial port registers on atmega168 / atmega328
#if defined(USART_RX_vect)
#define USART0_RX_vect USART_RX_vect
#define USART0_UDRE_vect USART_UDRE_vect
#endif
void
serial_init(void)
{
if (CONFIG_SERIAL_BAUD_U2X) {
UCSR0A = 1<<U2X0;
UBRR0 = DIV_ROUND_CLOSEST(
CONFIG_CLOCK_FREQ, 8UL * CONFIG_SERIAL_BAUD) - 1UL;
} else {
UCSR0A = 0;
UBRR0 = DIV_ROUND_CLOSEST(
CONFIG_CLOCK_FREQ, 16UL * CONFIG_SERIAL_BAUD) - 1UL;
}
UCSR0A = CONFIG_SERIAL_BAUD_U2X ? (1<<U2X0) : 0;
uint32_t cm = CONFIG_SERIAL_BAUD_U2X ? 8 : 16;
UBRR0 = DIV_ROUND_CLOSEST(CONFIG_CLOCK_FREQ, cm * CONFIG_SERIAL_BAUD) - 1UL;
UCSR0C = (1<<UCSZ01) | (1<<UCSZ00);
UCSR0B = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0) | (1<<UDRIE0);
}
DECL_INIT(serial_init);
#ifdef USART_RX_vect
#define USART0_RX_vect USART_RX_vect
#define USART0_UDRE_vect USART_UDRE_vect
#endif
// Rx interrupt - data available to be read.
ISR(USART0_RX_vect)
{
uint8_t data = UDR0;
if (data == MESSAGE_SYNC)
sched_wake_tasks();
if (receive_pos >= sizeof(receive_buf))
// Serial overflow - ignore it as crc error will force retransmit
return;
@@ -79,16 +94,8 @@ enable_tx_irq(void)
* Console access functions
****************************************************************/
// Return a buffer (and length) containing any incoming messages
char *
console_get_input(uint8_t *plen)
{
*plen = readb(&receive_pos);
return receive_buf;
}
// Remove from the receive buffer the given number of bytes
void
static void
console_pop_input(uint8_t len)
{
uint8_t copied = 0;
@@ -99,6 +106,7 @@ console_pop_input(uint8_t len)
memmove(&receive_buf[copied], &receive_buf[copied + len]
, needcopy - copied);
copied = needcopy;
sched_wake_tasks();
}
irqstatus_t flag = irq_save();
if (rpos != readb(&receive_pos)) {
@@ -112,35 +120,51 @@ console_pop_input(uint8_t len)
}
}
// Return an output buffer that the caller may fill with transmit messages
char *
console_get_output(uint8_t len)
// Process any incoming commands
void
console_task(void)
{
uint8_t pop_count, rpos = readb(&receive_pos);
int8_t ret = command_find_block(receive_buf, rpos, &pop_count);
if (ret > 0)
command_dispatch(receive_buf, pop_count);
if (ret)
console_pop_input(pop_count);
}
DECL_TASK(console_task);
// Encode and transmit a "response" message
void
console_sendf(const struct command_encoder *ce, va_list args)
{
// Verify space for message
uint8_t tpos = readb(&transmit_pos), tmax = readb(&transmit_max);
if (tpos >= tmax) {
tpos = tmax = 0;
writeb(&transmit_max, 0);
writeb(&transmit_pos, 0);
}
if (tmax + len <= sizeof(transmit_buf))
return &transmit_buf[tmax];
if (tmax - tpos + len > sizeof(transmit_buf))
return NULL;
// Disable TX irq and move buffer
writeb(&transmit_max, 0);
tpos = readb(&transmit_pos);
tmax -= tpos;
memmove(&transmit_buf[0], &transmit_buf[tpos], tmax);
writeb(&transmit_pos, 0);
writeb(&transmit_max, tmax);
enable_tx_irq();
return &transmit_buf[tmax];
}
uint8_t max_size = READP(ce->max_size);
if (tmax + max_size > sizeof(transmit_buf)) {
if (tmax + max_size - tpos > sizeof(transmit_buf))
// Not enough space for message
return;
// Disable TX irq and move buffer
writeb(&transmit_max, 0);
tpos = readb(&transmit_pos);
tmax -= tpos;
memmove(&transmit_buf[0], &transmit_buf[tpos], tmax);
writeb(&transmit_pos, 0);
writeb(&transmit_max, tmax);
enable_tx_irq();
}
// Accept the given number of bytes added to the transmit buffer
void
console_push_output(uint8_t len)
{
writeb(&transmit_max, readb(&transmit_max) + len);
// Generate message
char *buf = &transmit_buf[tmax];
uint8_t msglen = command_encodef(buf, ce, args);
command_add_frame(buf, msglen);
// Start message transmit
writeb(&transmit_max, tmax + msglen);
enable_tx_irq();
}
+73 -65
View File
@@ -1,6 +1,6 @@
// AVR timer interrupt scheduling code.
//
// Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
@@ -9,7 +9,7 @@
#include "board/misc.h" // timer_from_us
#include "command.h" // shutdown
#include "irq.h" // irq_save
#include "sched.h" // sched_timer_kick
#include "sched.h" // sched_timer_dispatch
/****************************************************************
@@ -67,37 +67,40 @@ timer_repeat_set(uint16_t next)
{
// Timer1B is used to limit the number of timers run from a timer1A irq
OCR1B = next;
TIFR1 = 1<<OCF1B;
// This is "TIFR1 = 1<<OCF1B" - gcc handles that poorly, so it's hand coded
uint8_t dummy;
asm volatile("ldi %0, %2\n out %1, %0"
: "=d"(dummy) : "i"(&TIFR1 - 0x20), "i"(1<<OCF1B));
}
// Reset the timer - clear settings and dispatch next timer immediately
static void
// Activate timer dispatch as soon as possible
void
timer_kick(void)
{
timer_set(timer_get() + 50);
TIFR1 = 1<<OCF1A;
}
static struct timer wrap_timer;
void
timer_reset(void)
{
uint16_t now = timer_get();
timer_set(now + 50);
TIFR1 = 1<<OCF1A;
timer_repeat_set(now + 50);
sched_add_timer(&wrap_timer);
}
DECL_SHUTDOWN(timer_reset);
static void
void
timer_init(void)
{
if (CONFIG_AVR_CLKPR != -1 && (uint8_t)CONFIG_AVR_CLKPR != CLKPR) {
// Program the clock prescaler
irqstatus_t flag = irq_save();
CLKPR = 0x80;
CLKPR = CONFIG_AVR_CLKPR;
irq_restore(flag);
}
// no outputs
TCCR1A = 0;
// Normal Mode
TCCR1B = 1<<CS10;
// Setup for first irq
irqstatus_t flag = irq_save();
timer_kick();
timer_repeat_set(timer_get() + 50);
timer_reset();
TIFR1 = 1<<TOV1;
// enable interrupt
@@ -118,31 +121,45 @@ uint32_t
timer_read_time(void)
{
irqstatus_t flag = irq_save();
union u32_u calc;
calc.val = timer_get();
union u32_u calc = { .val = timer_get() };
calc.hi = timer_high;
if (TIFR1 & (1<<TOV1) && calc.lo < 0x8000)
calc.hi++;
if (unlikely(TIFR1 & (1<<TOV1))) {
irq_restore(flag);
if (calc.b1 < 0xff)
calc.hi++;
return calc.val;
}
irq_restore(flag);
return calc.val;
}
// Called by main code once every millisecond. (IRQs disabled.)
void
timer_periodic(void)
// Timer that runs every ~2ms - allows 16bit comparison optimizations
static uint_fast8_t
timer_event(struct timer *t)
{
union u32_u *nextwake = (void*)&wrap_timer.waketime;
if (TIFR1 & (1<<TOV1)) {
// Hardware timer has overflowed - update overflow counter
TIFR1 = 1<<TOV1;
timer_high++;
*nextwake = (union u32_u){ .hi = timer_high, .lo = 0x8000 };
} else {
*nextwake = (union u32_u){ .hi = timer_high + 1, .lo = 0x0000 };
}
return SF_RESCHEDULE;
}
static struct timer wrap_timer = {
.func = timer_event,
.waketime = 0x8000,
};
#define TIMER_IDLE_REPEAT_TICKS 8000
#define TIMER_REPEAT_TICKS 3000
#define TIMER_MIN_TRY_TICKS 60 // 40 ticks to exit irq; 20 ticks of progress
#define TIMER_DEFER_REPEAT_TICKS 200
#define TIMER_MIN_ENTRY_TICKS 44
#define TIMER_MIN_EXIT_TICKS 47
#define TIMER_MIN_TRY_TICKS (TIMER_MIN_ENTRY_TICKS + TIMER_MIN_EXIT_TICKS)
#define TIMER_DEFER_REPEAT_TICKS 256
// Hardware timer IRQ handler - dispatch software timers
ISR(TIMER1_COMPA_vect)
@@ -152,52 +169,43 @@ ISR(TIMER1_COMPA_vect)
// Run the next software timer
next = sched_timer_dispatch();
int16_t diff = timer_get() - next;
if (likely(diff >= 0)) {
// Another timer is pending - briefly allow irqs to fire
for (;;) {
int16_t diff = timer_get() - next;
if (likely(diff >= 0)) {
// Another timer is pending - briefly allow irqs and then run it
irq_enable();
if (unlikely(TIFR1 & (1<<OCF1B)))
goto check_defer;
irq_disable();
break;
}
if (likely(diff <= -TIMER_MIN_TRY_TICKS))
// Schedule next timer normally
goto done;
irq_enable();
if (unlikely(TIFR1 & (1<<OCF1B)))
// Too many repeat timers - must exit irq handler
goto force_defer;
goto check_defer;
irq_disable();
continue;
}
if (likely(diff <= -TIMER_MIN_TRY_TICKS))
// Schedule next timer normally
goto done;
// Next timer in very near future - wait for it to be ready
do {
irq_enable();
if (unlikely(TIFR1 & (1<<OCF1B)))
goto force_defer;
check_defer:
// Check if there are too many repeat timers
irq_disable();
diff = timer_get() - next;
} while (diff < 0);
uint16_t now = timer_get();
if ((int16_t)(next - now) < (int16_t)(-timer_from_us(1000)))
try_shutdown("Rescheduled timer in the past");
if (sched_tasks_busy()) {
timer_repeat_set(now + TIMER_REPEAT_TICKS);
next = now + TIMER_DEFER_REPEAT_TICKS;
goto done;
}
timer_repeat_set(now + TIMER_IDLE_REPEAT_TICKS);
timer_set(now);
}
}
force_defer:
// Too many repeat timers - force a pause so tasks aren't starved
irq_disable();
uint16_t now = timer_get();
if ((int16_t)(next - now) < (int16_t)(-timer_from_us(1000)))
shutdown("Rescheduled timer in the past");
timer_repeat_set(now + TIMER_REPEAT_TICKS);
next = now + TIMER_DEFER_REPEAT_TICKS;
done:
timer_set(next);
return;
}
// Periodic background task that temporarily boosts priority of
// timers. This helps prioritize timers when tasks are idling.
static void
timer_task(void)
{
irq_disable();
timer_repeat_set(timer_get() + TIMER_IDLE_REPEAT_TICKS);
irq_enable();
}
DECL_TASK(timer_task);
+35 -25
View File
@@ -1,29 +1,28 @@
// Wrappers for AVR usb serial.
//
// Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <avr/interrupt.h> // USART0_RX_vect
#include <string.h> // memmove
#include "../lib/pjrc_usb_serial/usb_serial.h"
#include "board/misc.h" // console_sendf
#include "command.h" // command_dispatch
#include "sched.h" // DECL_INIT
#define USBSERIAL_BUFFER_SIZE 64
static char receive_buf[USBSERIAL_BUFFER_SIZE];
static char receive_buf[MESSAGE_MAX];
static uint8_t receive_pos;
static char transmit_buf[USBSERIAL_BUFFER_SIZE];
static void
void
usbserial_init(void)
{
usb_init();
}
DECL_INIT(usbserial_init);
// Return a buffer (and length) containing any incoming messages
char *
console_get_input(uint8_t *plen)
// Check for new incoming data
static void
console_check_input(void)
{
for (;;) {
if (receive_pos >= sizeof(receive_buf))
@@ -33,33 +32,44 @@ console_get_input(uint8_t *plen)
break;
receive_buf[receive_pos++] = ret;
}
*plen = receive_pos;
return receive_buf;
}
// Remove from the receive buffer the given number of bytes
void
static void
console_pop_input(uint8_t len)
{
uint8_t needcopy = receive_pos - len;
if (needcopy)
if (needcopy) {
memmove(receive_buf, &receive_buf[len], needcopy);
sched_wake_tasks();
}
receive_pos = needcopy;
}
// Return an output buffer that the caller may fill with transmit messages
char *
console_get_output(uint8_t len)
{
if (len > sizeof(transmit_buf))
return NULL;
return transmit_buf;
}
// Accept the given number of bytes added to the transmit buffer
// Process any incoming commands
void
console_push_output(uint8_t len)
console_task(void)
{
usb_serial_write((void*)transmit_buf, len);
console_check_input();
uint8_t pop_count;
int8_t ret = command_find_block(receive_buf, receive_pos, &pop_count);
if (ret > 0)
command_dispatch(receive_buf, pop_count);
if (ret)
console_pop_input(pop_count);
}
DECL_TASK(console_task);
// Encode and transmit a "response" message
void
console_sendf(const struct command_encoder *ce, va_list args)
{
// Generate message
static char buf[MESSAGE_MAX];
uint8_t msglen = command_encodef(buf, ce, args);
command_add_frame(buf, msglen);
// Transmit message
usb_serial_write((void*)buf, msglen);
usb_serial_flush_output();
}
+2 -2
View File
@@ -18,7 +18,7 @@ ISR(WDT_vect)
shutdown("Watchdog timer!");
}
static void
void
watchdog_reset(void)
{
wdt_reset();
@@ -29,7 +29,7 @@ watchdog_reset(void)
}
DECL_TASK(watchdog_reset);
static void
void
watchdog_init(void)
{
// 0.5s timeout, interrupt and system reset
+74 -122
View File
@@ -1,18 +1,59 @@
// Basic infrastructure commands.
//
// Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <stdlib.h> // malloc
#include <string.h> // memset
#include "basecmd.h" // oid_lookup
#include "board/irq.h" // irq_save
#include "board/misc.h" // alloc_maxsize
#include "board/pgm.h" // READP
#include "command.h" // DECL_COMMAND
#include "sched.h" // sched_clear_shutdown
/****************************************************************
* Low level allocation
****************************************************************/
static void *alloc_end;
void
alloc_init(void)
{
alloc_end = (void*)ALIGN((size_t)dynmem_start(), __alignof__(void*));
}
DECL_INIT(alloc_init);
// Allocate an area of memory
static void *
alloc_chunk(size_t size)
{
if (alloc_end + size > dynmem_end())
shutdown("alloc_chunk failed");
void *data = alloc_end;
alloc_end += ALIGN(size, __alignof__(void*));
memset(data, 0, size);
return data;
}
// Allocate an array of chunks
static void *
alloc_chunks(size_t size, size_t count, uint16_t *avail)
{
size_t can_alloc = 0;
void *p = alloc_end, *end = dynmem_end();
while (can_alloc < count && p + size <= end)
can_alloc++, p += size;
if (!can_alloc)
shutdown("alloc_chunks failed");
void *data = alloc_chunk(p - alloc_end);
*avail = can_alloc;
return data;
}
/****************************************************************
* Move queue
****************************************************************/
@@ -66,7 +107,7 @@ move_request_size(int size)
move_item_size = size;
}
static void
void
move_reset(void)
{
if (!move_count)
@@ -86,12 +127,10 @@ DECL_SHUTDOWN(move_reset);
static void
move_finalize(void)
{
if (is_finalized())
shutdown("Already finalized");
move_request_size(sizeof(*move_free_list));
uint16_t count = alloc_maxsize(move_item_size*1024) / move_item_size;
move_list = malloc(count * move_item_size);
if (!count || !move_list)
shutdown("move queue malloc failed");
move_count = count;
move_list = alloc_chunks(move_item_size, 1024, &move_count);
move_reset();
}
@@ -115,23 +154,14 @@ oid_lookup(uint8_t oid, void *type)
return oids[oid].data;
}
static void
oid_assign(uint8_t oid, void *type, void *data)
void *
oid_alloc(uint8_t oid, void *type, uint16_t size)
{
if (oid >= oid_count || oids[oid].type || is_finalized())
shutdown("Can't assign oid");
oids[oid].type = type;
void *data = alloc_chunk(size);
oids[oid].data = data;
}
void *
oid_alloc(uint8_t oid, void *type, uint16_t size)
{
void *data = malloc(size);
if (!data)
shutdown("malloc failed");
memset(data, 0, size);
oid_assign(oid, type, data);
return data;
}
@@ -156,10 +186,7 @@ command_allocate_oids(uint32_t *args)
if (oids)
shutdown("oids already allocated");
uint8_t count = args[0];
oids = malloc(sizeof(oids[0]) * count);
if (!oids)
shutdown("malloc failed");
memset(oids, 0, sizeof(oids[0]) * count);
oids = alloc_chunk(sizeof(oids[0]) * count);
oid_count = count;
}
DECL_COMMAND(command_allocate_oids, "allocate_oids count=%c");
@@ -182,43 +209,30 @@ DECL_COMMAND_FLAGS(command_get_config, HF_IN_SHUTDOWN, "get_config");
void
command_finalize_config(uint32_t *args)
{
if (!oids || is_finalized())
shutdown("Can't finalize");
move_finalize();
config_crc = args[0];
command_get_config(NULL);
}
DECL_COMMAND(command_finalize_config, "finalize_config crc=%u");
/****************************************************************
* Group commands
****************************************************************/
static struct timer group_timer;
static uint_fast8_t
group_end_event(struct timer *timer)
{
shutdown("Missed scheduling of next event");
}
// Attempt a full manual reset of the config
void
command_start_group(uint32_t *args)
config_reset(uint32_t *args)
{
sched_del_timer(&group_timer);
group_timer.func = group_end_event;
group_timer.waketime = args[0];
sched_add_timer(&group_timer);
if (! sched_is_shutdown())
shutdown("config_reset only available when shutdown");
irq_disable();
config_crc = 0;
oid_count = 0;
oids = NULL;
move_free_list = NULL;
move_list = NULL;
move_count = move_item_size = 0;
alloc_init();
sched_timer_reset();
sched_clear_shutdown();
irq_enable();
}
DECL_COMMAND(command_start_group, "start_group clock=%u");
void
command_end_group(uint32_t *args)
{
sched_del_timer(&group_timer);
}
DECL_COMMAND(command_end_group, "end_group");
/****************************************************************
@@ -246,14 +260,13 @@ DECL_COMMAND_FLAGS(command_get_uptime, HF_IN_SHUTDOWN, "get_uptime");
#define SUMSQ_BASE 256
DECL_CONSTANT(STATS_SUMSQ_BASE, SUMSQ_BASE);
static void
stats_task(void)
void
stats_update(uint32_t start, uint32_t cur)
{
static uint32_t last, count, sumsq;
uint32_t cur = timer_read_time();
uint32_t diff = cur - last;
last = cur;
static uint32_t count, sum, sumsq;
uint32_t diff = cur - start;
count++;
sum += diff;
// Calculate sum of diff^2 - be careful of integer overflow
uint32_t nextsumsq;
if (diff <= 0xffff) {
@@ -269,73 +282,12 @@ stats_task(void)
if (timer_is_before(cur, stats_send_time + timer_from_us(5000000)))
return;
sendf("stats count=%u sum=%u sumsq=%u", count, cur - stats_send_time, sumsq);
sendf("stats count=%u sum=%u sumsq=%u", count, sum, sumsq);
if (cur < stats_send_time)
stats_send_time_high++;
stats_send_time = cur;
count = sumsq = 0;
count = sum = sumsq = 0;
}
DECL_TASK(stats_task);
/****************************************************************
* Register debug commands
****************************************************************/
void
command_debug_read8(uint32_t *args)
{
uint8_t *ptr = (void*)(size_t)args[0];
uint16_t v = *ptr;
sendf("debug_result val=%hu", v);
}
DECL_COMMAND_FLAGS(command_debug_read8, HF_IN_SHUTDOWN, "debug_read8 addr=%u");
void
command_debug_read16(uint32_t *args)
{
uint16_t *ptr = (void*)(size_t)args[0];
irqstatus_t flag = irq_save();
uint16_t v = *ptr;
irq_restore(flag);
sendf("debug_result val=%hu", v);
}
DECL_COMMAND_FLAGS(command_debug_read16, HF_IN_SHUTDOWN, "debug_read16 addr=%u");
void
command_debug_write8(uint32_t *args)
{
uint8_t *ptr = (void*)(size_t)args[0];
*ptr = args[1];
}
DECL_COMMAND_FLAGS(command_debug_write8, HF_IN_SHUTDOWN,
"debug_write8 addr=%u val=%u");
void
command_debug_write16(uint32_t *args)
{
uint16_t *ptr = (void*)(size_t)args[0];
irqstatus_t flag = irq_save();
*ptr = args[1];
irq_restore(flag);
}
DECL_COMMAND_FLAGS(command_debug_write16, HF_IN_SHUTDOWN,
"debug_write16 addr=%u val=%u");
void
command_debug_ping(uint32_t *args)
{
uint8_t len = args[0];
char *data = (void*)(size_t)args[1];
sendf("pong data=%*s", len, data);
}
DECL_COMMAND_FLAGS(command_debug_ping, HF_IN_SHUTDOWN, "debug_ping data=%*s");
void
command_debug_nop(uint32_t *args)
{
}
DECL_COMMAND_FLAGS(command_debug_nop, HF_IN_SHUTDOWN, "debug_nop data=%*s");
/****************************************************************
@@ -345,7 +297,7 @@ DECL_COMMAND_FLAGS(command_debug_nop, HF_IN_SHUTDOWN, "debug_nop data=%*s");
void
command_emergency_stop(uint32_t *args)
{
shutdown("command request");
shutdown("Command request");
}
DECL_COMMAND_FLAGS(command_emergency_stop, HF_IN_SHUTDOWN, "emergency_stop");
+2
View File
@@ -9,6 +9,8 @@ void move_request_size(int size);
void *oid_lookup(uint8_t oid, void *type);
void *oid_alloc(uint8_t oid, void *type, uint16_t size);
void *oid_next(uint8_t *i, void *type);
void stats_update(uint32_t start, uint32_t cur);
void config_reset(uint32_t *args);
#define foreach_oid(pos,data,oidtype) \
for (pos=-1; (data=oid_next(&pos, oidtype)); )
+126 -140
View File
@@ -1,29 +1,17 @@
// Code for parsing incoming commands and encoding outgoing messages
//
// Copyright (C) 2016 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2016,2017 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <stdarg.h> // va_start
#include <string.h> // memcpy
#include "board/io.h" // readb
#include "board/irq.h" // irq_poll
#include "board/misc.h" // crc16_ccitt
#include "board/pgm.h" // READP
#include "command.h" // output_P
#include "sched.h" // DECL_TASK
#define MESSAGE_MIN 5
#define MESSAGE_MAX 64
#define MESSAGE_HEADER_SIZE 2
#define MESSAGE_TRAILER_SIZE 3
#define MESSAGE_POS_LEN 0
#define MESSAGE_POS_SEQ 1
#define MESSAGE_TRAILER_CRC 3
#define MESSAGE_TRAILER_SYNC 1
#define MESSAGE_PAYLOAD_MAX (MESSAGE_MAX - MESSAGE_MIN)
#define MESSAGE_SEQ_MASK 0x0f
#define MESSAGE_DEST 0x10
#define MESSAGE_SYNC 0x7E
#include "sched.h" // sched_is_shutdown
static uint8_t next_sequence = MESSAGE_DEST;
@@ -67,13 +55,10 @@ parse_int(char **pp)
}
// Parse an incoming command into 'args'
static noinline char *
parsef(char *p, char *maxend, const struct command_parser *cp, uint32_t *args)
char *
command_parsef(char *p, char *maxend
, const struct command_parser *cp, uint32_t *args)
{
if (sched_is_shutdown() && !(READP(cp->flags) & HF_IN_SHUTDOWN)) {
sendf("is_shutdown static_string_id=%hu", sched_shutdown_reason());
return NULL;
}
uint8_t num_params = READP(cp->num_params);
const uint8_t *param_types = READP(cp->param_types);
while (num_params--) {
@@ -107,11 +92,87 @@ error:
shutdown("Command parser error");
}
// Encode a message
uint8_t
command_encodef(char *buf, const struct command_encoder *ce, va_list args)
{
uint8_t max_size = READP(ce->max_size);
if (max_size <= MESSAGE_MIN)
// Ack/Nak message
return max_size;
char *p = &buf[MESSAGE_HEADER_SIZE];
char *maxend = &p[max_size - MESSAGE_MIN];
uint8_t num_params = READP(ce->num_params);
const uint8_t *param_types = READP(ce->param_types);
*p++ = READP(ce->msg_id);
while (num_params--) {
if (p > maxend)
goto error;
uint8_t t = READP(*param_types);
param_types++;
uint32_t v;
switch (t) {
case PT_uint32:
case PT_int32:
case PT_uint16:
case PT_int16:
case PT_byte:
if (sizeof(v) > sizeof(int) && t >= PT_uint16)
if (t == PT_int16)
v = (int32_t)va_arg(args, int);
else
v = va_arg(args, unsigned int);
else
v = va_arg(args, uint32_t);
p = encode_int(p, v);
break;
case PT_string: {
char *s = va_arg(args, char*), *lenp = p++;
while (*s && p<maxend)
*p++ = *s++;
*lenp = p-lenp-1;
break;
}
case PT_progmem_buffer:
case PT_buffer: {
v = va_arg(args, int);
if (v > maxend-p)
v = maxend-p;
*p++ = v;
char *s = va_arg(args, char*);
if (t == PT_progmem_buffer)
memcpy_P(p, s, v);
else
memcpy(p, s, v);
p += v;
break;
}
default:
goto error;
}
}
return p - buf + MESSAGE_TRAILER_SIZE;
error:
shutdown("Message encode error");
}
// Add header and trailer bytes to a message block
void
command_add_frame(char *buf, uint8_t msglen)
{
buf[MESSAGE_POS_LEN] = msglen;
buf[MESSAGE_POS_SEQ] = next_sequence;
uint16_t crc = crc16_ccitt(buf, msglen - MESSAGE_TRAILER_SIZE);
buf[msglen - MESSAGE_TRAILER_CRC + 0] = crc >> 8;
buf[msglen - MESSAGE_TRAILER_CRC + 1] = crc;
buf[msglen - MESSAGE_TRAILER_SYNC] = MESSAGE_SYNC;
}
static uint8_t in_sendf;
// Encode a message and transmit it
// Encode and transmit a "response" message
void
_sendf(uint8_t parserid, ...)
command_sendf(const struct command_encoder *ce, ...)
{
if (readb(&in_sendf))
// This sendf call was made from an irq handler while the main
@@ -119,85 +180,15 @@ _sendf(uint8_t parserid, ...)
return;
writeb(&in_sendf, 1);
const struct command_encoder *cp = &command_encoders[parserid];
uint8_t max_size = READP(cp->max_size);
char *buf = console_get_output(max_size + MESSAGE_MIN);
if (!buf)
goto done;
char *p = &buf[MESSAGE_HEADER_SIZE];
if (max_size) {
char *maxend = &p[max_size];
va_list args;
va_start(args, parserid);
uint8_t num_params = READP(cp->num_params);
const uint8_t *param_types = READP(cp->param_types);
*p++ = READP(cp->msg_id);
while (num_params--) {
if (p > maxend)
goto error;
uint8_t t = READP(*param_types);
param_types++;
uint32_t v;
switch (t) {
case PT_uint32:
case PT_int32:
case PT_uint16:
case PT_int16:
case PT_byte:
if (t >= PT_uint16)
if (t == PT_int16)
v = (int32_t)va_arg(args, int);
else
v = va_arg(args, unsigned int);
else
v = va_arg(args, uint32_t);
p = encode_int(p, v);
break;
case PT_string: {
char *s = va_arg(args, char*), *lenp = p++;
while (*s && p<maxend)
*p++ = *s++;
*lenp = p-lenp-1;
break;
}
case PT_progmem_buffer:
case PT_buffer: {
v = va_arg(args, int);
if (v > maxend-p)
v = maxend-p;
*p++ = v;
char *s = va_arg(args, char*);
if (t == PT_progmem_buffer)
memcpy_P(p, s, v);
else
memcpy(p, s, v);
p += v;
break;
}
default:
goto error;
}
}
va_end(args);
}
va_list args;
va_start(args, ce);
console_sendf(ce, args);
va_end(args);
// Send message to serial port
uint8_t msglen = p+MESSAGE_TRAILER_SIZE - buf;
buf[MESSAGE_POS_LEN] = msglen;
buf[MESSAGE_POS_SEQ] = next_sequence;
uint16_t crc = crc16_ccitt(buf, p-buf);
*p++ = crc>>8;
*p++ = crc;
*p++ = MESSAGE_SYNC;
console_push_output(msglen);
done:
writeb(&in_sendf, 0);
return;
error:
shutdown("Message encode error");
}
static void
void
sendf_shutdown(void)
{
writeb(&in_sendf, 0);
@@ -211,32 +202,29 @@ DECL_SHUTDOWN(sendf_shutdown);
// Find the command handler associated with a command
static const struct command_parser *
command_get_handler(uint8_t cmdid)
command_lookup_parser(uint8_t cmdid)
{
if (cmdid >= READP(command_index_size))
goto error;
const struct command_parser *cp = READP(command_index[cmdid]);
if (!cp)
goto error;
return cp;
error:
shutdown("Invalid command");
if (!cmdid || cmdid >= READP(command_index_size))
shutdown("Invalid command");
return &command_index[cmdid];
}
// Empty message (for ack/nak transmission)
const struct command_encoder encode_acknak PROGMEM = {
.max_size = MESSAGE_MIN,
};
enum { CF_NEED_SYNC=1<<0, CF_NEED_VALID=1<<1 };
// Find the next complete message.
static char *
command_get_message(void)
// Find the next complete message block
int8_t
command_find_block(char *buf, uint8_t buf_len, uint8_t *pop_count)
{
static uint8_t sync_state;
uint8_t buf_len;
char *buf = console_get_input(&buf_len);
if (buf_len && sync_state & CF_NEED_SYNC)
goto need_sync;
if (buf_len < MESSAGE_MIN)
// Not ready to run.
return NULL;
goto need_more_data;
uint8_t msglen = buf[MESSAGE_POS_LEN];
if (msglen < MESSAGE_MIN || msglen > MESSAGE_MAX)
goto error;
@@ -244,8 +232,7 @@ command_get_message(void)
if ((msgseq & ~MESSAGE_SEQ_MASK) != MESSAGE_DEST)
goto error;
if (buf_len < msglen)
// Need more data
return NULL;
goto need_more_data;
if (buf[msglen-MESSAGE_TRAILER_SYNC] != MESSAGE_SYNC)
goto error;
uint16_t msgcrc = ((buf[msglen-MESSAGE_TRAILER_CRC] << 8)
@@ -254,21 +241,24 @@ command_get_message(void)
if (crc != msgcrc)
goto error;
sync_state &= ~CF_NEED_VALID;
*pop_count = msglen;
// Check sequence number
if (msgseq != next_sequence) {
// Lost message - discard messages until it is retransmitted
console_pop_input(msglen);
goto nak;
}
next_sequence = ((msgseq + 1) & MESSAGE_SEQ_MASK) | MESSAGE_DEST;
sendf(""); // An empty message with a new sequence number is an ack
return buf;
command_sendf(&encode_acknak);
return 1;
need_more_data:
*pop_count = 0;
return 0;
error:
if (buf[0] == MESSAGE_SYNC) {
// Ignore (do not nak) leading SYNC bytes
console_pop_input(1);
return NULL;
*pop_count = 1;
return -1;
}
sync_state |= CF_NEED_SYNC;
need_sync: ;
@@ -276,39 +266,35 @@ need_sync: ;
char *next_sync = memchr(buf, MESSAGE_SYNC, buf_len);
if (next_sync) {
sync_state &= ~CF_NEED_SYNC;
console_pop_input(next_sync - buf + 1);
*pop_count = next_sync - buf + 1;
} else {
console_pop_input(buf_len);
*pop_count = buf_len;
}
if (sync_state & CF_NEED_VALID)
return NULL;
return -1;
sync_state |= CF_NEED_VALID;
nak:
sendf(""); // An empty message with a duplicate sequence number is a nak
return NULL;
command_sendf(&encode_acknak);
return -1;
}
// Background task that reads commands from the board serial port
static void
command_task(void)
// Dispatch all the commands found in a message block
void
command_dispatch(char *buf, uint8_t msglen)
{
// Process commands.
char *buf = command_get_message();
if (!buf)
return;
uint8_t msglen = buf[MESSAGE_POS_LEN];
char *p = &buf[MESSAGE_HEADER_SIZE];
char *msgend = &buf[msglen-MESSAGE_TRAILER_SIZE];
while (p < msgend) {
uint8_t cmdid = *p++;
const struct command_parser *cp = command_get_handler(cmdid);
const struct command_parser *cp = command_lookup_parser(cmdid);
uint32_t args[READP(cp->num_args)];
p = parsef(p, msgend, cp, args);
if (!p)
break;
p = command_parsef(p, msgend, cp, args);
if (sched_is_shutdown() && !(READP(cp->flags) & HF_IN_SHUTDOWN)) {
sched_report_shutdown();
continue;
}
irq_poll();
void (*func)(uint32_t*) = READP(cp->func);
func(args);
}
console_pop_input(msglen);
}
DECL_TASK(command_task);
+44 -34
View File
@@ -2,9 +2,9 @@
#define __COMMAND_H
#include <stdarg.h> // va_list
#include <stddef.h> // size_t
#include <stddef.h>
#include <stdint.h> // uint8_t
#include "compiler.h" // __section
#include "ctr.h" // DECL_CTR
// Declare a function to run when the specified command is received
#define DECL_COMMAND(FUNC, MSG) \
@@ -21,11 +21,11 @@
// Send an output message (and declare a static message type for it)
#define output(FMT, args...) \
_sendf(_DECL_OUTPUT(FMT) , ##args )
command_sendf(_DECL_OUTPUT(FMT) , ##args )
// Declare a message type and transmit it.
#define sendf(FMT, args...) \
_sendf(_DECL_PARSER(FMT) , ##args)
command_sendf(_DECL_ENCODER(FMT) , ##args )
// Shut down the machine (also declares a static string to transmit)
#define shutdown(msg) \
@@ -33,10 +33,19 @@
#define try_shutdown(msg) \
sched_try_shutdown(_DECL_STATIC_STR(msg))
// command.c
void _sendf(uint8_t parserid, ...);
#define MESSAGE_MIN 5
#define MESSAGE_MAX 64
#define MESSAGE_HEADER_SIZE 2
#define MESSAGE_TRAILER_SIZE 3
#define MESSAGE_POS_LEN 0
#define MESSAGE_POS_SEQ 1
#define MESSAGE_TRAILER_CRC 3
#define MESSAGE_TRAILER_SYNC 1
#define MESSAGE_PAYLOAD_MAX (MESSAGE_MAX - MESSAGE_MIN)
#define MESSAGE_SEQ_MASK 0x0f
#define MESSAGE_DEST 0x10
#define MESSAGE_SYNC 0x7E
// out/compile_time_request.c (auto generated file)
struct command_encoder {
uint8_t msg_id, max_size, num_params;
const uint8_t *param_types;
@@ -50,41 +59,42 @@ enum {
PT_uint32, PT_int32, PT_uint16, PT_int16, PT_byte,
PT_string, PT_progmem_buffer, PT_buffer,
};
extern const struct command_encoder command_encoders[];
extern const struct command_parser * const command_index[];
// command.c
char *command_parsef(char *p, char *maxend
, const struct command_parser *cp, uint32_t *args);
uint8_t command_encodef(char *buf, const struct command_encoder *ce
, va_list args);
void command_sendf(const struct command_encoder *ce, ...);
void command_add_frame(char *buf, uint8_t msglen);
int8_t command_find_block(char *buf, uint8_t buf_len, uint8_t *pop_count);
void command_dispatch(char *buf, uint8_t msglen);
// out/compile_time_request.c (auto generated file)
extern const struct command_parser command_index[];
extern const uint8_t command_index_size;
extern const uint8_t command_identify_data[];
extern const uint32_t command_identify_size;
const struct command_encoder *ctr_lookup_encoder(const char *str);
const struct command_encoder *ctr_lookup_output(const char *str);
uint8_t ctr_lookup_static_string(const char *str);
// Compiler glue for DECL_COMMAND macros above.
#define _DECL_COMMAND(FUNC, FLAGS, MSG) \
char __PASTE(_DECLS_ ## FUNC ## _, __LINE__) [] \
__visible __section(".compile_time_request") \
= "_DECL_COMMAND " __stringify(FUNC) " " __stringify(FLAGS) " " MSG; \
void __visible FUNC(uint32_t*)
DECL_CTR("_DECL_COMMAND " __stringify(FUNC) " " __stringify(FLAGS) " " MSG)
#define _DECL_CONSTANT(NAME, VALUE) \
char __PASTE(_DECLC_ ## NAME ## _, __LINE__) [] \
__visible __section(".compile_time_request") \
= "_DECL_CONSTANT " __stringify(NAME) " " __stringify(VALUE)
#define _DECL_CONSTANT(NAME, VALUE) \
DECL_CTR("_DECL_CONSTANT " __stringify(NAME) " " __stringify(VALUE))
// Create a compile time request and return a unique (incrementing id)
// for that request.
#define _DECL_REQUEST_ID(REQUEST, ID_SECTION) ({ \
static char __PASTE(_DECLS_, __LINE__)[] \
__section(".compile_time_request") = REQUEST; \
asm volatile("" : : "m"(__PASTE(_DECLS_, __LINE__))); \
static char __PASTE(_DECLI_, __LINE__) \
__section(".compile_time_request." ID_SECTION); \
(size_t)&__PASTE(_DECLI_, __LINE__); })
#define _DECL_ENCODER(FMT) ({ \
DECL_CTR("_DECL_ENCODER " FMT); \
ctr_lookup_encoder(FMT); })
#define _DECL_PARSER(FMT) \
_DECL_REQUEST_ID("_DECL_PARSER " FMT, "parsers")
#define _DECL_OUTPUT(FMT) ({ \
DECL_CTR("_DECL_OUTPUT " FMT); \
ctr_lookup_output(FMT); })
#define _DECL_OUTPUT(FMT) \
_DECL_REQUEST_ID("_DECL_OUTPUT " FMT, "parsers")
#define _DECL_STATIC_STR(FMT) \
_DECL_REQUEST_ID("_DECL_STATIC_STR " FMT, "static_strings")
#define _DECL_STATIC_STR(MSG) ({ \
DECL_CTR("_DECL_STATIC_STR " MSG); \
ctr_lookup_static_string(MSG); })
#endif // command.h
+17
View File
@@ -0,0 +1,17 @@
#ifndef __CTR_H
#define __CTR_H
// Definitions for creating compile time requests. The DECL_CTR macro
// produces requests (text strings) that are placed in a special
// section of the intermediate object files. The requests are then
// extracted during the build and passed to scripts/buildcommand.py.
// The scripts/buildcommand.py code then generates
// out/compile_time_request.c from these requests.
#include "compiler.h" // __section
// Declare a compile time request
#define DECL_CTR(REQUEST) \
static char __PASTE(_DECLS_, __LINE__)[] __attribute__((used)) \
__section(".compile_time_request") = (REQUEST)
#endif // ctr.h
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff. Show more