ByteUtil -> kt

This commit is contained in:
Milos Kozak 2023-09-21 14:32:24 +02:00
parent 6ad2559caf
commit 120f1d4e03
101 changed files with 1225 additions and 995 deletions

View file

@ -29,7 +29,7 @@ import info.nightscout.interfaces.pump.PumpSync
import info.nightscout.interfaces.pump.WarnColors import info.nightscout.interfaces.pump.WarnColors
import info.nightscout.interfaces.queue.Callback import info.nightscout.interfaces.queue.Callback
import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.queue.CommandQueue
import info.nightscout.pump.core.defs.PumpDeviceState import info.nightscout.pump.common.defs.PumpDeviceState
import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventExtendedBolusChange import info.nightscout.rx.events.EventExtendedBolusChange
@ -188,7 +188,7 @@ class MedtronicFragment : DaggerFragment() {
@Synchronized @Synchronized
private fun setDeviceStatus() { private fun setDeviceStatus() {
val resourceId = rileyLinkServiceData.rileyLinkServiceState.resourceId val resourceId = rileyLinkServiceData.rileyLinkServiceState.resourceId
val rileyLinkError =rileyLinkServiceData.rileyLinkError val rileyLinkError = rileyLinkServiceData.rileyLinkError
binding.rlStatus.text = binding.rlStatus.text =
when { when {
rileyLinkServiceData.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> rh.gs(resourceId) rileyLinkServiceData.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> rh.gs(resourceId)

View file

@ -34,8 +34,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Comp
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Companion.getByteArrayFromUnsignedShort import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Companion.getByteArrayFromUnsignedShort
import info.nightscout.core.utils.DateTimeUtil import info.nightscout.core.utils.DateTimeUtil
import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.pump.defs.PumpType
import info.nightscout.pump.core.defs.PumpDeviceState import info.nightscout.pump.common.defs.PumpDeviceState
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import org.joda.time.LocalDateTime import org.joda.time.LocalDateTime
import java.util.Calendar import java.util.Calendar
@ -78,7 +78,8 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
fun onInit() { fun onInit() {
// we can't do this in the constructor, as sp only gets injected after the constructor has returned // we can't do this in the constructor, as sp only gets injected after the constructor has returned
medtronicPumpStatus.previousConnection = sp.getLong( medtronicPumpStatus.previousConnection = sp.getLong(
RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L) RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L
)
} }
override fun createResponseMessage(payload: ByteArray): PumpMessage { override fun createResponseMessage(payload: ByteArray): PumpMessage {
@ -127,8 +128,10 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
// check connection // check connection
val pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData) // simple val pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData) // simple
val rfSpyResponse = rfspy.transmitThenReceive(RadioPacket(injector, pumpMsgContent), 0.toByte(), 200.toByte(), val rfSpyResponse = rfspy.transmitThenReceive(
0.toByte(), 0.toByte(), 25000, 0.toByte()) RadioPacket(injector, pumpMsgContent), 0.toByte(), 200.toByte(),
0.toByte(), 0.toByte(), 25000, 0.toByte()
)
aapsLogger.info(LTag.PUMPCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.raw)) aapsLogger.info(LTag.PUMPCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.raw))
if (rfSpyResponse.wasTimeout()) { if (rfSpyResponse.wasTimeout()) {
aapsLogger.error(LTag.PUMPCOMM, "isDeviceReachable. Failed to find pump (timeout).") aapsLogger.error(LTag.PUMPCOMM, "isDeviceReachable. Failed to find pump (timeout).")
@ -140,8 +143,11 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
val pumpResponse = createResponseMessage(radioResponse.payload) val pumpResponse = createResponseMessage(radioResponse.payload)
if (!pumpResponse.isValid) { if (!pumpResponse.isValid) {
aapsLogger.warn( aapsLogger.warn(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Response is invalid ! [interrupted=%b, timeout=%b]", rfSpyResponse.wasInterrupted(), LTag.PUMPCOMM, String.format(
rfSpyResponse.wasTimeout())) Locale.ENGLISH, "Response is invalid ! [interrupted=%b, timeout=%b]", rfSpyResponse.wasInterrupted(),
rfSpyResponse.wasTimeout()
)
)
} else { } else {
// radioResponse.rssi; // radioResponse.rssi;
@ -153,8 +159,11 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
medtronicUtil.isModelSet = true medtronicUtil.isModelSet = true
} }
aapsLogger.debug( aapsLogger.debug(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "isDeviceReachable. PumpModel is %s - Valid: %b (rssi=%d)", medtronicUtil.medtronicPumpModel, valid, LTag.PUMPCOMM, String.format(
radioResponse.rssi)) Locale.ENGLISH, "isDeviceReachable. PumpModel is %s - Valid: %b (rssi=%d)", medtronicUtil.medtronicPumpModel, valid,
radioResponse.rssi
)
)
if (valid) { if (valid) {
if (state === PumpDeviceState.PumpUnreachable) if (state === PumpDeviceState.PumpUnreachable)
medtronicPumpStatus.pumpDeviceState = PumpDeviceState.WakingUp medtronicPumpStatus.pumpDeviceState = PumpDeviceState.WakingUp
@ -169,12 +178,14 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
} else { } else {
aapsLogger.warn( aapsLogger.warn(
LTag.PUMPCOMM, "isDeviceReachable. Failed to parse radio response: " LTag.PUMPCOMM, "isDeviceReachable. Failed to parse radio response: "
+ ByteUtil.shortHexString(rfSpyResponse.raw)) + ByteUtil.shortHexString(rfSpyResponse.raw)
)
} }
} catch (e: RileyLinkCommunicationException) { } catch (e: RileyLinkCommunicationException) {
aapsLogger.warn( aapsLogger.warn(
LTag.PUMPCOMM, "isDeviceReachable. Failed to decode radio response: " LTag.PUMPCOMM, "isDeviceReachable. Failed to decode radio response: "
+ ByteUtil.shortHexString(rfSpyResponse.raw)) + ByteUtil.shortHexString(rfSpyResponse.raw)
)
} }
} else { } else {
aapsLogger.warn(LTag.PUMPCOMM, "isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.raw)) aapsLogger.warn(LTag.PUMPCOMM, "isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.raw))
@ -230,8 +241,11 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
if (rval.commandType !== MedtronicCommandType.CommandACK) { if (rval.commandType !== MedtronicCommandType.CommandACK) {
aapsLogger.error(LTag.PUMPCOMM, "runCommandWithFrames: Pump did not ACK frame #$frameNr") aapsLogger.error(LTag.PUMPCOMM, "runCommandWithFrames: Pump did not ACK frame #$frameNr")
aapsLogger.error( aapsLogger.error(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Run command with Frames FAILED (command=%s, response=%s)", commandType.name, LTag.PUMPCOMM, String.format(
rval.toString())) Locale.ENGLISH, "Run command with Frames FAILED (command=%s, response=%s)", commandType.name,
rval.toString()
)
)
return PumpMessage(aapsLogger, "No ACK after frame #$frameNr") return PumpMessage(aapsLogger, "No ACK after frame #$frameNr")
} else { } else {
aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: Got ACK response for frame #$frameNr") aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: Got ACK response for frame #$frameNr")
@ -250,8 +264,10 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
for (pageNumber in 0..4) { for (pageNumber in 0..4) {
val rawHistoryPage = RawHistoryPage(aapsLogger) val rawHistoryPage = RawHistoryPage(aapsLogger)
// wakeUp(receiverDeviceAwakeForMinutes, false); // wakeUp(receiverDeviceAwakeForMinutes, false);
val getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData, val getHistoryMsg = makePumpMessage(
GetHistoryPageCarelinkMessageBody(pageNumber)) MedtronicCommandType.GetHistoryData,
GetHistoryPageCarelinkMessageBody(pageNumber)
)
aapsLogger.info(LTag.PUMPCOMM, "getPumpHistory: Page $pageNumber") aapsLogger.info(LTag.PUMPCOMM, "getPumpHistory: Page $pageNumber")
// aapsLogger.info(LTag.PUMPCOMM,"getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData())); // aapsLogger.info(LTag.PUMPCOMM,"getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData()));
// Ask the pump to transfer history (we get first frame?) // Ask the pump to transfer history (we get first frame?)
@ -293,8 +309,10 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
rawHistoryPage.appendData(currentResponse.frameData) rawHistoryPage.appendData(currentResponse.frameData)
// RileyLinkMedtronicService.getInstance().announceProgress(((100 / 16) * // RileyLinkMedtronicService.getInstance().announceProgress(((100 / 16) *
// currentResponse.getFrameNumber() + 1)); // currentResponse.getFrameNumber() + 1));
medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, medtronicUtil.setCurrentCommand(
currentResponse.frameNumber) MedtronicCommandType.GetHistoryData, pageNumber,
currentResponse.frameNumber
)
aapsLogger.info(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: Got frame %d of Page %d", currentResponse.frameNumber, pageNumber)) aapsLogger.info(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: Got frame %d of Page %d", currentResponse.frameNumber, pageNumber))
// Do we need to ask for the next frame? // Do we need to ask for the next frame?
if (expectedFrameNum < 16) { // This number may not be correct for pumps other than 522/722 if (expectedFrameNum < 16) { // This number may not be correct for pumps other than 522/722
@ -311,8 +329,11 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
failures++ failures++
if (failures == 6) { if (failures == 6) {
aapsLogger.error( aapsLogger.error(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: 6 failures in attempting to download frame %d of page %d, giving up.", LTag.PUMPCOMM, String.format(
expectedFrameNum, pageNumber)) Locale.ENGLISH, "getPumpHistory: 6 failures in attempting to download frame %d of page %d, giving up.",
expectedFrameNum, pageNumber
)
)
done = true // failure completion. done = true // failure completion.
doneWithError = true doneWithError = true
} }
@ -338,7 +359,8 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
if (rawHistoryPage.length != 1024) { if (rawHistoryPage.length != 1024) {
aapsLogger.warn( aapsLogger.warn(
LTag.PUMPCOMM, "getPumpHistory: short page. Expected length of 1024, found length of " LTag.PUMPCOMM, "getPumpHistory: short page. Expected length of 1024, found length of "
+ rawHistoryPage.length) + rawHistoryPage.length
)
doneWithError = true doneWithError = true
} }
if (!rawHistoryPage.isChecksumOK) { if (!rawHistoryPage.isChecksumOK) {
@ -365,9 +387,9 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
override fun createPumpMessageContent(type: RLMessageType): ByteArray { override fun createPumpMessageContent(type: RLMessageType): ByteArray {
return when (type) { return when (type) {
RLMessageType.PowerOn -> medtronicUtil.buildCommandPayload(rileyLinkServiceData, MedtronicCommandType.RFPowerOn, byteArrayOf(2, 1, receiverDeviceAwakeForMinutes.toByte())) RLMessageType.PowerOn -> medtronicUtil.buildCommandPayload(rileyLinkServiceData, MedtronicCommandType.RFPowerOn, byteArrayOf(2, 1, receiverDeviceAwakeForMinutes.toByte()))
RLMessageType.ReadSimpleData -> medtronicUtil.buildCommandPayload(rileyLinkServiceData, MedtronicCommandType.PumpModel, null) RLMessageType.ReadSimpleData -> medtronicUtil.buildCommandPayload(rileyLinkServiceData, MedtronicCommandType.PumpModel, null)
else -> ByteArray(0) else -> ByteArray(0)
} }
} }
@ -451,8 +473,11 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
private inline fun checkResponseRawContent(rawContent: ByteArray?, commandType: MedtronicCommandType, errorCase: () -> Unit) { private inline fun checkResponseRawContent(rawContent: ByteArray?, commandType: MedtronicCommandType, errorCase: () -> Unit) {
if (rawContent?.isEmpty() != false && commandType != MedtronicCommandType.PumpModel) { if (rawContent?.isEmpty() != false && commandType != MedtronicCommandType.PumpModel) {
aapsLogger.warn( aapsLogger.warn(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Content is empty or too short, no data to convert (type=%s,isNull=%b,length=%s)", LTag.PUMPCOMM, String.format(
commandType.name, rawContent == null, rawContent?.size ?: "-")) Locale.ENGLISH, "Content is empty or too short, no data to convert (type=%s,isNull=%b,length=%s)",
commandType.name, rawContent == null, rawContent?.size ?: "-"
)
)
errorCase.invoke() errorCase.invoke()
} else { } else {
aapsLogger.debug(LTag.PUMPCOMM, "Raw response before convert: " + ByteUtil.shortHexString(rawContent)) aapsLogger.debug(LTag.PUMPCOMM, "Raw response before convert: " + ByteUtil.shortHexString(rawContent))
@ -473,7 +498,8 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
} else { } else {
val responseData = String.format( val responseData = String.format(
"%s: Cannot return data. Data is too short [expected=%s, received=%s].", method, "" "%s: Cannot return data. Data is too short [expected=%s, received=%s].", method, ""
+ expectedLength, "" + contents.size) + expectedLength, "" + contents.size
)
aapsLogger.warn(LTag.PUMPCOMM, responseData) aapsLogger.warn(LTag.PUMPCOMM, responseData)
responseData responseData
} }
@ -564,7 +590,8 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
private fun checkIfWeHaveMoreData(commandType: MedtronicCommandType, response: PumpMessage, data: ByteArray): Boolean { private fun checkIfWeHaveMoreData(commandType: MedtronicCommandType, response: PumpMessage, data: ByteArray): Boolean {
if (commandType === MedtronicCommandType.GetBasalProfileSTD || // if (commandType === MedtronicCommandType.GetBasalProfileSTD || //
commandType === MedtronicCommandType.GetBasalProfileA || // commandType === MedtronicCommandType.GetBasalProfileA || //
commandType === MedtronicCommandType.GetBasalProfileB) { commandType === MedtronicCommandType.GetBasalProfileB
) {
val responseRaw = response.rawContentOfFrame val responseRaw = response.rawContentOfFrame
val last = responseRaw.size - 1 val last = responseRaw.size - 1
aapsLogger.debug(LTag.PUMPCOMM, "Length: " + data.size) aapsLogger.debug(LTag.PUMPCOMM, "Length: " + data.size)
@ -652,8 +679,11 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
try { try {
if (doWakeUpBeforeCommand) wakeUp(false) if (doWakeUpBeforeCommand) wakeUp(false)
if (debugSetCommands) aapsLogger.debug( if (debugSetCommands) aapsLogger.debug(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: Body - %s", commandType.commandDescription, LTag.PUMPCOMM, String.format(
ByteUtil.getHex(body))) Locale.ENGLISH, "%s: Body - %s", commandType.commandDescription,
ByteUtil.getHex(body)
)
)
val msg = makePumpMessage(commandType, CarelinkLongMessageBody(body)) val msg = makePumpMessage(commandType, CarelinkLongMessageBody(body))
val pumpMessage = runCommandWithArgs(msg) val pumpMessage = runCommandWithArgs(msg)
if (debugSetCommands) aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: %s", commandType.commandDescription, pumpMessage.responseContent)) if (debugSetCommands) aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: %s", commandType.commandDescription, pumpMessage.responseContent))
@ -684,14 +714,25 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
for (retries in 0..MAX_COMMAND_TRIES) { for (retries in 0..MAX_COMMAND_TRIES) {
var responseMessage: PumpMessage? = null var responseMessage: PumpMessage? = null
try { try {
responseMessage = runCommandWithFrames(MedtronicCommandType.SetBasalProfileSTD, responseMessage = runCommandWithFrames(
basalProfileFrames) MedtronicCommandType.SetBasalProfileSTD,
basalProfileFrames
)
if (responseMessage!!.commandType === MedtronicCommandType.CommandACK) return true if (responseMessage!!.commandType === MedtronicCommandType.CommandACK) return true
} catch (e: RileyLinkCommunicationException) { } catch (e: RileyLinkCommunicationException) {
aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.message, retries + 1)) aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.message, retries + 1))
} }
if (responseMessage != null) aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Set Basal Profile: Invalid response: commandType=%s,rawData=%s", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.rawContent))) else aapsLogger.warn( if (responseMessage != null) aapsLogger.warn(
LTag.PUMPCOMM, "Set Basal Profile: Null response.") LTag.PUMPCOMM,
String.format(
Locale.ENGLISH,
"Set Basal Profile: Invalid response: commandType=%s,rawData=%s",
responseMessage.commandType,
ByteUtil.shortHexString(responseMessage.rawContent)
)
) else aapsLogger.warn(
LTag.PUMPCOMM, "Set Basal Profile: Null response."
)
} }
return false return false
} }

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps.plugins.pump.medtronic.comm package info.nightscout.androidaps.plugins.pump.medtronic.comm
import info.nightscout.interfaces.pump.defs.PumpType
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BatteryStatusDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BatteryStatusDTO
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpConfigurationGroup import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpConfigurationGroup
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.interfaces.pump.defs.PumpType
import info.nightscout.pump.core.utils.StringUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.pump.common.utils.StringUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import org.joda.time.IllegalFieldValueException import org.joda.time.IllegalFieldValueException
@ -82,7 +82,7 @@ class MedtronicConverter @Inject constructor(
if (strokes == 40) { if (strokes == 40) {
startIdx = 2 startIdx = 2
} }
if (rawData.size==2 && strokes == 40) { if (rawData.size == 2 && strokes == 40) {
aapsLogger.error(LTag.PUMPCOMM, "It seems configuration is not correct, detected model $pumpModel should have length bigger than 2, but it doesn't (data: $rawData)") aapsLogger.error(LTag.PUMPCOMM, "It seems configuration is not correct, detected model $pumpModel should have length bigger than 2, but it doesn't (data: $rawData)")
startIdx = 0 startIdx = 0
} }
@ -112,8 +112,11 @@ class MedtronicConverter @Inject constructor(
LocalDateTime(year, month, day, hours, minutes, seconds) LocalDateTime(year, month, day, hours, minutes, seconds)
} catch (e: IllegalFieldValueException) { } catch (e: IllegalFieldValueException) {
aapsLogger.error( aapsLogger.error(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "decodeTime: Failed to parse pump time value: year=%d, month=%d, hours=%d, minutes=%d, seconds=%d", LTag.PUMPCOMM, String.format(
year, month, day, hours, minutes, seconds)) Locale.ENGLISH, "decodeTime: Failed to parse pump time value: year=%d, month=%d, hours=%d, minutes=%d, seconds=%d",
year, month, day, hours, minutes, seconds
)
)
null null
} }
} }
@ -123,11 +126,17 @@ class MedtronicConverter @Inject constructor(
addSettingToMap("PCFG_MAX_BOLUS", "" + decodeMaxBolus(rd), PumpConfigurationGroup.Bolus, map) addSettingToMap("PCFG_MAX_BOLUS", "" + decodeMaxBolus(rd), PumpConfigurationGroup.Bolus, map)
addSettingToMap( addSettingToMap(
"PCFG_MAX_BASAL", "" "PCFG_MAX_BASAL", ""
+ decodeBasalInsulin( + decodeBasalInsulin(
ByteUtil.makeUnsignedShort(rd[settingIndexMaxBasal].toInt(), ByteUtil.makeUnsignedShort(
rd[settingIndexMaxBasal + 1].toInt())), PumpConfigurationGroup.Basal, map) rd[settingIndexMaxBasal].toInt(),
addSettingToMap("CFG_BASE_CLOCK_MODE", if (rd[settingIndexTimeDisplayFormat].toInt() == 0) "12h" else "24h", rd[settingIndexMaxBasal + 1].toInt()
PumpConfigurationGroup.General, map) )
), PumpConfigurationGroup.Basal, map
)
addSettingToMap(
"CFG_BASE_CLOCK_MODE", if (rd[settingIndexTimeDisplayFormat].toInt() == 0) "12h" else "24h",
PumpConfigurationGroup.General, map
)
addSettingToMap("PCFG_BASAL_PROFILES_ENABLED", parseResultEnable(rd[10].toInt()), PumpConfigurationGroup.Basal, map) addSettingToMap("PCFG_BASAL_PROFILES_ENABLED", parseResultEnable(rd[10].toInt()), PumpConfigurationGroup.Basal, map)
if (rd[10].toInt() == 1) { if (rd[10].toInt() == 1) {
val patt: String val patt: String
@ -156,25 +165,37 @@ class MedtronicConverter @Inject constructor(
} }
addSettingToMap("PCFG_AUDIO_BOLUS_ENABLED", parseResultEnable(rd[2].toInt()), PumpConfigurationGroup.Bolus, map) addSettingToMap("PCFG_AUDIO_BOLUS_ENABLED", parseResultEnable(rd[2].toInt()), PumpConfigurationGroup.Bolus, map)
if (rd[2].toInt() == 1) { if (rd[2].toInt() == 1) {
addSettingToMap("PCFG_AUDIO_BOLUS_STEP_SIZE", "" + decodeBolusInsulin(ByteUtil.asUINT8(rd[3])), addSettingToMap(
PumpConfigurationGroup.Bolus, map) "PCFG_AUDIO_BOLUS_STEP_SIZE", "" + decodeBolusInsulin(ByteUtil.asUINT8(rd[3])),
PumpConfigurationGroup.Bolus, map
)
} }
addSettingToMap("PCFG_VARIABLE_BOLUS_ENABLED", parseResultEnable(rd[4].toInt()), PumpConfigurationGroup.Bolus, map) addSettingToMap("PCFG_VARIABLE_BOLUS_ENABLED", parseResultEnable(rd[4].toInt()), PumpConfigurationGroup.Bolus, map)
addSettingToMap("PCFG_MAX_BOLUS", "" + decodeMaxBolus(rd), PumpConfigurationGroup.Bolus, map) addSettingToMap("PCFG_MAX_BOLUS", "" + decodeMaxBolus(rd), PumpConfigurationGroup.Bolus, map)
addSettingToMap( addSettingToMap(
"PCFG_MAX_BASAL", "" "PCFG_MAX_BASAL", ""
+ decodeBasalInsulin( + decodeBasalInsulin(
ByteUtil.makeUnsignedShort(rd[settingIndexMaxBasal].toInt(), ByteUtil.makeUnsignedShort(
rd[settingIndexMaxBasal + 1].toInt())), PumpConfigurationGroup.Basal, map) rd[settingIndexMaxBasal].toInt(),
addSettingToMap("CFG_BASE_CLOCK_MODE", if (rd[settingIndexTimeDisplayFormat].toInt() == 0) "12h" else "24h", rd[settingIndexMaxBasal + 1].toInt()
PumpConfigurationGroup.General, map) )
), PumpConfigurationGroup.Basal, map
)
addSettingToMap(
"CFG_BASE_CLOCK_MODE", if (rd[settingIndexTimeDisplayFormat].toInt() == 0) "12h" else "24h",
PumpConfigurationGroup.General, map
)
if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) {
addSettingToMap("PCFG_INSULIN_CONCENTRATION", "" + if (rd[9].toInt() == 0) 50 else 100, PumpConfigurationGroup.Insulin, addSettingToMap(
map) "PCFG_INSULIN_CONCENTRATION", "" + if (rd[9].toInt() == 0) 50 else 100, PumpConfigurationGroup.Insulin,
map
)
// LOG.debug("Insulin concentration: " + rd[9]); // LOG.debug("Insulin concentration: " + rd[9]);
} else { } else {
addSettingToMap("PCFG_INSULIN_CONCENTRATION", "" + if (rd[9].toInt() != 0) 50 else 100, PumpConfigurationGroup.Insulin, addSettingToMap(
map) "PCFG_INSULIN_CONCENTRATION", "" + if (rd[9].toInt() != 0) 50 else 100, PumpConfigurationGroup.Insulin,
map
)
// LOG.debug("Insulin concentration: " + rd[9]); // LOG.debug("Insulin concentration: " + rd[9]);
} }
addSettingToMap("PCFG_BASAL_PROFILES_ENABLED", parseResultEnable(rd[10].toInt()), PumpConfigurationGroup.Basal, map) addSettingToMap("PCFG_BASAL_PROFILES_ENABLED", parseResultEnable(rd[10].toInt()), PumpConfigurationGroup.Basal, map)
@ -205,16 +226,25 @@ class MedtronicConverter @Inject constructor(
fun decodeSettings(rd: ByteArray): Map<String, PumpSettingDTO> { fun decodeSettings(rd: ByteArray): Map<String, PumpSettingDTO> {
val map = decodeSettings512(rd) val map = decodeSettings512(rd)
addSettingToMap("PCFG_MM_RESERVOIR_WARNING_TYPE_TIME", if (rd[18].toInt() != 0) "PCFG_MM_RESERVOIR_WARNING_TYPE_TIME" else "PCFG_MM_RESERVOIR_WARNING_TYPE_UNITS", PumpConfigurationGroup.Other, map) addSettingToMap(
addSettingToMap("PCFG_MM_SRESERVOIR_WARNING_POINT", "" + ByteUtil.asUINT8(rd[19]), "PCFG_MM_RESERVOIR_WARNING_TYPE_TIME",
PumpConfigurationGroup.Other, map) if (rd[18].toInt() != 0) "PCFG_MM_RESERVOIR_WARNING_TYPE_TIME" else "PCFG_MM_RESERVOIR_WARNING_TYPE_UNITS",
PumpConfigurationGroup.Other,
map
)
addSettingToMap(
"PCFG_MM_SRESERVOIR_WARNING_POINT", "" + ByteUtil.asUINT8(rd[19]),
PumpConfigurationGroup.Other, map
)
addSettingToMap("CFG_MM_KEYPAD_LOCKED", parseResultEnable(rd[20].toInt()), PumpConfigurationGroup.Other, map) addSettingToMap("CFG_MM_KEYPAD_LOCKED", parseResultEnable(rd[20].toInt()), PumpConfigurationGroup.Other, map)
if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) {
addSettingToMap("PCFG_BOLUS_SCROLL_STEP_SIZE", "" + rd[21], PumpConfigurationGroup.Bolus, map) addSettingToMap("PCFG_BOLUS_SCROLL_STEP_SIZE", "" + rd[21], PumpConfigurationGroup.Bolus, map)
addSettingToMap("PCFG_CAPTURE_EVENT_ENABLE", parseResultEnable(rd[22].toInt()), PumpConfigurationGroup.Other, map) addSettingToMap("PCFG_CAPTURE_EVENT_ENABLE", parseResultEnable(rd[22].toInt()), PumpConfigurationGroup.Other, map)
addSettingToMap("PCFG_OTHER_DEVICE_ENABLE", parseResultEnable(rd[23].toInt()), PumpConfigurationGroup.Other, map) addSettingToMap("PCFG_OTHER_DEVICE_ENABLE", parseResultEnable(rd[23].toInt()), PumpConfigurationGroup.Other, map)
addSettingToMap("PCFG_OTHER_DEVICE_PAIRED_STATE", parseResultEnable(rd[24].toInt()), PumpConfigurationGroup.Other, addSettingToMap(
map) "PCFG_OTHER_DEVICE_PAIRED_STATE", parseResultEnable(rd[24].toInt()), PumpConfigurationGroup.Other,
map
)
} }
return map return map
} }
@ -234,8 +264,10 @@ class MedtronicConverter @Inject constructor(
// 512 // 512
private fun decodeInsulinActionSetting(ai: ByteArray, map: MutableMap<String, PumpSettingDTO>) { private fun decodeInsulinActionSetting(ai: ByteArray, map: MutableMap<String, PumpSettingDTO>) {
if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_512_712)) { if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_512_712)) {
addSettingToMap("PCFG_INSULIN_ACTION_TYPE", if (ai[17].toInt() != 0) "Regular" else "Fast", addSettingToMap(
PumpConfigurationGroup.Insulin, map) "PCFG_INSULIN_ACTION_TYPE", if (ai[17].toInt() != 0) "Regular" else "Fast",
PumpConfigurationGroup.Insulin, map
)
} else { } else {
val i = ai[17].toInt() val i = ai[17].toInt()
val s: String val s: String

View file

@ -1,8 +1,7 @@
package info.nightscout.androidaps.plugins.pump.medtronic.comm.history package info.nightscout.androidaps.plugins.pump.medtronic.comm.history
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.StringUtil
import info.nightscout.pump.core.utils.StringUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.StringUtils
@ -14,9 +13,9 @@ import org.apache.commons.lang3.StringUtils
* *
* Author: Andy {andy.rozman@gmail.com} * Author: Andy {andy.rozman@gmail.com}
*/ */
abstract class MedtronicHistoryDecoder<T : MedtronicHistoryEntry?>(var aapsLogger: AAPSLogger, abstract class MedtronicHistoryDecoder<T : MedtronicHistoryEntry?>(
var medtronicUtil: MedtronicUtil, var aapsLogger: AAPSLogger,
var bitUtils: ByteUtil var medtronicUtil: MedtronicUtil
) : MedtronicHistoryDecoderInterface<T> { ) : MedtronicHistoryDecoderInterface<T> {
// STATISTICS (remove at later time or not) // STATISTICS (remove at later time or not)

View file

@ -2,8 +2,8 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.core.utils.DateTimeUtil import info.nightscout.core.utils.DateTimeUtil
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.pump.core.utils.StringUtil import info.nightscout.pump.common.utils.StringUtil
/** /**
* This file was taken from GGC - GNU Gluco Control (ggc.sourceforge.net), application for diabetes * This file was taken from GGC - GNU Gluco Control (ggc.sourceforge.net), application for diabetes

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history
import info.nightscout.androidaps.plugins.pump.common.utils.CRC import info.nightscout.androidaps.plugins.pump.common.utils.CRC
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import java.util.Arrays import java.util.Arrays
@ -36,8 +36,11 @@ class RawHistoryPage(private val aapsLogger: AAPSLogger) {
val crcStored = ByteUtil.toInt(data[1022].toInt(), data[1023].toInt()) val crcStored = ByteUtil.toInt(data[1022].toInt(), data[1023].toInt())
if (crcCalculated != crcStored) { if (crcCalculated != crcStored) {
aapsLogger.error( aapsLogger.error(
LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Stored CRC (%d) is different than calculated (%d), but ignored for now.", crcStored, LTag.PUMPBTCOMM, String.format(
crcCalculated)) Locale.ENGLISH, "Stored CRC (%d) is different than calculated (%d), but ignored for now.", crcStored,
crcCalculated
)
)
} else { } else {
if (MedtronicUtil.isLowLevelDebug) aapsLogger.debug(LTag.PUMPBTCOMM, "CRC ok.") if (MedtronicUtil.isLowLevelDebug) aapsLogger.debug(LTag.PUMPBTCOMM, "CRC ok.")
} }

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.cgms
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.MedtronicHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.MedtronicHistoryEntry
import info.nightscout.core.utils.DateTimeUtil import info.nightscout.core.utils.DateTimeUtil
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.StringUtils
import org.joda.time.LocalDateTime import org.joda.time.LocalDateTime

View file

@ -5,7 +5,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RecordDeco
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.cgms.CGMSHistoryEntryType.Companion.getByCode import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.cgms.CGMSHistoryEntryType.Companion.getByCode
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.core.utils.DateTimeUtil import info.nightscout.core.utils.DateTimeUtil
import info.nightscout.pump.core.utils.ByteUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import org.joda.time.LocalDateTime import org.joda.time.LocalDateTime
@ -20,9 +19,8 @@ import java.util.Arrays
*/ */
class MedtronicCGMSHistoryDecoder constructor( class MedtronicCGMSHistoryDecoder constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
medtronicUtil: MedtronicUtil, medtronicUtil: MedtronicUtil
bitUtils: ByteUtil ) : MedtronicHistoryDecoder<CGMSHistoryEntry>(aapsLogger, medtronicUtil) {
) : MedtronicHistoryDecoder<CGMSHistoryEntry>(aapsLogger, medtronicUtil, bitUtils) {
override fun decodeRecord(record: CGMSHistoryEntry): RecordDecodeStatus? { override fun decodeRecord(record: CGMSHistoryEntry): RecordDecodeStatus? {
return try { return try {
@ -172,8 +170,10 @@ class MedtronicCGMSHistoryDecoder constructor(
if (!entry.entryType.hasDate()) return null if (!entry.entryType.hasDate()) return null
val data = entry.datetime val data = entry.datetime
return if (entry.entryType.dateType === CGMSHistoryEntryType.DateType.MinuteSpecific) { return if (entry.entryType.dateType === CGMSHistoryEntryType.DateType.MinuteSpecific) {
val atechDateTime = DateTimeUtil.toATechDate(parseYear(data[3].toInt()), parseMonths(data[0].toInt(), data[1].toInt()), val atechDateTime = DateTimeUtil.toATechDate(
parseDay(data[2].toInt()), parseHours(data[0].toInt()), parseMinutes(data[1].toInt()), 0) parseYear(data[3].toInt()), parseMonths(data[0].toInt(), data[1].toInt()),
parseDay(data[2].toInt()), parseHours(data[0].toInt()), parseMinutes(data[1].toInt()), 0
)
entry.atechDateTime = atechDateTime entry.atechDateTime = atechDateTime
atechDateTime atechDateTime
} else if (entry.entryType.dateType === CGMSHistoryEntryType.DateType.SecondSpecific) { } else if (entry.entryType.dateType === CGMSHistoryEntryType.DateType.SecondSpecific) {

View file

@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceTyp
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpBolusType import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpBolusType
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.core.utils.DateTimeUtil import info.nightscout.core.utils.DateTimeUtil
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import java.util.Locale import java.util.Locale
@ -30,9 +30,8 @@ import kotlin.experimental.and
@Singleton @Singleton
class MedtronicPumpHistoryDecoder @Inject constructor( class MedtronicPumpHistoryDecoder @Inject constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
medtronicUtil: MedtronicUtil, medtronicUtil: MedtronicUtil
bitUtils: ByteUtil ) : MedtronicHistoryDecoder<PumpHistoryEntry>(aapsLogger, medtronicUtil) {
) : MedtronicHistoryDecoder<PumpHistoryEntry>(aapsLogger, medtronicUtil, bitUtils) {
//private var tbrPreviousRecord: PumpHistoryEntry? = null //private var tbrPreviousRecord: PumpHistoryEntry? = null
private var changeTimeRecord: PumpHistoryEntry? = null private var changeTimeRecord: PumpHistoryEntry? = null
@ -78,7 +77,8 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
val listRawData: MutableList<Byte> = ArrayList() val listRawData: MutableList<Byte> = ArrayList()
listRawData.add(opCode.toByte()) listRawData.add(opCode.toByte())
if (entryType === PumpHistoryEntryType.UnabsorbedInsulin if (entryType === PumpHistoryEntryType.UnabsorbedInsulin
|| entryType === PumpHistoryEntryType.UnabsorbedInsulin512) { || entryType === PumpHistoryEntryType.UnabsorbedInsulin512
) {
val elements: Int = dataClearInput[counter].toInt() val elements: Int = dataClearInput[counter].toInt()
listRawData.add(elements.toByte()) listRawData.add(elements.toByte())
counter++ counter++
@ -98,7 +98,8 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
} catch (ex: Exception) { } catch (ex: Exception) {
aapsLogger.error( aapsLogger.error(
LTag.PUMPBTCOMM, "OpCode: " + ByteUtil.shortHexString(opCode.toByte()) + ", Invalid package: " LTag.PUMPBTCOMM, "OpCode: " + ByteUtil.shortHexString(opCode.toByte()) + ", Invalid package: "
+ ByteUtil.getHex(listRawData)) + ByteUtil.getHex(listRawData)
)
// throw ex; // throw ex;
incompletePacket = true incompletePacket = true
break break
@ -204,12 +205,15 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
PumpHistoryEntryType.UnabsorbedInsulin, PumpHistoryEntryType.UnabsorbedInsulin,
PumpHistoryEntryType.UnabsorbedInsulin512 -> RecordDecodeStatus.Ignored PumpHistoryEntryType.UnabsorbedInsulin512 -> RecordDecodeStatus.Ignored
PumpHistoryEntryType.DailyTotals522, PumpHistoryEntryType.DailyTotals522,
PumpHistoryEntryType.DailyTotals523, PumpHistoryEntryType.DailyTotals523,
PumpHistoryEntryType.DailyTotals515, PumpHistoryEntryType.DailyTotals515,
PumpHistoryEntryType.EndResultTotals -> decodeDailyTotals(entry) PumpHistoryEntryType.EndResultTotals -> decodeDailyTotals(entry)
PumpHistoryEntryType.ChangeBasalProfile_OldProfile, PumpHistoryEntryType.ChangeBasalProfile_OldProfile,
PumpHistoryEntryType.ChangeBasalProfile_NewProfile -> decodeBasalProfile(entry) PumpHistoryEntryType.ChangeBasalProfile_NewProfile -> decodeBasalProfile(entry)
PumpHistoryEntryType.BasalProfileStart -> decodeBasalProfileStart(entry) PumpHistoryEntryType.BasalProfileStart -> decodeBasalProfileStart(entry)
PumpHistoryEntryType.ChangeTime -> { PumpHistoryEntryType.ChangeTime -> {
@ -253,6 +257,7 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
PumpHistoryEntryType.ChangeMaxBasal, PumpHistoryEntryType.ChangeMaxBasal,
PumpHistoryEntryType.ClearSettings, PumpHistoryEntryType.ClearSettings,
PumpHistoryEntryType.SaveSettings -> RecordDecodeStatus.OK PumpHistoryEntryType.SaveSettings -> RecordDecodeStatus.OK
PumpHistoryEntryType.BolusWizard -> decodeBolusWizard(entry) PumpHistoryEntryType.BolusWizard -> decodeBolusWizard(entry)
PumpHistoryEntryType.BolusWizard512 -> decodeBolusWizard512(entry) PumpHistoryEntryType.BolusWizard512 -> decodeBolusWizard512(entry)
@ -425,16 +430,20 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
val bolus: BolusDTO? val bolus: BolusDTO?
val data = entry.head val data = entry.head
if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) {
bolus = BolusDTO(atechDateTime = entry.atechDateTime, bolus = BolusDTO(
requestedAmount = ByteUtil.toInt(data.get(0), data.get(1)) / 40.0, atechDateTime = entry.atechDateTime,
deliveredAmount = ByteUtil.toInt(data.get(2), data.get(3)) / 40.0, requestedAmount = ByteUtil.toInt(data.get(0), data.get(1)) / 40.0,
duration = data.get(6) * 30) deliveredAmount = ByteUtil.toInt(data.get(2), data.get(3)) / 40.0,
duration = data.get(6) * 30
)
bolus.insulinOnBoard = ByteUtil.toInt(data.get(4), data.get(5)) / 40.0 bolus.insulinOnBoard = ByteUtil.toInt(data.get(4), data.get(5)) / 40.0
} else { } else {
bolus = BolusDTO(atechDateTime = entry.atechDateTime, bolus = BolusDTO(
requestedAmount = ByteUtil.asUINT8(data.get(0)) / 10.0, atechDateTime = entry.atechDateTime,
deliveredAmount = ByteUtil.asUINT8(data.get(1)) / 10.0, requestedAmount = ByteUtil.asUINT8(data.get(0)) / 10.0,
duration = ByteUtil.asUINT8(data.get(2)) * 30) deliveredAmount = ByteUtil.asUINT8(data.get(1)) / 10.0,
duration = ByteUtil.asUINT8(data.get(2)) * 30
)
} }
bolus.bolusType = if (bolus.duration > 0) PumpBolusType.Extended else PumpBolusType.Normal bolus.bolusType = if (bolus.duration > 0) PumpBolusType.Extended else PumpBolusType.Normal
entry.addDecodedData("Object", bolus) entry.addDecodedData("Object", bolus)
@ -459,7 +468,8 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
tbrRate.head.get(0), tbrRate.head.get(0),
tbrRate.body.get(0), tbrRate.body.get(0),
tbrDuration!!.head.get(0).toInt(), tbrDuration!!.head.get(0).toInt(),
ByteUtil.asUINT8(tbrRate.datetime.get(4)) shr 3 == 0) ByteUtil.asUINT8(tbrRate.datetime.get(4)) shr 3 == 0
)
entry.addDecodedData("Object", tbr) entry.addDecodedData("Object", tbr)
entry.displayableValue = tbr.description entry.displayableValue = tbr.description
@ -495,8 +505,11 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
//LOG.debug("DT: {} {} {}", year, month, dayOfMonth); //LOG.debug("DT: {} {} {}", year, month, dayOfMonth);
if (dayOfMonth == 32) { if (dayOfMonth == 32) {
aapsLogger.warn( aapsLogger.warn(
LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Entry: Day 32 %s = [%s] %s", entry.entryType.name, LTag.PUMPBTCOMM, String.format(
ByteUtil.getHex(entry.rawData), entry)) Locale.ENGLISH, "Entry: Day 32 %s = [%s] %s", entry.entryType.name,
ByteUtil.getHex(entry.rawData), entry
)
)
} }
if (isEndResults(entry.entryType)) { if (isEndResults(entry.entryType)) {
hour = 23 hour = 23

View file

@ -4,8 +4,8 @@ import com.google.gson.annotations.Expose
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.MedtronicHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.MedtronicHistoryEntry
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BolusDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BolusDTO
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.pump.core.utils.StringUtil import info.nightscout.pump.common.utils.StringUtil
import java.util.Objects import java.util.Objects
/** /**

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.pump.medtronic.comm.message package info.nightscout.androidaps.plugins.pump.medtronic.comm.message
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import kotlin.experimental.and import kotlin.experimental.and
/** /**

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.pump.medtronic.comm.message package info.nightscout.androidaps.plugins.pump.medtronic.comm.message
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
/** /**
* Created by geoff on 5/29/16. * Created by geoff on 5/29/16.

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.message
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import kotlin.math.min import kotlin.math.min
@ -61,8 +61,10 @@ class PumpMessage : RLMessage {
} }
} }
if (rxData.size > 5) { if (rxData.size > 5) {
messageBody = MedtronicCommandType.constructMessageBody(commandType, messageBody = MedtronicCommandType.constructMessageBody(
ByteUtil.substring(rxData, 5, rxData.size - 5)) commandType,
ByteUtil.substring(rxData, 5, rxData.size - 5)
)
} }
} }

View file

@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicUIRespons
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.pump.core.defs.PumpDeviceState import info.nightscout.pump.common.defs.PumpDeviceState
import info.nightscout.rx.bus.RxBus import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
@ -106,8 +106,10 @@ class MedtronicUITask {
} }
MedtronicCommandType.GetHistoryData -> { MedtronicCommandType.GetHistoryData -> {
result = communicationManager.getPumpHistory(parameters!![0] as PumpHistoryEntry?, result = communicationManager.getPumpHistory(
parameters!![1] as LocalDateTime?) parameters!![0] as PumpHistoryEntry?,
parameters!![1] as LocalDateTime?
)
} }
else -> { else -> {
@ -127,9 +129,11 @@ class MedtronicUITask {
} }
private fun getTbrSettings(): TempBasalPair { private fun getTbrSettings(): TempBasalPair {
return TempBasalPair(getDoubleFromParameters(0)!!, // return TempBasalPair(
getDoubleFromParameters(0)!!, //
false, // false, //
getIntegerFromParameters(1)) getIntegerFromParameters(1)
)
} }
private fun getFloatFromParameters(index: Int): Float { private fun getFloatFromParameters(index: Int): Float {
@ -153,13 +157,19 @@ class MedtronicUITask {
postprocessor.postProcessData(this) postprocessor.postProcessData(this)
} }
if (responseType === MedtronicUIResponseType.Invalid) { if (responseType === MedtronicUIResponseType.Invalid) {
rxBus.send(EventRileyLinkDeviceStatusChange( rxBus.send(
PumpDeviceState.ErrorWhenCommunicating, EventRileyLinkDeviceStatusChange(
"Unsupported command in MedtronicUITask")) PumpDeviceState.ErrorWhenCommunicating,
"Unsupported command in MedtronicUITask"
)
)
} else if (responseType === MedtronicUIResponseType.Error) { } else if (responseType === MedtronicUIResponseType.Error) {
rxBus.send(EventRileyLinkDeviceStatusChange( rxBus.send(
PumpDeviceState.ErrorWhenCommunicating, EventRileyLinkDeviceStatusChange(
errorDescription)) PumpDeviceState.ErrorWhenCommunicating,
errorDescription
)
)
} else { } else {
rxBus.send(EventMedtronicPumpValuesChanged()) rxBus.send(EventMedtronicPumpValuesChanged())
medtronicPumpStatus.setLastCommunicationToNow() medtronicPumpStatus.setLastCommunicationToNow()

View file

@ -32,7 +32,7 @@ import info.nightscout.pump.common.sync.PumpDbEntryBolus
import info.nightscout.pump.common.sync.PumpDbEntryCarbs import info.nightscout.pump.common.sync.PumpDbEntryCarbs
import info.nightscout.pump.common.sync.PumpDbEntryTBR import info.nightscout.pump.common.sync.PumpDbEntryTBR
import info.nightscout.pump.common.sync.PumpSyncStorage import info.nightscout.pump.common.sync.PumpSyncStorage
import info.nightscout.pump.core.utils.StringUtil import info.nightscout.pump.common.utils.StringUtil
import info.nightscout.rx.bus.RxBus import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag

View file

@ -1,9 +1,9 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data.dto package info.nightscout.androidaps.plugins.pump.medtronic.data.dto
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.interfaces.pump.defs.PumpType
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.interfaces.pump.defs.PumpType
import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import org.joda.time.Instant import org.joda.time.Instant
@ -102,8 +102,11 @@ class BasalProfile {
val startString = entry.startTime!!.toString("HH:mm") val startString = entry.startTime!!.toString("HH:mm")
// this doesn't work // this doesn't work
aapsLogger.debug( aapsLogger.debug(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Entry %d, rate=%.3f (%s), start=%s (0x%02X)", i + 1, entry.rate, LTag.PUMPCOMM, String.format(
ByteUtil.getHex(entry.rate_raw), startString, entry.startTime_raw)) Locale.ENGLISH, "Entry %d, rate=%.3f (%s), start=%s (0x%02X)", i + 1, entry.rate,
ByteUtil.getHex(entry.rate_raw), startString, entry.startTime_raw
)
)
} }
} }
@ -142,8 +145,11 @@ class BasalProfile {
val entries = getEntries() val entries = getEntries()
if (entries.size == 0) { if (entries.size == 0) {
aapsLogger.warn( aapsLogger.warn(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getEntryForTime(%s): table is empty", LTag.PUMPCOMM, String.format(
`when`.toDateTime().toLocalTime().toString("HH:mm"))) Locale.ENGLISH, "getEntryForTime(%s): table is empty",
`when`.toDateTime().toLocalTime().toString("HH:mm")
)
)
return rval return rval
} }
// Log.w(TAG,"Assuming first entry"); // Log.w(TAG,"Assuming first entry");
@ -159,8 +165,11 @@ class BasalProfile {
val entry = entries[i] val entry = entries[i]
if (DEBUG_BASALPROFILE) { if (DEBUG_BASALPROFILE) {
aapsLogger.debug( aapsLogger.debug(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Comparing 'now'=%s to entry 'start time'=%s", `when`.toDateTime().toLocalTime() LTag.PUMPCOMM, String.format(
.toString("HH:mm"), entry.startTime!!.toString("HH:mm"))) Locale.ENGLISH, "Comparing 'now'=%s to entry 'start time'=%s", `when`.toDateTime().toLocalTime()
.toString("HH:mm"), entry.startTime!!.toString("HH:mm")
)
)
} }
if (localMillis >= entry.startTime!!.millisOfDay) { if (localMillis >= entry.startTime!!.millisOfDay) {
rval = entry rval = entry
@ -177,9 +186,12 @@ class BasalProfile {
} }
if (DEBUG_BASALPROFILE) { if (DEBUG_BASALPROFILE) {
aapsLogger.debug( aapsLogger.debug(
LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getEntryForTime(%s): Returning entry: rate=%.3f (%s), start=%s (%d)", `when` LTag.PUMPCOMM, String.format(
.toDateTime().toLocalTime().toString("HH:mm"), rval.rate, ByteUtil.getHex(rval.rate_raw), Locale.ENGLISH, "getEntryForTime(%s): Returning entry: rate=%.3f (%s), start=%s (%d)", `when`
rval.startTime!!.toString("HH:mm"), rval.startTime_raw)) .toDateTime().toLocalTime().toString("HH:mm"), rval.rate, ByteUtil.getHex(rval.rate_raw),
rval.startTime!!.toString("HH:mm"), rval.startTime_raw
)
)
} }
return rval return rval
}// readUnsignedByte(mRawData[i]); }// readUnsignedByte(mRawData[i]);

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpBolusType import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpBolusType
import info.nightscout.pump.core.utils.StringUtil import info.nightscout.pump.common.utils.StringUtil
/** /**
* Application: GGC - GNU Gluco Control * Application: GGC - GNU Gluco Control
@ -30,10 +30,11 @@ import info.nightscout.pump.core.utils.StringUtil
* *
* Author: Andy {andy@atech-software.com} * Author: Andy {andy@atech-software.com}
*/ */
class BolusDTO constructor(atechDateTime: Long, class BolusDTO constructor(
@Expose var requestedAmount: Double, atechDateTime: Long,
@Expose var deliveredAmount: Double, @Expose var requestedAmount: Double,
@Expose var duration: Int = 0 @Expose var deliveredAmount: Double,
@Expose var duration: Int = 0
) : PumpTimeStampedRecord(atechDateTime) { ) : PumpTimeStampedRecord(atechDateTime) {
@Expose @Expose
@ -56,11 +57,15 @@ class BolusDTO constructor(atechDateTime: Long,
get() = if (bolusType === PumpBolusType.Normal || bolusType === PumpBolusType.Audio) { get() = if (bolusType === PumpBolusType.Normal || bolusType === PumpBolusType.Audio) {
getFormattedDecimal(deliveredAmount) getFormattedDecimal(deliveredAmount)
} else if (bolusType === PumpBolusType.Extended) { } else if (bolusType === PumpBolusType.Extended) {
String.format("AMOUNT_SQUARE=%s;DURATION=%s", getFormattedDecimal(deliveredAmount), String.format(
durationString) "AMOUNT_SQUARE=%s;DURATION=%s", getFormattedDecimal(deliveredAmount),
durationString
)
} else { } else {
String.format("AMOUNT=%s;AMOUNT_SQUARE=%s;DURATION=%s", getFormattedDecimal(immediateAmount!!), String.format(
getFormattedDecimal(deliveredAmount), durationString) "AMOUNT=%s;AMOUNT_SQUARE=%s;DURATION=%s", getFormattedDecimal(immediateAmount!!),
getFormattedDecimal(deliveredAmount), durationString
)
} }
val displayableValue: String val displayableValue: String

View file

@ -4,8 +4,8 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntryType import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntryType
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.pump.core.utils.StringUtil import info.nightscout.pump.common.utils.StringUtil
import org.apache.commons.lang3.builder.ToStringBuilder import org.apache.commons.lang3.builder.ToStringBuilder
import java.util.Locale import java.util.Locale
@ -64,8 +64,10 @@ class DailyTotalsDTO(var entry: PumpHistoryEntry) {
} }
private fun decodeEndResultsTotals(entry: PumpHistoryEntry) { private fun decodeEndResultsTotals(entry: PumpHistoryEntry) {
val totals = ByteUtil.toInt(entry.head[0].toInt(), entry.head[1].toInt(), entry.head[2].toInt(), val totals = ByteUtil.toInt(
entry.head[3].toInt(), ByteUtil.BitConversion.BIG_ENDIAN) * 0.025 entry.head[0].toInt(), entry.head[1].toInt(), entry.head[2].toInt(),
entry.head[3].toInt(), ByteUtil.BitConversion.BIG_ENDIAN
) * 0.025
insulinTotal = totals insulinTotal = totals
entry.addDecodedData("Totals", totals) entry.addDecodedData("Totals", totals)
} }
@ -79,11 +81,19 @@ class DailyTotalsDTO(var entry: PumpHistoryEntry) {
val k: Int = ByteUtil.toInt(data[i], data[i + 1], data[i + 2]) val k: Int = ByteUtil.toInt(data[i], data[i + 1], data[i + 2])
val j1 = ByteUtil.toInt(data[i + 1], data[i]) val j1 = ByteUtil.toInt(data[i + 1], data[i])
val k1: Int = ByteUtil.toInt(data[i + 2], data[i + 1], data[i]) val k1: Int = ByteUtil.toInt(data[i + 2], data[i + 1], data[i])
println(String.format(Locale.ENGLISH, println(
"index: %d, number=%d, del/40=%.3f, del/10=%.3f, singular=%d, sing_hex=%s", i, j, j / 40.0, j / 10.0, String.format(
data[i], ByteUtil.shortHexString(data[i]))) Locale.ENGLISH,
println(String.format(Locale.ENGLISH, " number[k,j1,k1]=%d / %d /%d, del/40=%.3f, del/40=%.3f, del/40=%.3f", "index: %d, number=%d, del/40=%.3f, del/10=%.3f, singular=%d, sing_hex=%s", i, j, j / 40.0, j / 10.0,
k, j1, k1, k / 40.0, j1 / 40.0, k1 / 40.0)) data[i], ByteUtil.shortHexString(data[i])
)
)
println(
String.format(
Locale.ENGLISH, " number[k,j1,k1]=%d / %d /%d, del/40=%.3f, del/40=%.3f, del/40=%.3f",
k, j1, k1, k / 40.0, j1 / 40.0, k1 / 40.0
)
)
} }
} }

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data.dto package info.nightscout.androidaps.plugins.pump.medtronic.data.dto
import info.nightscout.pump.core.utils.StringUtil import info.nightscout.pump.common.utils.StringUtil
/** /**
* Created by andy on 6/2/18. * Created by andy on 6/2/18.

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.pump.common.defs.TempBasalPair import info.nightscout.pump.common.defs.TempBasalPair
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import java.util.Locale import java.util.Locale

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.pump.medtronic.di package info.nightscout.androidaps.plugins.pump.medtronic.di
import dagger.Module import dagger.Module
import dagger.Provides
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager
@ -9,7 +8,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUIComm
import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask
import info.nightscout.androidaps.plugins.pump.medtronic.dialog.MedtronicHistoryActivity import info.nightscout.androidaps.plugins.pump.medtronic.dialog.MedtronicHistoryActivity
import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService
import info.nightscout.pump.core.utils.ByteUtil
@Module @Module
@Suppress("unused") @Suppress("unused")
@ -26,10 +24,4 @@ abstract class MedtronicModule {
abstract fun medtronicCommunicationManagerProvider(): MedtronicCommunicationManager abstract fun medtronicCommunicationManagerProvider(): MedtronicCommunicationManager
@ContributesAndroidInjector abstract fun medtronicUITaskProvider(): MedtronicUITask @ContributesAndroidInjector abstract fun medtronicUITaskProvider(): MedtronicUITask
@ContributesAndroidInjector abstract fun medtronicUICommProvider(): MedtronicUIComm @ContributesAndroidInjector abstract fun medtronicUICommProvider(): MedtronicUIComm
companion object {
@Provides
fun byteUtilProvider(): ByteUtil = ByteUtil()
}
} }

View file

@ -11,8 +11,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst
import info.nightscout.annotations.OpenForTesting import info.nightscout.annotations.OpenForTesting
import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.pump.defs.PumpType
import info.nightscout.pump.common.data.PumpStatus import info.nightscout.pump.common.data.PumpStatus
import info.nightscout.pump.common.defs.PumpDeviceState
import info.nightscout.pump.common.sync.PumpDbEntryTBR import info.nightscout.pump.common.sync.PumpDbEntryTBR
import info.nightscout.pump.core.defs.PumpDeviceState
import info.nightscout.rx.bus.RxBus import info.nightscout.rx.bus.RxBus
import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP

View file

@ -17,8 +17,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceTyp
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.pump.core.defs.PumpDeviceState import info.nightscout.pump.common.defs.PumpDeviceState
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton

View file

@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceTyp
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.ui.UiInteraction
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.bus.RxBus import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventDismissNotification import info.nightscout.rx.events.EventDismissNotification
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
@ -21,6 +21,7 @@ import info.nightscout.rx.logging.LTag
import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.interfaces.ResourceHelper
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.nio.ByteOrder import java.nio.ByteOrder
import java.security.InvalidParameterException
import java.util.Locale import java.util.Locale
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -45,8 +46,10 @@ class MedtronicUtil @Inject constructor(
//private MedtronicDeviceType medtronicPumpModel; //private MedtronicDeviceType medtronicPumpModel;
private var currentCommand: MedtronicCommandType? = null private var currentCommand: MedtronicCommandType? = null
var settings: Map<String, PumpSettingDTO>? = null var settings: Map<String, PumpSettingDTO>? = null
@Suppress("PrivatePropertyName") @Suppress("PrivatePropertyName")
private val BIG_FRAME_LENGTH = 65 private val BIG_FRAME_LENGTH = 65
//private val doneBit = 1 shl 7 //private val doneBit = 1 shl 7
var pumpTime: ClockDTO? = null var pumpTime: ClockDTO? = null
var gsonInstance: Gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() var gsonInstance: Gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
@ -89,7 +92,7 @@ class MedtronicUtil @Inject constructor(
scrollRate = 1 scrollRate = 1
} }
val strokes = (amount * (strokesPerUnit * 1.0 / (scrollRate * 1.0))).toInt() * scrollRate val strokes = (amount * (strokesPerUnit * 1.0 / (scrollRate * 1.0))).toInt() * scrollRate
return ByteUtil.fromHexString(String.format("%02x%0" + 2 * length + "x", length, strokes)) return ByteUtil.fromHexString(String.format("%02x%0" + 2 * length + "x", length, strokes)) ?: throw InvalidParameterException()
} }
// fun createCommandBody(input: ByteArray): ByteArray { // fun createCommandBody(input: ByteArray): ByteArray {
@ -169,7 +172,7 @@ class MedtronicUtil @Inject constructor(
// System.out.println("Subarray: " + ByteUtil.getCompactString(substring)); // System.out.println("Subarray: " + ByteUtil.getCompactString(substring));
// System.out.println("Subarray Lenths: " + substring.length); // System.out.println("Subarray Lenths: " + substring.length);
val frameData = ByteUtil.getListFromByteArray(substring) val frameData = ByteUtil.getListFromByteArray(substring).toMutableList()
if (isEmptyFrame(frameData)) { if (isEmptyFrame(frameData)) {
var b = frame.toByte() var b = frame.toByte()
// b |= 0x80; // b |= 0x80;

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.ActivePlugin
import info.nightscout.interfaces.pump.PumpSync import info.nightscout.interfaces.pump.PumpSync
import info.nightscout.pump.common.sync.PumpSyncStorage import info.nightscout.pump.common.sync.PumpSyncStorage
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP
import info.nightscout.sharedtests.TestBase import info.nightscout.sharedtests.TestBase

View file

@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpSta
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.database.impl.serialisation.SealedClassHelper import info.nightscout.database.impl.serialisation.SealedClassHelper
import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.ui.UiInteraction
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.mockito.Mock import org.mockito.Mock

View file

@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceTyp
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.ui.UiInteraction
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message; package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message;
import androidx.annotation.NonNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.List; import java.util.List;
@ -14,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Po
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.CrcMismatchException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.CrcMismatchException;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.MessageDecodingException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.MessageDecodingException;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.NotEnoughDataException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.NotEnoughDataException;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import info.nightscout.rx.logging.AAPSLogger; import info.nightscout.rx.logging.AAPSLogger;
import info.nightscout.rx.logging.LTag; import info.nightscout.rx.logging.LTag;
@ -41,20 +43,20 @@ public class OmnipodMessage {
throw new NotEnoughDataException(data); throw new NotEnoughDataException(data);
} }
int address = ByteUtil.toInt((int) data[0], (int) data[1], (int) data[2], int address = ByteUtil.INSTANCE.toInt((int) data[0], (int) data[1], (int) data[2],
(int) data[3], ByteUtil.BitConversion.BIG_ENDIAN); (int) data[3], ByteUtil.BitConversion.BIG_ENDIAN);
byte b9 = data[4]; byte b9 = data[4];
int bodyLength = ByteUtil.convertUnsignedByteToInt(data[5]); int bodyLength = ByteUtil.INSTANCE.convertUnsignedByteToInt(data[5]);
if (data.length - 8 < bodyLength) { if (data.length - 8 < bodyLength) {
throw new NotEnoughDataException(data); throw new NotEnoughDataException(data);
} }
int sequenceNumber = (((int) b9 >> 2) & 0b11111); int sequenceNumber = (((int) b9 >> 2) & 0b11111);
int crc = ByteUtil.toInt(data[data.length - 2], data[data.length - 1]); int crc = ByteUtil.INSTANCE.toInt(data[data.length - 2], data[data.length - 1]);
int calculatedCrc = OmnipodCrc.crc16(ByteUtil.substring(data, 0, data.length - 2)); int calculatedCrc = OmnipodCrc.crc16(ByteUtil.INSTANCE.substring(data, 0, data.length - 2));
if (crc != calculatedCrc) { if (crc != calculatedCrc) {
throw new CrcMismatchException(calculatedCrc, crc); throw new CrcMismatchException(calculatedCrc, crc);
} }
List<MessageBlock> blocks = decodeBlocks(ByteUtil.substring(data, 6, data.length - 6 - 2)); List<MessageBlock> blocks = decodeBlocks(ByteUtil.INSTANCE.substring(data, 6, data.length - 6 - 2));
if (blocks.size() == 0) { if (blocks.size() == 0) {
throw new MessageDecodingException("No blocks decoded"); throw new MessageDecodingException("No blocks decoded");
} }
@ -68,7 +70,7 @@ public class OmnipodMessage {
while (index < data.length) { while (index < data.length) {
try { try {
MessageBlockType blockType = MessageBlockType.fromByte(data[index]); MessageBlockType blockType = MessageBlockType.fromByte(data[index]);
MessageBlock block = blockType.decode(ByteUtil.substring(data, index)); MessageBlock block = blockType.decode(ByteUtil.INSTANCE.substring(data, index));
blocks.add(block); blocks.add(block);
int blockLength = block.getRawData().length; int blockLength = block.getRawData().length;
index += blockLength; index += blockLength;
@ -83,17 +85,17 @@ public class OmnipodMessage {
public byte[] getEncoded() { public byte[] getEncoded() {
byte[] encodedData = new byte[0]; byte[] encodedData = new byte[0];
for (MessageBlock messageBlock : messageBlocks) { for (MessageBlock messageBlock : messageBlocks) {
encodedData = ByteUtil.concat(encodedData, messageBlock.getRawData()); encodedData = ByteUtil.INSTANCE.concat(encodedData, messageBlock.getRawData());
} }
byte[] header = new byte[0]; byte[] header = new byte[0];
//right before the message blocks we have 6 bits of seqNum and 10 bits of length //right before the message blocks we have 6 bits of seqNum and 10 bits of length
header = ByteUtil.concat(header, ByteUtil.getBytesFromInt(address)); header = ByteUtil.INSTANCE.concat(header, ByteUtil.INSTANCE.getBytesFromInt(address));
header = ByteUtil.concat(header, (byte) (((sequenceNumber & 0x1F) << 2) + ((encodedData.length >> 8) & 0x03))); header = ByteUtil.INSTANCE.concat(header, (byte) (((sequenceNumber & 0x1F) << 2) + ((encodedData.length >> 8) & 0x03)));
header = ByteUtil.concat(header, (byte) (encodedData.length & 0xFF)); header = ByteUtil.INSTANCE.concat(header, (byte) (encodedData.length & 0xFF));
encodedData = ByteUtil.concat(header, encodedData); encodedData = ByteUtil.INSTANCE.concat(header, encodedData);
int crc = OmnipodCrc.crc16(encodedData); int crc = OmnipodCrc.crc16(encodedData);
encodedData = ByteUtil.concat(encodedData, ByteUtil.substring(ByteUtil.getBytesFromInt(crc), 2, 2)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.substring(ByteUtil.INSTANCE.getBytesFromInt(crc), 2, 2));
return encodedData; return encodedData;
} }
@ -160,12 +162,12 @@ public class OmnipodMessage {
return messageBlocks.size() >= 1 && messageBlocks.get(0).getType() == MessageBlockType.CANCEL_DELIVERY; return messageBlocks.size() >= 1 && messageBlocks.get(0).getType() == MessageBlockType.CANCEL_DELIVERY;
} }
@Override @NonNull @Override
public String toString() { public String toString() {
return "OmnipodMessage{" + return "OmnipodMessage{" +
"address=" + address + "address=" + address +
", messageBlocks=" + messageBlocks + ", messageBlocks=" + messageBlocks +
", encoded=" + ByteUtil.shortHexStringWithoutSpaces(getEncoded()) + ", encoded=" + ByteUtil.INSTANCE.shortHexStringWithoutSpaces(getEncoded()) +
", sequenceNumber=" + sequenceNumber + ", sequenceNumber=" + sequenceNumber +
'}'; '}';
} }

View file

@ -5,7 +5,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Om
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PacketType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PacketType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.CrcMismatchException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.CrcMismatchException;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalPacketTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalPacketTypeException;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
/** /**
* Created by andy on 6/1/18. * Created by andy on 6/1/18.
@ -21,7 +21,7 @@ public class OmnipodPacket implements RLMessage {
if (encoded.length < 7) { if (encoded.length < 7) {
return; return;
} }
this.packetAddress = ByteUtil.toInt((int) encoded[0], (int) encoded[1], this.packetAddress = ByteUtil.INSTANCE.toInt((int) encoded[0], (int) encoded[1],
(int) encoded[2], (int) encoded[3], ByteUtil.BitConversion.BIG_ENDIAN); (int) encoded[2], (int) encoded[3], ByteUtil.BitConversion.BIG_ENDIAN);
try { try {
this.packetType = PacketType.fromByte((byte) (((int) encoded[4] & 0xFF) >> 5)); this.packetType = PacketType.fromByte((byte) (((int) encoded[4] & 0xFF) >> 5));
@ -29,11 +29,11 @@ public class OmnipodPacket implements RLMessage {
throw new IllegalPacketTypeException(null, null); throw new IllegalPacketTypeException(null, null);
} }
this.sequenceNumber = (encoded[4] & 0b11111); this.sequenceNumber = (encoded[4] & 0b11111);
byte crc = OmnipodCrc.crc8(ByteUtil.substring(encoded, 0, encoded.length - 1)); byte crc = OmnipodCrc.crc8(ByteUtil.INSTANCE.substring(encoded, 0, encoded.length - 1));
if (crc != encoded[encoded.length - 1]) { if (crc != encoded[encoded.length - 1]) {
throw new CrcMismatchException(crc, encoded[encoded.length - 1]); throw new CrcMismatchException(crc, encoded[encoded.length - 1]);
} }
this.encodedMessage = ByteUtil.substring(encoded, 5, encoded.length - 1 - 5); this.encodedMessage = ByteUtil.INSTANCE.substring(encoded, 5, encoded.length - 1 - 5);
valid = true; valid = true;
} }
@ -43,7 +43,7 @@ public class OmnipodPacket implements RLMessage {
this.sequenceNumber = packetNumber; this.sequenceNumber = packetNumber;
this.encodedMessage = encodedMessage; this.encodedMessage = encodedMessage;
if (encodedMessage.length > packetType.getMaxBodyLength()) { if (encodedMessage.length > packetType.getMaxBodyLength()) {
this.encodedMessage = ByteUtil.substring(encodedMessage, 0, packetType.getMaxBodyLength()); this.encodedMessage = ByteUtil.INSTANCE.substring(encodedMessage, 0, packetType.getMaxBodyLength());
} }
this.valid = true; this.valid = true;
} }
@ -67,10 +67,10 @@ public class OmnipodPacket implements RLMessage {
@Override @Override
public byte[] getTxData() { public byte[] getTxData() {
byte[] output = new byte[0]; byte[] output = new byte[0];
output = ByteUtil.concat(output, ByteUtil.getBytesFromInt(this.packetAddress)); output = ByteUtil.INSTANCE.concat(output, ByteUtil.INSTANCE.getBytesFromInt(this.packetAddress));
output = ByteUtil.concat(output, (byte) ((this.packetType.getValue() << 5) + (sequenceNumber & 0b11111))); output = ByteUtil.INSTANCE.concat(output, (byte) ((this.packetType.getValue() << 5) + (sequenceNumber & 0b11111)));
output = ByteUtil.concat(output, encodedMessage); output = ByteUtil.INSTANCE.concat(output, encodedMessage);
output = ByteUtil.concat(output, OmnipodCrc.crc8(output)); output = ByteUtil.INSTANCE.concat(output, OmnipodCrc.crc8(output));
return output; return output;
} }
@ -85,7 +85,7 @@ public class OmnipodPacket implements RLMessage {
"packetAddress=" + packetAddress + "packetAddress=" + packetAddress +
", packetType=" + packetType + ", packetType=" + packetType +
", sequenceNumber=" + sequenceNumber + ", sequenceNumber=" + sequenceNumber +
", encodedMessage=" + ByteUtil.shortHexStringWithoutSpaces(encodedMessage) + ", encodedMessage=" + ByteUtil.INSTANCE.shortHexStringWithoutSpaces(encodedMessage) +
", valid=" + valid + ", valid=" + valid +
'}'; '}';
} }

View file

@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSet; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSet;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class AcknowledgeAlertsCommand extends NonceResyncableMessageBlock { public class AcknowledgeAlertsCommand extends NonceResyncableMessageBlock {
@ -31,8 +31,8 @@ public class AcknowledgeAlertsCommand extends NonceResyncableMessageBlock {
} }
private void encode() { private void encode() {
encodedData = ByteUtil.getBytesFromInt(nonce); encodedData = ByteUtil.INSTANCE.getBytesFromInt(nonce);
encodedData = ByteUtil.concat(encodedData, alerts.getRawValue()); encodedData = ByteUtil.INSTANCE.concat(encodedData, alerts.getRawValue());
} }
@Override @Override

View file

@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Me
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.RateEntry; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.RateEntry;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class BasalScheduleExtraCommand extends MessageBlock { public class BasalScheduleExtraCommand extends MessageBlock {
private final boolean acknowledgementBeep; private final boolean acknowledgementBeep;
@ -73,11 +73,11 @@ public class BasalScheduleExtraCommand extends MessageBlock {
currentEntryIndex currentEntryIndex
}; };
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt16((int) Math.round(remainingPulses * 10))); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt16((int) Math.round(remainingPulses * 10)));
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt((int) Math.round(delayUntilNextTenthOfPulseInSeconds * 1000 * 1000))); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt((int) Math.round(delayUntilNextTenthOfPulseInSeconds * 1000 * 1000)));
for (RateEntry entry : rateEntries) { for (RateEntry entry : rateEntries) {
encodedData = ByteUtil.concat(encodedData, entry.getRawData()); encodedData = ByteUtil.INSTANCE.concat(encodedData, entry.getRawData());
} }
} }

View file

@ -7,7 +7,7 @@ import org.joda.time.Duration;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.MessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepConfigType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepConfigType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class BeepConfigCommand extends MessageBlock { public class BeepConfigCommand extends MessageBlock {
private final BeepConfigType beepType; private final BeepConfigType beepType;
@ -34,9 +34,9 @@ public class BeepConfigCommand extends MessageBlock {
private void encode() { private void encode() {
encodedData = new byte[]{beepType.getValue()}; encodedData = new byte[]{beepType.getValue()};
encodedData = ByteUtil.concat(encodedData, (byte) ((basalCompletionBeep ? (1 << 6) : 0) + (basalIntervalBeep.getStandardMinutes() & 0x3f))); encodedData = ByteUtil.INSTANCE.concat(encodedData, (byte) ((basalCompletionBeep ? (1 << 6) : 0) + (basalIntervalBeep.getStandardMinutes() & 0x3f)));
encodedData = ByteUtil.concat(encodedData, (byte) ((tempBasalCompletionBeep ? (1 << 6) : 0) + (tempBasalIntervalBeep.getStandardMinutes() & 0x3f))); encodedData = ByteUtil.INSTANCE.concat(encodedData, (byte) ((tempBasalCompletionBeep ? (1 << 6) : 0) + (tempBasalIntervalBeep.getStandardMinutes() & 0x3f)));
encodedData = ByteUtil.concat(encodedData, (byte) ((bolusCompletionBeep ? (1 << 6) : 0) + (bolusIntervalBeep.getStandardMinutes() & 0x3f))); encodedData = ByteUtil.INSTANCE.concat(encodedData, (byte) ((bolusCompletionBeep ? (1 << 6) : 0) + (bolusIntervalBeep.getStandardMinutes() & 0x3f)));
} }
@Override @Override

View file

@ -5,7 +5,7 @@ import org.joda.time.Duration;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.MessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class BolusExtraCommand extends MessageBlock { public class BolusExtraCommand extends MessageBlock {
private final boolean acknowledgementBeep; private final boolean acknowledgementBeep;
@ -48,11 +48,11 @@ public class BolusExtraCommand extends MessageBlock {
int squareWavePulseCountCountX10 = (int) Math.round(squareWaveUnits * 200); int squareWavePulseCountCountX10 = (int) Math.round(squareWaveUnits * 200);
int timeBetweenExtendedPulses = squareWavePulseCountCountX10 > 0 ? (int) squareWaveDuration.getMillis() * 100 / squareWavePulseCountCountX10 : 0; int timeBetweenExtendedPulses = squareWavePulseCountCountX10 > 0 ? (int) squareWaveDuration.getMillis() * 100 / squareWavePulseCountCountX10 : 0;
encodedData = ByteUtil.concat(encodedData, beepOptions); encodedData = ByteUtil.INSTANCE.concat(encodedData, beepOptions);
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt16((int) Math.round(units * 200))); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt16((int) Math.round(units * 200)));
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt((int) timeBetweenPulses.getMillis() * 100)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt((int) timeBetweenPulses.getMillis() * 100));
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt16(squareWavePulseCountCountX10)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt16(squareWavePulseCountCountX10));
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt(timeBetweenExtendedPulses)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt(timeBetweenExtendedPulses));
} }
@Override @Override

View file

@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class CancelDeliveryCommand extends NonceResyncableMessageBlock { public class CancelDeliveryCommand extends NonceResyncableMessageBlock {
@ -32,7 +32,7 @@ public class CancelDeliveryCommand extends NonceResyncableMessageBlock {
private void encode() { private void encode() {
encodedData = new byte[5]; encodedData = new byte[5];
System.arraycopy(ByteUtil.getBytesFromInt(nonce), 0, encodedData, 0, 4); System.arraycopy(ByteUtil.INSTANCE.getBytesFromInt(nonce), 0, encodedData, 0, 4);
byte beepTypeValue = beepType.getValue(); byte beepTypeValue = beepType.getValue();
if (beepTypeValue > 8) { if (beepTypeValue > 8) {
beepTypeValue = 0; beepTypeValue = 0;

View file

@ -7,7 +7,7 @@ import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.NonceResyncableMessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.NonceResyncableMessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertConfiguration; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertConfiguration;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class ConfigureAlertsCommand extends NonceResyncableMessageBlock { public class ConfigureAlertsCommand extends NonceResyncableMessageBlock {
private final List<AlertConfiguration> configurations; private final List<AlertConfiguration> configurations;
@ -25,9 +25,9 @@ public class ConfigureAlertsCommand extends NonceResyncableMessageBlock {
} }
private void encode() { private void encode() {
encodedData = ByteUtil.getBytesFromInt(nonce); encodedData = ByteUtil.INSTANCE.getBytesFromInt(nonce);
for (AlertConfiguration config : configurations) { for (AlertConfiguration config : configurations) {
encodedData = ByteUtil.concat(encodedData, config.getRawData()); encodedData = ByteUtil.INSTANCE.concat(encodedData, config.getRawData());
} }
} }

View file

@ -4,7 +4,7 @@ import androidx.annotation.NonNull;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.NonceResyncableMessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.NonceResyncableMessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class DeactivatePodCommand extends NonceResyncableMessageBlock { public class DeactivatePodCommand extends NonceResyncableMessageBlock {
private int nonce; private int nonce;
@ -20,7 +20,7 @@ public class DeactivatePodCommand extends NonceResyncableMessageBlock {
} }
private void encode() { private void encode() {
encodedData = ByteUtil.getBytesFromInt(nonce); encodedData = ByteUtil.INSTANCE.getBytesFromInt(nonce);
} }
@Override @Override

View file

@ -4,7 +4,7 @@ import androidx.annotation.NonNull;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.NonceResyncableMessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.NonceResyncableMessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class FaultConfigCommand extends NonceResyncableMessageBlock { public class FaultConfigCommand extends NonceResyncableMessageBlock {
private final byte tab5sub16; private final byte tab5sub16;
@ -20,9 +20,9 @@ public class FaultConfigCommand extends NonceResyncableMessageBlock {
} }
private void encode() { private void encode() {
encodedData = ByteUtil.getBytesFromInt(nonce); encodedData = ByteUtil.INSTANCE.getBytesFromInt(nonce);
encodedData = ByteUtil.concat(encodedData, tab5sub16); encodedData = ByteUtil.INSTANCE.concat(encodedData, tab5sub16);
encodedData = ByteUtil.concat(encodedData, tab5sub17); encodedData = ByteUtil.INSTANCE.concat(encodedData, tab5sub17);
} }
@Override @Override

View file

@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.sc
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BolusDeliverySchedule; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BolusDeliverySchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.DeliverySchedule; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.DeliverySchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.TempBasalDeliverySchedule; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.TempBasalDeliverySchedule;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class SetInsulinScheduleCommand extends NonceResyncableMessageBlock { public class SetInsulinScheduleCommand extends NonceResyncableMessageBlock {
@ -65,10 +65,10 @@ public class SetInsulinScheduleCommand extends NonceResyncableMessageBlock {
} }
private void encode() { private void encode() {
encodedData = ByteUtil.getBytesFromInt(nonce); encodedData = ByteUtil.INSTANCE.getBytesFromInt(nonce);
encodedData = ByteUtil.concat(encodedData, schedule.getType().getValue()); encodedData = ByteUtil.INSTANCE.concat(encodedData, schedule.getType().getValue());
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt16(schedule.getChecksum())); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt16(schedule.getChecksum()));
encodedData = ByteUtil.concat(encodedData, schedule.getRawData()); encodedData = ByteUtil.INSTANCE.concat(encodedData, schedule.getRawData());
} }
@Override @Override

View file

@ -4,7 +4,7 @@ import org.joda.time.DateTime;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.MessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class SetupPodCommand extends MessageBlock { public class SetupPodCommand extends MessageBlock {
@ -30,8 +30,8 @@ public class SetupPodCommand extends MessageBlock {
private void encode() { private void encode() {
encodedData = new byte[0]; encodedData = new byte[0];
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt(address)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt(address));
encodedData = ByteUtil.concat(encodedData, new byte[]{ // encodedData = ByteUtil.INSTANCE.concat(encodedData, new byte[]{ //
(byte) 0x14, // unknown (byte) 0x14, // unknown
PACKET_TIMEOUT_LIMIT, // PACKET_TIMEOUT_LIMIT, //
(byte) date.monthOfYear().get(), // (byte) date.monthOfYear().get(), //
@ -40,8 +40,8 @@ public class SetupPodCommand extends MessageBlock {
(byte) date.hourOfDay().get(), // (byte) date.hourOfDay().get(), //
(byte) date.minuteOfHour().get() // (byte) date.minuteOfHour().get() //
}); });
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt(lot)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt(lot));
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt(tid)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt(tid));
} }
@Override @Override

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.RateEntry; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.RateEntry;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class TempBasalExtraCommand extends MessageBlock { public class TempBasalExtraCommand extends MessageBlock {
private final boolean acknowledgementBeep; private final boolean acknowledgementBeep;
@ -55,15 +55,15 @@ public class TempBasalExtraCommand extends MessageBlock {
(byte) 0x00 (byte) 0x00
}; };
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt16((int) Math.round(remainingPulses * 10))); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt16((int) Math.round(remainingPulses * 10)));
if (remainingPulses == 0) { if (remainingPulses == 0) {
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt((int) (delayUntilNextPulse * 1000 * 100) * 10)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt((int) (delayUntilNextPulse * 1000 * 100) * 10));
} else { } else {
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt((int) (delayUntilNextPulse * 1000 * 100))); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt((int) (delayUntilNextPulse * 1000 * 100)));
} }
for (RateEntry entry : rateEntries) { for (RateEntry entry : rateEntries) {
encodedData = ByteUtil.concat(encodedData, entry.getRawData()); encodedData = ByteUtil.INSTANCE.concat(encodedData, entry.getRawData());
} }
} }

View file

@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class ErrorResponse extends MessageBlock { public class ErrorResponse extends MessageBlock {
public static final byte ERROR_RESPONSE_CODE_BAD_NONCE = (byte) 0x14; public static final byte ERROR_RESPONSE_CODE_BAD_NONCE = (byte) 0x14;
@ -24,12 +24,12 @@ public class ErrorResponse extends MessageBlock {
if (encodedData.length < MESSAGE_LENGTH) { if (encodedData.length < MESSAGE_LENGTH) {
throw new IllegalArgumentException("Not enough data"); throw new IllegalArgumentException("Not enough data");
} }
this.encodedData = ByteUtil.substring(encodedData, 2, MESSAGE_LENGTH - 2); this.encodedData = ByteUtil.INSTANCE.substring(encodedData, 2, MESSAGE_LENGTH - 2);
errorResponseCode = encodedData[2]; errorResponseCode = encodedData[2];
if (errorResponseCode == ERROR_RESPONSE_CODE_BAD_NONCE) { if (errorResponseCode == ERROR_RESPONSE_CODE_BAD_NONCE) {
nonceSearchKey = ByteUtil.makeUnsignedShort(encodedData[3], encodedData[4]); nonceSearchKey = ByteUtil.INSTANCE.makeUnsignedShort(encodedData[3], encodedData[4]);
faultEventCode = null; faultEventCode = null;
podProgressStatus = null; podProgressStatus = null;

View file

@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.De
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class StatusResponse extends MessageBlock implements StatusUpdatableResponse { public class StatusResponse extends MessageBlock implements StatusUpdatableResponse {
private static final int MESSAGE_LENGTH = 10; private static final int MESSAGE_LENGTH = 10;
@ -30,25 +30,25 @@ public class StatusResponse extends MessageBlock implements StatusUpdatableRespo
if (encodedData.length < MESSAGE_LENGTH) { if (encodedData.length < MESSAGE_LENGTH) {
throw new IllegalArgumentException("Not enough data"); throw new IllegalArgumentException("Not enough data");
} }
this.encodedData = ByteUtil.substring(encodedData, 1, MESSAGE_LENGTH - 1); this.encodedData = ByteUtil.INSTANCE.substring(encodedData, 1, MESSAGE_LENGTH - 1);
deliveryStatus = DeliveryStatus.fromByte((byte) (ByteUtil.convertUnsignedByteToInt(encodedData[1]) >>> 4)); deliveryStatus = DeliveryStatus.fromByte((byte) (ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[1]) >>> 4));
podProgressStatus = PodProgressStatus.fromByte((byte) (encodedData[1] & 0x0F)); podProgressStatus = PodProgressStatus.fromByte((byte) (encodedData[1] & 0x0F));
int minutes = ((encodedData[7] & 0x7F) << 6) | ((encodedData[8] & 0xFC) >>> 2); int minutes = ((encodedData[7] & 0x7F) << 6) | ((encodedData[8] & 0xFC) >>> 2);
timeActive = Duration.standardMinutes(minutes); timeActive = Duration.standardMinutes(minutes);
int highInsulinBits = (encodedData[2] & 0xF) << 9; int highInsulinBits = (encodedData[2] & 0xF) << 9;
int middleInsulinBits = ByteUtil.convertUnsignedByteToInt(encodedData[3]) << 1; int middleInsulinBits = ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[3]) << 1;
int lowInsulinBits = ByteUtil.convertUnsignedByteToInt(encodedData[4]) >>> 7; int lowInsulinBits = ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[4]) >>> 7;
ticksDelivered = (highInsulinBits | middleInsulinBits | lowInsulinBits); ticksDelivered = (highInsulinBits | middleInsulinBits | lowInsulinBits);
insulinDelivered = OmnipodConstants.POD_PULSE_SIZE * ticksDelivered; insulinDelivered = OmnipodConstants.POD_PULSE_SIZE * ticksDelivered;
podMessageCounter = (byte) ((encodedData[4] >>> 3) & 0xf); podMessageCounter = (byte) ((encodedData[4] >>> 3) & 0xf);
bolusNotDelivered = OmnipodConstants.POD_PULSE_SIZE * (((encodedData[4] & 0x03) << 8) | ByteUtil.convertUnsignedByteToInt(encodedData[5])); bolusNotDelivered = OmnipodConstants.POD_PULSE_SIZE * (((encodedData[4] & 0x03) << 8) | ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[5]));
unacknowledgedAlerts = new AlertSet((byte) (((encodedData[6] & 0x7f) << 1) | (ByteUtil.convertUnsignedByteToInt(encodedData[7]) >>> 7))); unacknowledgedAlerts = new AlertSet((byte) (((encodedData[6] & 0x7f) << 1) | (ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[7]) >>> 7)));
double reservoirValue = (((encodedData[8] & 0x3) << 8) + ByteUtil.convertUnsignedByteToInt(encodedData[9])) * OmnipodConstants.POD_PULSE_SIZE; double reservoirValue = (((encodedData[8] & 0x3) << 8) + ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[9])) * OmnipodConstants.POD_PULSE_SIZE;
if (reservoirValue > OmnipodConstants.MAX_RESERVOIR_READING) { if (reservoirValue > OmnipodConstants.MAX_RESERVOIR_READING) {
reservoirLevel = null; reservoirLevel = null;
} else { } else {
@ -120,7 +120,7 @@ public class StatusResponse extends MessageBlock implements StatusUpdatableRespo
", bolusNotDelivered=" + bolusNotDelivered + ", bolusNotDelivered=" + bolusNotDelivered +
", podMessageCounter=" + podMessageCounter + ", podMessageCounter=" + podMessageCounter +
", unacknowledgedAlerts=" + unacknowledgedAlerts + ", unacknowledgedAlerts=" + unacknowledgedAlerts +
", encodedData=" + ByteUtil.shortHexStringWithoutSpaces(encodedData) + ", encodedData=" + ByteUtil.INSTANCE.shortHexStringWithoutSpaces(encodedData) +
'}'; '}';
} }
} }

View file

@ -4,7 +4,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FirmwareVersion; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FirmwareVersion;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class VersionResponse extends MessageBlock { public class VersionResponse extends MessageBlock {
private static final int ASSIGN_ADDRESS_VERSION_RESPONSE_LENGTH = 0x15; private static final int ASSIGN_ADDRESS_VERSION_RESPONSE_LENGTH = 0x15;
@ -15,38 +15,38 @@ public class VersionResponse extends MessageBlock {
private final FirmwareVersion piVersion; private final FirmwareVersion piVersion;
private final int lot; private final int lot;
private final int tid; private final int tid;
private final int address;
private Byte gain; // Only in the assign address version response private Byte gain; // Only in the assign address version response
private Byte rssi; // Only in the assign address version response private Byte rssi; // Only in the assign address version response
private final int address;
public VersionResponse(byte[] data) { public VersionResponse(byte[] data) {
int length = ByteUtil.convertUnsignedByteToInt(data[1]); int length = ByteUtil.INSTANCE.convertUnsignedByteToInt(data[1]);
this.encodedData = ByteUtil.substring(data, 2, length); this.encodedData = ByteUtil.INSTANCE.substring(data, 2, length);
switch (length) { switch (length) {
case ASSIGN_ADDRESS_VERSION_RESPONSE_LENGTH: case ASSIGN_ADDRESS_VERSION_RESPONSE_LENGTH:
podProgressStatus = PodProgressStatus.fromByte(data[9]); podProgressStatus = PodProgressStatus.fromByte(data[9]);
pmVersion = new FirmwareVersion(data[2], data[3], data[4]); pmVersion = new FirmwareVersion(data[2], data[3], data[4]);
piVersion = new FirmwareVersion(data[5], data[6], data[7]); piVersion = new FirmwareVersion(data[5], data[6], data[7]);
lot = ByteUtil.toInt((int) data[10], (int) data[11], lot = ByteUtil.INSTANCE.toInt((int) data[10], (int) data[11],
(int) data[12], (int) data[13], ByteUtil.BitConversion.BIG_ENDIAN); (int) data[12], (int) data[13], ByteUtil.BitConversion.BIG_ENDIAN);
tid = ByteUtil.toInt((int) data[14], (int) data[15], tid = ByteUtil.INSTANCE.toInt((int) data[14], (int) data[15],
(int) data[16], (int) data[17], ByteUtil.BitConversion.BIG_ENDIAN); (int) data[16], (int) data[17], ByteUtil.BitConversion.BIG_ENDIAN);
gain = (byte) ((data[18] & 0xc0) >>> 6); gain = (byte) ((data[18] & 0xc0) >>> 6);
rssi = (byte) (data[18] & 0x3f); rssi = (byte) (data[18] & 0x3f);
address = ByteUtil.toInt((int) data[19], (int) data[20], address = ByteUtil.INSTANCE.toInt((int) data[19], (int) data[20],
(int) data[21], (int) data[22], ByteUtil.BitConversion.BIG_ENDIAN); (int) data[21], (int) data[22], ByteUtil.BitConversion.BIG_ENDIAN);
break; break;
case SETUP_POD_VERSION_RESPONSE_LENGTH: case SETUP_POD_VERSION_RESPONSE_LENGTH:
podProgressStatus = PodProgressStatus.fromByte(data[16]); podProgressStatus = PodProgressStatus.fromByte(data[16]);
pmVersion = new FirmwareVersion(data[9], data[10], data[11]); pmVersion = new FirmwareVersion(data[9], data[10], data[11]);
piVersion = new FirmwareVersion(data[12], data[13], data[14]); piVersion = new FirmwareVersion(data[12], data[13], data[14]);
lot = ByteUtil.toInt((int) data[17], (int) data[18], lot = ByteUtil.INSTANCE.toInt((int) data[17], (int) data[18],
(int) data[19], (int) data[20], ByteUtil.BitConversion.BIG_ENDIAN); (int) data[19], (int) data[20], ByteUtil.BitConversion.BIG_ENDIAN);
tid = ByteUtil.toInt((int) data[21], (int) data[22], tid = ByteUtil.INSTANCE.toInt((int) data[21], (int) data[22],
(int) data[23], (int) data[24], ByteUtil.BitConversion.BIG_ENDIAN); (int) data[23], (int) data[24], ByteUtil.BitConversion.BIG_ENDIAN);
address = ByteUtil.toInt((int) data[25], (int) data[26], address = ByteUtil.INSTANCE.toInt((int) data[25], (int) data[26],
(int) data[27], (int) data[28], ByteUtil.BitConversion.BIG_ENDIAN); (int) data[27], (int) data[28], ByteUtil.BitConversion.BIG_ENDIAN);
break; break;
default: default:

View file

@ -8,7 +8,7 @@ import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class PodInfoActiveAlerts extends PodInfo { public class PodInfoActiveAlerts extends PodInfo {
private static final int MINIMUM_MESSAGE_LENGTH = 11; private static final int MINIMUM_MESSAGE_LENGTH = 11;
@ -23,13 +23,13 @@ public class PodInfoActiveAlerts extends PodInfo {
throw new IllegalArgumentException("Not enough data"); throw new IllegalArgumentException("Not enough data");
} }
word278 = ByteUtil.substring(encodedData, 1, 2); word278 = ByteUtil.INSTANCE.substring(encodedData, 1, 2);
alertActivations = new ArrayList<>(); alertActivations = new ArrayList<>();
for (AlertSlot alertSlot : AlertSlot.values()) { for (AlertSlot alertSlot : AlertSlot.values()) {
int valueHighBits = ByteUtil.convertUnsignedByteToInt(encodedData[3 + alertSlot.getValue() * 2]); int valueHighBits = ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[3 + alertSlot.getValue() * 2]);
int valueLowBits = ByteUtil.convertUnsignedByteToInt(encodedData[4 + alertSlot.getValue() * 2]); int valueLowBits = ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[4 + alertSlot.getValue() * 2]);
int value = (valueHighBits << 8) | valueLowBits; int value = (valueHighBits << 8) | valueLowBits;
if (value != 0) { if (value != 0) {
alertActivations.add(new AlertActivation(alertSlot, value)); alertActivations.add(new AlertActivation(alertSlot, value));
@ -53,7 +53,7 @@ public class PodInfoActiveAlerts extends PodInfo {
@Override @Override
public String toString() { public String toString() {
return "PodInfoActiveAlerts{" + return "PodInfoActiveAlerts{" +
"word278=" + ByteUtil.shortHexString(word278) + "word278=" + ByteUtil.INSTANCE.shortHexString(word278) +
", alertActivations=" + alertActivations + ", alertActivations=" + alertActivations +
'}'; '}';
} }

View file

@ -8,7 +8,7 @@ import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class PodInfoDataLog extends PodInfo { public class PodInfoDataLog extends PodInfo {
private static final int MINIMUM_MESSAGE_LENGTH = 8; private static final int MINIMUM_MESSAGE_LENGTH = 8;
@ -27,8 +27,8 @@ public class PodInfoDataLog extends PodInfo {
} }
faultEventCode = FaultEventCode.fromByte(encodedData[1]); faultEventCode = FaultEventCode.fromByte(encodedData[1]);
timeFaultEvent = Duration.standardMinutes(ByteUtil.toInt(encodedData[2], encodedData[3])); timeFaultEvent = Duration.standardMinutes(ByteUtil.INSTANCE.toInt(encodedData[2], encodedData[3]));
timeSinceActivation = Duration.standardMinutes(ByteUtil.toInt(encodedData[4], encodedData[5])); timeSinceActivation = Duration.standardMinutes(ByteUtil.INSTANCE.toInt(encodedData[4], encodedData[5]));
dataChunkSize = encodedData[6]; dataChunkSize = encodedData[6];
maximumNumberOfDwords = encodedData[7]; maximumNumberOfDwords = encodedData[7];
@ -36,7 +36,7 @@ public class PodInfoDataLog extends PodInfo {
int numberOfDwords = (bodyLength - 8) / 4; int numberOfDwords = (bodyLength - 8) / 4;
for (int i = 0; i < numberOfDwords; i++) { for (int i = 0; i < numberOfDwords; i++) {
dwords.add(ByteUtil.substring(encodedData, 8 + (4 * i), 4)); dwords.add(ByteUtil.INSTANCE.substring(encodedData, 8 + (4 * i), 4));
} }
} }

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Fa
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class PodInfoDetailedStatus extends PodInfo implements StatusUpdatableResponse { public class PodInfoDetailedStatus extends PodInfo implements StatusUpdatableResponse {
private static final int MINIMUM_MESSAGE_LENGTH = 21; private static final int MINIMUM_MESSAGE_LENGTH = 21;
@ -42,13 +42,13 @@ public class PodInfoDetailedStatus extends PodInfo implements StatusUpdatableRes
podProgressStatus = PodProgressStatus.fromByte(encodedData[1]); podProgressStatus = PodProgressStatus.fromByte(encodedData[1]);
deliveryStatus = DeliveryStatus.fromByte(encodedData[2]); deliveryStatus = DeliveryStatus.fromByte(encodedData[2]);
bolusNotDelivered = OmnipodConstants.POD_PULSE_SIZE * ByteUtil.toInt(encodedData[3], encodedData[4]); bolusNotDelivered = OmnipodConstants.POD_PULSE_SIZE * ByteUtil.INSTANCE.toInt(encodedData[3], encodedData[4]);
podMessageCounter = encodedData[5]; podMessageCounter = encodedData[5];
ticksDelivered = ByteUtil.toInt(encodedData[6], encodedData[7]); ticksDelivered = ByteUtil.INSTANCE.toInt(encodedData[6], encodedData[7]);
insulinDelivered = OmnipodConstants.POD_PULSE_SIZE * ticksDelivered; insulinDelivered = OmnipodConstants.POD_PULSE_SIZE * ticksDelivered;
faultEventCode = FaultEventCode.fromByte(encodedData[8]); faultEventCode = FaultEventCode.fromByte(encodedData[8]);
int minutesSinceActivation = ByteUtil.toInt(encodedData[9], encodedData[10]); int minutesSinceActivation = ByteUtil.INSTANCE.toInt(encodedData[9], encodedData[10]);
if (minutesSinceActivation == 0xffff) { if (minutesSinceActivation == 0xffff) {
faultEventTime = null; faultEventTime = null;
} else { } else {
@ -56,14 +56,14 @@ public class PodInfoDetailedStatus extends PodInfo implements StatusUpdatableRes
} }
double reservoirValue = ((encodedData[11] & 0x03) << 8) + double reservoirValue = ((encodedData[11] & 0x03) << 8) +
ByteUtil.convertUnsignedByteToInt(encodedData[12]) * OmnipodConstants.POD_PULSE_SIZE; ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[12]) * OmnipodConstants.POD_PULSE_SIZE;
if (reservoirValue > OmnipodConstants.MAX_RESERVOIR_READING) { if (reservoirValue > OmnipodConstants.MAX_RESERVOIR_READING) {
reservoirLevel = null; reservoirLevel = null;
} else { } else {
reservoirLevel = reservoirValue; reservoirLevel = reservoirValue;
} }
int minutesActive = ByteUtil.toInt(encodedData[13], encodedData[14]); int minutesActive = ByteUtil.INSTANCE.toInt(encodedData[13], encodedData[14]);
timeActive = Duration.standardMinutes(minutesActive); timeActive = Duration.standardMinutes(minutesActive);
unacknowledgedAlerts = new AlertSet(encodedData[15]); unacknowledgedAlerts = new AlertSet(encodedData[15]);
@ -74,14 +74,14 @@ public class PodInfoDetailedStatus extends PodInfo implements StatusUpdatableRes
} else { } else {
errorEventInfo = ErrorEventInfo.fromByte(rawErrorEventInfo); errorEventInfo = ErrorEventInfo.fromByte(rawErrorEventInfo);
} }
receiverLowGain = (byte) (ByteUtil.convertUnsignedByteToInt(encodedData[18]) >>> 6); receiverLowGain = (byte) (ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[18]) >>> 6);
radioRSSI = (byte) (encodedData[18] & 0x3f); radioRSSI = (byte) (encodedData[18] & 0x3f);
if (ByteUtil.convertUnsignedByteToInt(encodedData[19]) == 0xff) { // this byte is not valid (no fault has occurred) if (ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[19]) == 0xff) { // this byte is not valid (no fault has occurred)
previousPodProgressStatus = null; previousPodProgressStatus = null;
} else { } else {
previousPodProgressStatus = PodProgressStatus.fromByte((byte) (encodedData[19] & 0x0f)); previousPodProgressStatus = PodProgressStatus.fromByte((byte) (encodedData[19] & 0x0f));
} }
unknownValue = ByteUtil.substring(encodedData, 20, 2); unknownValue = ByteUtil.INSTANCE.substring(encodedData, 20, 2);
} }
@Override @Override
@ -183,7 +183,7 @@ public class PodInfoDetailedStatus extends PodInfo implements StatusUpdatableRes
", receiverLowGain=" + receiverLowGain + ", receiverLowGain=" + receiverLowGain +
", radioRSSI=" + radioRSSI + ", radioRSSI=" + radioRSSI +
", previousPodProgressStatus=" + previousPodProgressStatus + ", previousPodProgressStatus=" + previousPodProgressStatus +
", unknownValue=" + ByteUtil.shortHexString(unknownValue) + ", unknownValue=" + ByteUtil.INSTANCE.shortHexString(unknownValue) +
'}'; '}';
} }
} }

View file

@ -7,7 +7,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class PodInfoOlderPulseLog extends PodInfo { public class PodInfoOlderPulseLog extends PodInfo {
private static final int MINIMUM_MESSAGE_LENGTH = 3; private static final int MINIMUM_MESSAGE_LENGTH = 3;
@ -23,9 +23,9 @@ public class PodInfoOlderPulseLog extends PodInfo {
dwords = new ArrayList<>(); dwords = new ArrayList<>();
int numberOfDwordLogEntries = ByteUtil.toInt(encodedData[1], encodedData[2]); int numberOfDwordLogEntries = ByteUtil.INSTANCE.toInt(encodedData[1], encodedData[2]);
for (int i = 0; numberOfDwordLogEntries > i; i++) { for (int i = 0; numberOfDwordLogEntries > i; i++) {
byte[] dword = ByteUtil.substring(encodedData, 3 + (4 * i), 4); byte[] dword = ByteUtil.INSTANCE.substring(encodedData, 3 + (4 * i), 4);
dwords.add(dword); dwords.add(dword);
} }
} }
@ -46,7 +46,7 @@ public class PodInfoOlderPulseLog extends PodInfo {
List<String> hexDwords = new ArrayList<>(); List<String> hexDwords = new ArrayList<>();
for (byte[] dword : dwords) { for (byte[] dword : dwords) {
hexDwords.add(ByteUtil.shortHexStringWithoutSpaces(dword)); hexDwords.add(ByteUtil.INSTANCE.shortHexStringWithoutSpaces(dword));
} }
out += TextUtils.join(", ", hexDwords); out += TextUtils.join(", ", hexDwords);
out += "]}"; out += "]}";

View file

@ -7,7 +7,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class PodInfoRecentPulseLog extends PodInfo { public class PodInfoRecentPulseLog extends PodInfo {
private static final int MINIMUM_MESSAGE_LENGTH = 3; private static final int MINIMUM_MESSAGE_LENGTH = 3;
@ -23,13 +23,13 @@ public class PodInfoRecentPulseLog extends PodInfo {
throw new IllegalArgumentException("Not enough data"); throw new IllegalArgumentException("Not enough data");
} }
lastEntryIndex = ByteUtil.toInt(encodedData[1], encodedData[2]); lastEntryIndex = ByteUtil.INSTANCE.toInt(encodedData[1], encodedData[2]);
dwords = new ArrayList<>(); dwords = new ArrayList<>();
int numberOfDwords = (bodyLength - 3) / 4; int numberOfDwords = (bodyLength - 3) / 4;
for (int i = 0; numberOfDwords > i; i++) { for (int i = 0; numberOfDwords > i; i++) {
byte[] dword = ByteUtil.substring(encodedData, 3 + (4 * i), 4); byte[] dword = ByteUtil.INSTANCE.substring(encodedData, 3 + (4 * i), 4);
dwords.add(dword); dwords.add(dword);
} }
} }
@ -55,7 +55,7 @@ public class PodInfoRecentPulseLog extends PodInfo {
List<String> hexDwords = new ArrayList<>(); List<String> hexDwords = new ArrayList<>();
for (byte[] dword : dwords) { for (byte[] dword : dwords) {
hexDwords.add(ByteUtil.shortHexStringWithoutSpaces(dword)); hexDwords.add(ByteUtil.INSTANCE.shortHexStringWithoutSpaces(dword));
} }
out += TextUtils.join(", ", hexDwords); out += TextUtils.join(", ", hexDwords);
out += "]}"; out += "]}";

View file

@ -3,16 +3,16 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communicatio
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.MessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.MessageBlockType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class PodInfoResponse extends MessageBlock { public class PodInfoResponse extends MessageBlock {
private final PodInfoType subType; private final PodInfoType subType;
private final PodInfo podInfo; private final PodInfo podInfo;
public PodInfoResponse(byte[] encodedData) { public PodInfoResponse(byte[] encodedData) {
int bodyLength = ByteUtil.convertUnsignedByteToInt(encodedData[1]); int bodyLength = ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[1]);
this.encodedData = ByteUtil.substring(encodedData, 2, bodyLength); this.encodedData = ByteUtil.INSTANCE.substring(encodedData, 2, bodyLength);
subType = PodInfoType.fromByte(encodedData[2]); subType = PodInfoType.fromByte(encodedData[2]);
podInfo = subType.decode(this.encodedData, bodyLength); podInfo = subType.decode(this.encodedData, bodyLength);
} }

View file

@ -4,7 +4,7 @@ import androidx.annotation.NonNull;
import org.joda.time.Duration; import org.joda.time.Duration;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class AlertConfiguration { public class AlertConfiguration {
private final AlertType alertType; private final AlertType alertType;
@ -66,14 +66,14 @@ public class AlertConfiguration {
if (alertTrigger instanceof UnitsRemainingAlertTrigger) { if (alertTrigger instanceof UnitsRemainingAlertTrigger) {
int ticks = (int) (((UnitsRemainingAlertTrigger) alertTrigger).getValue() / OmnipodConstants.POD_PULSE_SIZE / 2); int ticks = (int) (((UnitsRemainingAlertTrigger) alertTrigger).getValue() / OmnipodConstants.POD_PULSE_SIZE / 2);
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt16(ticks)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt16(ticks));
} else if (alertTrigger instanceof TimerAlertTrigger) { } else if (alertTrigger instanceof TimerAlertTrigger) {
int durationInMinutes = (int) ((TimerAlertTrigger) alertTrigger).getValue().getStandardMinutes(); int durationInMinutes = (int) ((TimerAlertTrigger) alertTrigger).getValue().getStandardMinutes();
encodedData = ByteUtil.concat(encodedData, ByteUtil.getBytesFromInt16(durationInMinutes)); encodedData = ByteUtil.INSTANCE.concat(encodedData, ByteUtil.INSTANCE.getBytesFromInt16(durationInMinutes));
} }
encodedData = ByteUtil.concat(encodedData, beepRepeat.getValue()); encodedData = ByteUtil.INSTANCE.concat(encodedData, beepRepeat.getValue());
encodedData = ByteUtil.concat(encodedData, beepType.getValue()); encodedData = ByteUtil.INSTANCE.concat(encodedData, beepType.getValue());
return encodedData; return encodedData;
} }

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition; package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public final class ErrorEventInfo { public final class ErrorEventInfo {
private final boolean insulinStateTableCorruption; private final boolean insulinStateTableCorruption;
@ -16,7 +16,7 @@ public final class ErrorEventInfo {
} }
public static ErrorEventInfo fromByte(byte faultEventInfo) { public static ErrorEventInfo fromByte(byte faultEventInfo) {
int loggedFaultEventInfo = ByteUtil.convertUnsignedByteToInt(faultEventInfo); int loggedFaultEventInfo = ByteUtil.INSTANCE.convertUnsignedByteToInt(faultEventInfo);
boolean insulinStateTableCorruption = (loggedFaultEventInfo & 0x80) == 0x80; boolean insulinStateTableCorruption = (loggedFaultEventInfo & 0x80) == 0x80;
byte internalVariable = (byte) ((loggedFaultEventInfo >>> 5) & 0x03); byte internalVariable = (byte) ((loggedFaultEventInfo >>> 5) & 0x03);
boolean immediateBolusInProgress = (loggedFaultEventInfo & 0x10) == 0x10; boolean immediateBolusInProgress = (loggedFaultEventInfo & 0x10) == 0x10;

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.s
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class BasalDeliverySchedule extends DeliverySchedule implements IRawRepresentable { public class BasalDeliverySchedule extends DeliverySchedule implements IRawRepresentable {
@ -23,11 +23,11 @@ public class BasalDeliverySchedule extends DeliverySchedule implements IRawRepre
@Override @Override
public byte[] getRawData() { public byte[] getRawData() {
byte[] rawData = new byte[0]; byte[] rawData = new byte[0];
rawData = ByteUtil.concat(rawData, currentSegment); rawData = ByteUtil.INSTANCE.concat(rawData, currentSegment);
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt16(secondsRemaining << 3)); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt16(secondsRemaining << 3));
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt16(pulsesRemaining)); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt16(pulsesRemaining));
for (BasalTableEntry entry : basalTable.getEntries()) { for (BasalTableEntry entry : basalTable.getEntries()) {
rawData = ByteUtil.concat(rawData, entry.getRawData()); rawData = ByteUtil.INSTANCE.concat(rawData, entry.getRawData());
} }
return rawData; return rawData;
} }
@ -42,7 +42,7 @@ public class BasalDeliverySchedule extends DeliverySchedule implements IRawRepre
int checksum = 0; int checksum = 0;
byte[] rawData = getRawData(); byte[] rawData = getRawData();
for (int i = 0; i < rawData.length && i < 5; i++) { for (int i = 0; i < rawData.length && i < 5; i++) {
checksum += ByteUtil.convertUnsignedByteToInt(rawData[i]); checksum += ByteUtil.INSTANCE.convertUnsignedByteToInt(rawData[i]);
} }
for (BasalTableEntry entry : basalTable.getEntries()) { for (BasalTableEntry entry : basalTable.getEntries()) {
checksum += entry.getChecksum(); checksum += entry.getChecksum();

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.s
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class BasalTableEntry implements IRawRepresentable { public class BasalTableEntry implements IRawRepresentable {
@ -28,7 +28,7 @@ public class BasalTableEntry implements IRawRepresentable {
} }
public int getChecksum() { public int getChecksum() {
int checksumPerSegment = ByteUtil.convertUnsignedByteToInt((byte) pulses) + (pulses >>> 8); int checksumPerSegment = ByteUtil.INSTANCE.convertUnsignedByteToInt((byte) pulses) + (pulses >>> 8);
return (checksumPerSegment * segments + (alternateSegmentPulse ? segments / 2 : 0)); return (checksumPerSegment * segments + (alternateSegmentPulse ? segments / 2 : 0));
} }

View file

@ -6,7 +6,7 @@ import org.joda.time.Duration;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class BolusDeliverySchedule extends DeliverySchedule implements IRawRepresentable { public class BolusDeliverySchedule extends DeliverySchedule implements IRawRepresentable {
@ -31,9 +31,9 @@ public class BolusDeliverySchedule extends DeliverySchedule implements IRawRepre
int multiplier = (int) timeBetweenPulses.getStandardSeconds() * 8; int multiplier = (int) timeBetweenPulses.getStandardSeconds() * 8;
int fieldA = pulseCount * multiplier; int fieldA = pulseCount * multiplier;
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt16(fieldA)); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt16(fieldA));
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt16(pulseCount)); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt16(pulseCount));
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt16(pulseCount)); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt16(pulseCount));
return rawData; return rawData;
} }
@ -47,7 +47,7 @@ public class BolusDeliverySchedule extends DeliverySchedule implements IRawRepre
int checksum = 0; int checksum = 0;
byte[] rawData = getRawData(); byte[] rawData = getRawData();
for (int i = 0; i < rawData.length && i < 7; i++) { for (int i = 0; i < rawData.length && i < 7; i++) {
checksum += ByteUtil.convertUnsignedByteToInt(rawData[i]); checksum += ByteUtil.INSTANCE.convertUnsignedByteToInt(rawData[i]);
} }
return checksum; return checksum;
} }

View file

@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.s
import static info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants.BASAL_STEP_DURATION; import static info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants.BASAL_STEP_DURATION;
import androidx.annotation.NonNull;
import org.joda.time.Duration; import org.joda.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
@ -9,7 +11,7 @@ import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class RateEntry implements IRawRepresentable { public class RateEntry implements IRawRepresentable {
@ -67,16 +69,16 @@ public class RateEntry implements IRawRepresentable {
@Override @Override
public byte[] getRawData() { public byte[] getRawData() {
byte[] rawData = new byte[0]; byte[] rawData = new byte[0];
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt16((int) Math.round(totalPulses * 10))); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt16((int) Math.round(totalPulses * 10)));
if (totalPulses == 0) { if (totalPulses == 0) {
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt((int) (delayBetweenPulsesInSeconds * 1000 * 1000))); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt((int) (delayBetweenPulsesInSeconds * 1000 * 1000)));
} else { } else {
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt((int) (delayBetweenPulsesInSeconds * 1000 * 100))); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt((int) (delayBetweenPulsesInSeconds * 1000 * 100)));
} }
return rawData; return rawData;
} }
@Override @NonNull @Override
public String toString() { public String toString() {
return "RateEntry{" + return "RateEntry{" +
"totalPulses=" + totalPulses + "totalPulses=" + totalPulses +

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule; package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.IRawRepresentable;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class TempBasalDeliverySchedule extends DeliverySchedule implements IRawRepresentable { public class TempBasalDeliverySchedule extends DeliverySchedule implements IRawRepresentable {
@ -18,11 +18,11 @@ public class TempBasalDeliverySchedule extends DeliverySchedule implements IRawR
@Override @Override
public byte[] getRawData() { public byte[] getRawData() {
byte[] rawData = new byte[0]; byte[] rawData = new byte[0];
rawData = ByteUtil.concat(rawData, basalTable.numSegments()); rawData = ByteUtil.INSTANCE.concat(rawData, basalTable.numSegments());
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt16(secondsRemaining << 3)); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt16(secondsRemaining << 3));
rawData = ByteUtil.concat(rawData, ByteUtil.getBytesFromInt16(firstSegmentPulses)); rawData = ByteUtil.INSTANCE.concat(rawData, ByteUtil.INSTANCE.getBytesFromInt16(firstSegmentPulses));
for (BasalTableEntry entry : basalTable.getEntries()) { for (BasalTableEntry entry : basalTable.getEntries()) {
rawData = ByteUtil.concat(rawData, entry.getRawData()); rawData = ByteUtil.INSTANCE.concat(rawData, entry.getRawData());
} }
return rawData; return rawData;
} }
@ -37,7 +37,7 @@ public class TempBasalDeliverySchedule extends DeliverySchedule implements IRawR
int checksum = 0; int checksum = 0;
byte[] rawData = getRawData(); byte[] rawData = getRawData();
for (int i = 0; i < rawData.length && i < 5; i++) { for (int i = 0; i < rawData.length && i < 5; i++) {
checksum += ByteUtil.convertUnsignedByteToInt(rawData[i]); checksum += ByteUtil.INSTANCE.convertUnsignedByteToInt(rawData[i]);
} }
for (BasalTableEntry entry : basalTable.getEntries()) { for (BasalTableEntry entry : basalTable.getEntries()) {
checksum += entry.getChecksum(); checksum += entry.getChecksum();

View file

@ -1,12 +1,12 @@
package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception; package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class NotEnoughDataException extends OmnipodException { public class NotEnoughDataException extends OmnipodException {
private final byte[] data; private final byte[] data;
public NotEnoughDataException(byte[] data) { public NotEnoughDataException(byte[] data) {
super("Not enough data: " + ByteUtil.shortHexString(data), false); super("Not enough data: " + ByteUtil.INSTANCE.shortHexString(data), false);
this.data = data; this.data = data;
} }

View file

@ -70,7 +70,7 @@ import info.nightscout.interfaces.pump.PumpSync;
import info.nightscout.interfaces.pump.defs.PumpType; import info.nightscout.interfaces.pump.defs.PumpType;
import info.nightscout.interfaces.ui.UiInteraction; import info.nightscout.interfaces.ui.UiInteraction;
import info.nightscout.pump.common.defs.TempBasalPair; import info.nightscout.pump.common.defs.TempBasalPair;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import info.nightscout.rx.AapsSchedulers; import info.nightscout.rx.AapsSchedulers;
import info.nightscout.rx.bus.RxBus; import info.nightscout.rx.bus.RxBus;
import info.nightscout.rx.events.Event; import info.nightscout.rx.events.Event;
@ -150,6 +150,23 @@ public class AapsOmnipodErosManager {
reloadSettings(); reloadSettings();
} }
public static BasalSchedule mapProfileToBasalSchedule(Profile profile) {
if (profile == null) {
throw new IllegalArgumentException("Profile can not be null");
}
Profile.ProfileValue[] basalValues = profile.getBasalValues();
if (basalValues == null) {
throw new IllegalArgumentException("Basal values can not be null");
}
List<BasalScheduleEntry> entries = new ArrayList<>();
for (Profile.ProfileValue basalValue : basalValues) {
entries.add(new BasalScheduleEntry(PumpType.OMNIPOD_EROS.determineCorrectBasalSize(basalValue.getValue()),
Duration.standardSeconds(basalValue.getTimeAsSeconds())));
}
return new BasalSchedule(entries);
}
public void reloadSettings() { public void reloadSettings() {
basalBeepsEnabled = sp.getBoolean(OmnipodErosStorageKeys.Preferences.BASAL_BEEPS_ENABLED, true); basalBeepsEnabled = sp.getBoolean(OmnipodErosStorageKeys.Preferences.BASAL_BEEPS_ENABLED, true);
bolusBeepsEnabled = sp.getBoolean(OmnipodErosStorageKeys.Preferences.BOLUS_BEEPS_ENABLED, true); bolusBeepsEnabled = sp.getBoolean(OmnipodErosStorageKeys.Preferences.BOLUS_BEEPS_ENABLED, true);
@ -251,7 +268,6 @@ public class AapsOmnipodErosManager {
return new PumpEnactResult(injector).success(true).enacted(false); return new PumpEnactResult(injector).success(true).enacted(false);
} }
public PumpEnactResult getPodStatus() { public PumpEnactResult getPodStatus() {
StatusResponse statusResponse; StatusResponse statusResponse;
@ -375,7 +391,7 @@ public class AapsOmnipodErosManager {
boolean beepsEnabled = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB ? isSmbBeepsEnabled() : isBolusBeepsEnabled(); boolean beepsEnabled = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB ? isSmbBeepsEnabled() : isBolusBeepsEnabled();
EventOverviewBolusProgress.INSTANCE.setT(new EventOverviewBolusProgress.Treatment(detailedBolusInfo.insulin, 0,detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB, detailedBolusInfo.getId())); EventOverviewBolusProgress.INSTANCE.setT(new EventOverviewBolusProgress.Treatment(detailedBolusInfo.insulin, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB, detailedBolusInfo.getId()));
Date bolusStarted; Date bolusStarted;
try { try {
@ -960,7 +976,7 @@ public class AapsOmnipodErosManager {
private String createPodFaultErrorMessage(FaultEventCode faultEventCode) { private String createPodFaultErrorMessage(FaultEventCode faultEventCode) {
return getStringResource(R.string.omnipod_eros_error_pod_fault, return getStringResource(R.string.omnipod_eros_error_pod_fault,
ByteUtil.convertUnsignedByteToInt(faultEventCode.getValue()), faultEventCode.name()); ByteUtil.INSTANCE.convertUnsignedByteToInt(faultEventCode.getValue()), faultEventCode.name());
} }
private void sendEvent(Event event) { private void sendEvent(Event event) {
@ -991,23 +1007,6 @@ public class AapsOmnipodErosManager {
return rh.gs(id, args); return rh.gs(id, args);
} }
public static BasalSchedule mapProfileToBasalSchedule(Profile profile) {
if (profile == null) {
throw new IllegalArgumentException("Profile can not be null");
}
Profile.ProfileValue[] basalValues = profile.getBasalValues();
if (basalValues == null) {
throw new IllegalArgumentException("Basal values can not be null");
}
List<BasalScheduleEntry> entries = new ArrayList<>();
for (Profile.ProfileValue basalValue : basalValues) {
entries.add(new BasalScheduleEntry(PumpType.OMNIPOD_EROS.determineCorrectBasalSize(basalValue.getValue()),
Duration.standardSeconds(basalValue.getTimeAsSeconds())));
}
return new BasalSchedule(entries);
}
private void uploadCareportalEvent(long date, DetailedBolusInfo.EventType event) { private void uploadCareportalEvent(long date, DetailedBolusInfo.EventType event) {
pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.OMNIPOD_EROS, Integer.toString(podStateManager.getAddress())); pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.OMNIPOD_EROS, Integer.toString(podStateManager.getAddress()));
} }

View file

@ -41,8 +41,8 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.Ril
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkUnexpectedException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkUnexpectedException;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkUnreachableException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkUnreachableException;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager;
import info.nightscout.pump.core.defs.PumpDeviceState; import info.nightscout.pump.common.defs.PumpDeviceState;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import info.nightscout.rx.logging.LTag; import info.nightscout.rx.logging.LTag;
/** /**
@ -230,7 +230,7 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication
byte[] encodedMessageInPacket = packet.getEncodedMessage(); byte[] encodedMessageInPacket = packet.getEncodedMessage();
// getting the data remaining to be sent // getting the data remaining to be sent
encodedMessage = ByteUtil.substring(encodedMessage, encodedMessageInPacket.length, encodedMessage.length - encodedMessageInPacket.length); encodedMessage = ByteUtil.INSTANCE.substring(encodedMessage, encodedMessageInPacket.length, encodedMessage.length - encodedMessageInPacket.length);
firstPacket = false; firstPacket = false;
try { try {
@ -257,7 +257,7 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication
byte[] receivedMessageData = response.getEncodedMessage(); byte[] receivedMessageData = response.getEncodedMessage();
while (receivedMessage == null) { while (receivedMessage == null) {
try { try {
aapsLogger.debug(LTag.PUMPBTCOMM, "Attempting to decode message: {}", ByteUtil.shortHexStringWithoutSpaces(receivedMessageData)); aapsLogger.debug(LTag.PUMPBTCOMM, "Attempting to decode message: {}", ByteUtil.INSTANCE.shortHexStringWithoutSpaces(receivedMessageData));
receivedMessage = OmnipodMessage.decodeMessage(receivedMessageData); receivedMessage = OmnipodMessage.decodeMessage(receivedMessageData);
if (receivedMessage.getAddress() != message.getAddress()) { if (receivedMessage.getAddress() != message.getAddress()) {
throw new IllegalMessageAddressException(message.getAddress(), receivedMessage.getAddress()); throw new IllegalMessageAddressException(message.getAddress(), receivedMessage.getAddress());
@ -276,7 +276,7 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication
if (conPacket.getPacketType() != PacketType.CON) { if (conPacket.getPacketType() != PacketType.CON) {
throw new IllegalPacketTypeException(PacketType.CON, conPacket.getPacketType()); throw new IllegalPacketTypeException(PacketType.CON, conPacket.getPacketType());
} }
receivedMessageData = ByteUtil.concat(receivedMessageData, conPacket.getEncodedMessage()); receivedMessageData = ByteUtil.INSTANCE.concat(receivedMessageData, conPacket.getEncodedMessage());
} }
} }
@ -305,7 +305,7 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication
if (messageAddress == null) { if (messageAddress == null) {
messageAddress = podStateManager.getAddress(); messageAddress = podStateManager.getAddress();
} }
return new OmnipodPacket(packetAddress, PacketType.ACK, podStateManager.getPacketNumber(), ByteUtil.getBytesFromInt(messageAddress)); return new OmnipodPacket(packetAddress, PacketType.ACK, podStateManager.getPacketNumber(), ByteUtil.INSTANCE.getBytesFromInt(messageAddress));
} }
private void ackUntilQuiet(ErosPodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { private void ackUntilQuiet(ErosPodStateManager podStateManager, Integer packetAddress, Integer messageAddress) {

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugi
import info.nightscout.androidaps.plugins.pump.omnipod.eros.R; import info.nightscout.androidaps.plugins.pump.omnipod.eros.R;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.AapsOmnipodUtil; import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.AapsOmnipodUtil;
import info.nightscout.pump.core.defs.PumpDeviceState; import info.nightscout.pump.common.defs.PumpDeviceState;
import info.nightscout.rx.logging.LTag; import info.nightscout.rx.logging.LTag;
@ -30,12 +30,10 @@ import info.nightscout.rx.logging.LTag;
public class RileyLinkOmnipodService extends RileyLinkService { public class RileyLinkOmnipodService extends RileyLinkService {
private static final String REGEX_MAC = "([\\da-fA-F]{1,2}(?::|$)){6}"; private static final String REGEX_MAC = "([\\da-fA-F]{1,2}(?::|$)){6}";
private final IBinder mBinder = new LocalBinder();
@Inject OmnipodErosPumpPlugin omnipodErosPumpPlugin; @Inject OmnipodErosPumpPlugin omnipodErosPumpPlugin;
@Inject AapsOmnipodUtil aapsOmnipodUtil; @Inject AapsOmnipodUtil aapsOmnipodUtil;
@Inject OmnipodRileyLinkCommunicationManager omnipodRileyLinkCommunicationManager; @Inject OmnipodRileyLinkCommunicationManager omnipodRileyLinkCommunicationManager;
private final IBinder mBinder = new LocalBinder();
private boolean rileyLinkAddressChanged = false; private boolean rileyLinkAddressChanged = false;
private boolean inPreInit = true; private boolean inPreInit = true;
private String rileyLinkAddress; private String rileyLinkAddress;
@ -89,18 +87,12 @@ public class RileyLinkOmnipodService extends RileyLinkService {
return errorDescription; return errorDescription;
} }
public class LocalBinder extends Binder {
public RileyLinkOmnipodService getServiceInstance() {
return RileyLinkOmnipodService.this;
}
}
/* private functions */
public boolean isInitialized() { public boolean isInitialized() {
return rileyLinkServiceData.getRileyLinkServiceState().isReady(); return rileyLinkServiceData.getRileyLinkServiceState().isReady();
} }
/* private functions */
@Override @Override
public boolean verifyConfiguration(boolean forceRileyLinkAddressRenewal) { public boolean verifyConfiguration(boolean forceRileyLinkAddressRenewal) {
try { try {
@ -153,4 +145,10 @@ public class RileyLinkOmnipodService extends RileyLinkService {
return reconfigureService(false); return reconfigureService(false);
} }
public class LocalBinder extends Binder {
public RileyLinkOmnipodService getServiceInstance() {
return RileyLinkOmnipodService.this;
}
}
} }

View file

@ -11,11 +11,11 @@ import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalScheduleEntry; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalScheduleEntry;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.RateEntry; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.RateEntry;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class BasalScheduleExtraCommandTest { class BasalScheduleExtraCommandTest {
@Test @Test
void testEncodingFromRateEntries() { void testEncodingFromRateEntries() {
List<RateEntry> rateEntries = RateEntry.createEntries(3.0, Duration.standardHours(24)); List<RateEntry> rateEntries = RateEntry.createEntries(3.0, Duration.standardHours(24));
BasalScheduleExtraCommand basalScheduleExtraCommand = new BasalScheduleExtraCommand( // BasalScheduleExtraCommand basalScheduleExtraCommand = new BasalScheduleExtraCommand( //
false, // false, //
@ -32,7 +32,7 @@ class BasalScheduleExtraCommandTest {
} }
@Test @Test
void testParametersCorrectFromBasalSchedule() { void testParametersCorrectFromBasalSchedule() {
BasalSchedule basalSchedule = new BasalSchedule(Collections.singletonList(new BasalScheduleEntry(0.05, Duration.ZERO))); BasalSchedule basalSchedule = new BasalSchedule(Collections.singletonList(new BasalScheduleEntry(0.05, Duration.ZERO)));
BasalScheduleExtraCommand basalScheduleExtraCommand = new BasalScheduleExtraCommand( // BasalScheduleExtraCommand basalScheduleExtraCommand = new BasalScheduleExtraCommand( //
basalSchedule, // basalSchedule, //
@ -59,7 +59,7 @@ class BasalScheduleExtraCommandTest {
} }
@Test @Test
void testEncodingFromBasalScheduleWithThreeEntries() { void testEncodingFromBasalScheduleWithThreeEntries() {
BasalSchedule schedule = new BasalSchedule(Arrays.asList( // BasalSchedule schedule = new BasalSchedule(Arrays.asList( //
new BasalScheduleEntry(1.05, Duration.ZERO), // new BasalScheduleEntry(1.05, Duration.ZERO), //
new BasalScheduleEntry(0.9, Duration.standardHours(10).plus(Duration.standardMinutes(30))), // new BasalScheduleEntry(0.9, Duration.standardHours(10).plus(Duration.standardMinutes(30))), //
@ -73,7 +73,7 @@ class BasalScheduleExtraCommandTest {
} }
@Test @Test
void testEncodingFromBasalScheduleWithSingleEntry() { void testEncodingFromBasalScheduleWithSingleEntry() {
BasalSchedule basalSchedule = new BasalSchedule(Arrays.asList(new BasalScheduleEntry(1.05, Duration.ZERO))); BasalSchedule basalSchedule = new BasalSchedule(Arrays.asList(new BasalScheduleEntry(1.05, Duration.ZERO)));
BasalScheduleExtraCommand basalScheduleExtraCommand = new BasalScheduleExtraCommand(basalSchedule, BasalScheduleExtraCommand basalScheduleExtraCommand = new BasalScheduleExtraCommand(basalSchedule,
Duration.standardMinutes((0x20 + 1) * 30).minus(Duration.standardSeconds(0x33c0 / 8)), Duration.standardMinutes((0x20 + 1) * 30).minus(Duration.standardSeconds(0x33c0 / 8)),
@ -83,7 +83,7 @@ class BasalScheduleExtraCommandTest {
} }
@Test @Test
void testSegmentMerging() { void testSegmentMerging() {
List<BasalScheduleEntry> entries = Arrays.asList( List<BasalScheduleEntry> entries = Arrays.asList(
new BasalScheduleEntry(0.8, Duration.ZERO), new BasalScheduleEntry(0.8, Duration.ZERO),
new BasalScheduleEntry(0.9, Duration.standardMinutes(180)), // new BasalScheduleEntry(0.9, Duration.standardMinutes(180)), //
@ -109,7 +109,7 @@ class BasalScheduleExtraCommandTest {
} }
@Test @Test
void testEncodingFromBasalScheduleWithThirteenEntries() { void testEncodingFromBasalScheduleWithThirteenEntries() {
List<BasalScheduleEntry> entries = Arrays.asList( List<BasalScheduleEntry> entries = Arrays.asList(
new BasalScheduleEntry(1.30, Duration.ZERO), // new BasalScheduleEntry(1.30, Duration.ZERO), //
new BasalScheduleEntry(0.05, Duration.standardMinutes(30)), // new BasalScheduleEntry(0.05, Duration.standardMinutes(30)), //
@ -136,7 +136,7 @@ class BasalScheduleExtraCommandTest {
} }
@Test @Test
void testBasalScheduleExtraCommandRoundsToNearestSecond() { void testBasalScheduleExtraCommandRoundsToNearestSecond() {
BasalSchedule basalSchedule = new BasalSchedule(Arrays.asList(new BasalScheduleEntry(1.00, Duration.ZERO))); BasalSchedule basalSchedule = new BasalSchedule(Arrays.asList(new BasalScheduleEntry(1.00, Duration.ZERO)));
BasalScheduleExtraCommand basalScheduleExtraCommand = new BasalScheduleExtraCommand(basalSchedule, BasalScheduleExtraCommand basalScheduleExtraCommand = new BasalScheduleExtraCommand(basalSchedule,
@ -164,6 +164,6 @@ class BasalScheduleExtraCommandTest {
} }
private double extractDelayUntilNextPulseInSeconds(byte[] message) { private double extractDelayUntilNextPulseInSeconds(byte[] message) {
return ByteUtil.toInt((int) message[6], (int) message[7], (int) message[8], (int) message[9], ByteUtil.BitConversion.BIG_ENDIAN) / 1_000_000.0; return ByteUtil.INSTANCE.toInt((int) message[6], (int) message[7], (int) message[8], (int) message[9], ByteUtil.BitConversion.BIG_ENDIAN) / 1_000_000.0;
} }
} }

View file

@ -5,7 +5,7 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepConfigType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepConfigType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class BeepConfigCommandTest { class BeepConfigCommandTest {
@Test @Test

View file

@ -4,7 +4,7 @@ import org.joda.time.Duration;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class BolusExtraCommandTest { class BolusExtraCommandTest {
@Test @Test

View file

@ -7,9 +7,11 @@ import java.util.EnumSet;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
/** @noinspection SpellCheckingInspection*/ /**
* @noinspection SpellCheckingInspection
*/
class CancelDeliveryCommandTest { class CancelDeliveryCommandTest {
@Test @Test

View file

@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Be
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepType;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.TimerAlertTrigger; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.TimerAlertTrigger;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.UnitsRemainingAlertTrigger; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.UnitsRemainingAlertTrigger;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class ConfigureAlertsCommandTest { class ConfigureAlertsCommandTest {
@Test @Test

View file

@ -4,7 +4,7 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class GetStatusCommandTest { class GetStatusCommandTest {
@Test @Test

View file

@ -11,7 +11,7 @@ import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalScheduleEntry; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalScheduleEntry;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BolusDeliverySchedule; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BolusDeliverySchedule;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class SetInsulinScheduleCommandTest { class SetInsulinScheduleCommandTest {
@Test @Test

View file

@ -4,7 +4,7 @@ import org.joda.time.DateTime;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class SetupPodCommandTest { class SetupPodCommandTest {
@Test @Test

View file

@ -4,7 +4,7 @@ import org.joda.time.Duration;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class TempBasalExtraCommandTest { class TempBasalExtraCommandTest {
@Test @Test

View file

@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class ErrorResponseTest { class ErrorResponseTest {
@Test @Test

View file

@ -2,14 +2,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communicatio
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import org.joda.time.Duration;
import org.junit.jupiter.api.Test;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import org.joda.time.Duration;
import org.junit.jupiter.api.Test;
class StatusResponseTest { class StatusResponseTest {

View file

@ -4,7 +4,7 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class VersionResponseTest { class VersionResponseTest {
@Test @Test

View file

@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class PodInfoActiveAlertsTest { class PodInfoActiveAlertsTest {
@Test @Test

View file

@ -4,8 +4,9 @@ import static com.google.common.truth.Truth.assertThat;
import org.joda.time.Duration; import org.joda.time.Duration;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class PodInfoDataLogTest { class PodInfoDataLogTest {
@Test @Test

View file

@ -2,13 +2,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communicatio
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import org.joda.time.Duration;
import org.junit.jupiter.api.Test;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ErrorEventInfo; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ErrorEventInfo;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import org.joda.time.Duration;
import org.junit.jupiter.api.Test;
/** /**
* @noinspection SpellCheckingInspection * @noinspection SpellCheckingInspection

View file

@ -2,12 +2,13 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communicatio
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode;
import info.nightscout.pump.core.utils.ByteUtil;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.Duration; import org.joda.time.Duration;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode;
import info.nightscout.pump.common.utils.ByteUtil;
class PodInfoFaultAndInitializationTimeTest { class PodInfoFaultAndInitializationTimeTest {
@Test @Test
void testDecoding() { void testDecoding() {

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communicatio
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
class PodInfoRecentPulseLogTest { class PodInfoRecentPulseLogTest {
@Test @Test

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.podinfo package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.podinfo
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test

View file

@ -1,4 +1,4 @@
package info.nightscout.pump.core.defs package info.nightscout.pump.common.defs
import info.nightscout.pump.common.R import info.nightscout.pump.common.R

View file

@ -0,0 +1,401 @@
package info.nightscout.pump.common.utils
import java.nio.ByteBuffer
import java.util.Locale
import kotlin.math.min
/**
* Created by geoff on 4/28/15.
*/
object ByteUtil {
private val HEX_DIGITS = charArrayOf(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
)
private const val HEX_DIGITS_STR = "0123456789ABCDEF"
/** @noinspection SpellCheckingInspection
*/
fun asUINT8(b: Byte): Int {
return if (b < 0) b + 256 else b.toInt()
}
fun getBytesFromInt16(value: Int): ByteArray {
val array = getBytesFromInt(value)
return byteArrayOf(array[2], array[3])
}
fun getBytesFromInt(value: Int): ByteArray {
return ByteBuffer.allocate(4).putInt(value).array()
}
/* For Reference: static void System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) */
fun concat(a: ByteArray, b: ByteArray?): ByteArray {
if (b == null) {
return a
}
val aLen = a.size
val bLen = b.size
val c = ByteArray(aLen + bLen)
System.arraycopy(a, 0, c, 0, aLen)
System.arraycopy(b, 0, c, aLen, bLen)
return c
}
fun concat(a: ByteArray, b: Byte): ByteArray {
val aLen = a.size
val c = ByteArray(aLen + 1)
System.arraycopy(a, 0, c, 0, aLen)
c[aLen] = b
return c
}
fun substring(a: ByteArray, start: Int, len: Int): ByteArray {
val rVal = ByteArray(len)
System.arraycopy(a, start, rVal, 0, len)
return rVal
}
fun substring(a: List<Byte>, start: Int, len: Int): ByteArray {
val rVal = ByteArray(len)
var i = start
var j = 0
while (i < start + len) {
rVal[j] = a[i]
i++
j++
}
return rVal
}
fun substring(a: ByteArray, start: Int): ByteArray {
val len = a.size - start
val rVal = ByteArray(len)
System.arraycopy(a, start, rVal, 0, len)
return rVal
}
fun shortHexString(ra: ByteArray?): String {
val rVal = StringBuilder()
if (ra == null) {
return rVal.toString()
}
if (ra.isEmpty()) {
return rVal.toString()
}
for (i in ra.indices) {
rVal.append(HEX_DIGITS[ra[i].toInt() and 0xF0 shr 4])
rVal.append(HEX_DIGITS[ra[i].toInt() and 0x0F])
if (i < ra.size - 1) {
rVal.append(" ")
}
}
return rVal.toString()
}
fun shortHexString(list: List<Byte>): String {
val aByte0 = getByteArrayFromList(list)
return shortHexString(aByte0)
}
fun shortHexString(`val`: Byte): String {
return getHexCompact(`val`)
}
fun shortHexStringWithoutSpaces(byteArray: ByteArray?): String {
val hexString = StringBuilder()
if (byteArray == null) {
return hexString.toString()
}
for (b in byteArray) {
hexString.append(HEX_DIGITS[b.toInt() and 0xF0 shr 4])
hexString.append(HEX_DIGITS[b.toInt() and 0x0F])
}
return hexString.toString()
}
fun fromHexString(src: String): ByteArray? {
val s = src.uppercase(Locale.getDefault())
var rVal = byteArrayOf()
if (s.length % 2 != 0) {
// invalid hex string!
return null
}
var i = 0
while (i < s.length) {
val highNibbleOrd = HEX_DIGITS_STR.indexOf(s[i])
if (highNibbleOrd < 0) {
// Not a hex digit.
return null
}
val lowNibbleOrd = HEX_DIGITS_STR.indexOf(s[i + 1])
if (lowNibbleOrd < 0) {
// Not a hex digit
return null
}
rVal = concat(rVal, (highNibbleOrd * 16 + lowNibbleOrd).toByte())
i += 2
}
return rVal
}
fun getListFromByteArray(array: ByteArray): List<Byte> {
val listOut: MutableList<Byte> = ArrayList()
for (`val` in array) {
listOut.add(`val`)
}
return listOut
}
fun getByteArrayFromList(list: List<Byte>): ByteArray {
val out = ByteArray(list.size)
for (i in list.indices) {
out[i] = list[i]
}
return out
}
// compares byte strings like strcmp
fun compare(s1: ByteArray, s2: ByteArray): Int {
val len1 = s1.size
val len2 = s2.size
if (len1 > len2) {
return 1
}
if (len2 > len1) {
return -1
}
var acc = 0
var i = 0
while (i < len1) {
acc += s1[i].toInt()
acc -= s2[i].toInt()
if (acc != 0) {
return acc
}
i++
}
return 0
}
/**
* Converts 4 (or less) ints into int. (Shorts are objects, so you can send null if you have less parameters)
*
* @param b1 short 1
* @param b2 short 2
* @param b3 short 3
* @param b4 short 4
* @param flag Conversion Flag (Big Endian, Little endian)
* @return int value
*/
fun toInt(b1: Int, b2: Int?, b3: Int?, b4: Int?, flag: BitConversion?): Int {
return when (flag) {
BitConversion.LITTLE_ENDIAN -> {
if (b4 != null) {
b4 and 0xff shl 24 or (b3!! and 0xff shl 16) or (b2!! and 0xff shl 8) or (b1 and 0xff)
} else if (b3 != null) {
b3 and 0xff shl 16 or (b2!! and 0xff shl 8) or (b1 and 0xff)
} else if (b2 != null) {
b2 and 0xff shl 8 or (b1 and 0xff)
} else {
b1 and 0xff
}
}
BitConversion.BIG_ENDIAN -> {
if (b4 != null) {
b1 and 0xff shl 24 or (b2!! and 0xff shl 16) or (b3!! and 0xff shl 8) or (b4 and 0xff)
} else if (b3 != null) {
b1 and 0xff shl 16 or (b2!! and 0xff shl 8) or (b3 and 0xff)
} else if (b2 != null) {
b1 and 0xff shl 8 or (b2 and 0xff)
} else {
b1 and 0xff
}
}
else -> {
if (b4 != null) {
b1 and 0xff shl 24 or (b2!! and 0xff shl 16) or (b3!! and 0xff shl 8) or (b4 and 0xff)
} else if (b3 != null) {
b1 and 0xff shl 16 or (b2!! and 0xff shl 8) or (b3 and 0xff)
} else if (b2 != null) {
b1 and 0xff shl 8 or (b2 and 0xff)
} else {
b1 and 0xff
}
}
}
}
/**
* Converts 4 (or less) ints into int. (Shorts are objects, so you can send null if you have less parameters)
*
* @param b1 short 1
* @param b2 short 2
* @param b3 short 3
* @param b4 short 4
* @param flag Conversion Flag (Big Endian, Little endian)
* @return int value
*/
fun toInt(b1: Byte, b2: Byte?, b3: Byte?, b4: Byte?, flag: BitConversion?): Int {
return when (flag) {
BitConversion.LITTLE_ENDIAN -> {
if (b4 != null) {
b4.toInt() and 0xff shl 24 or (b3!!.toInt() and 0xff shl 16) or (b2!!.toInt() and 0xff shl 8) or (b1.toInt() and 0xff)
} else if (b3 != null) {
b3.toInt() and 0xff shl 16 or (b2!!.toInt() and 0xff shl 8) or (b1.toInt() and 0xff)
} else if (b2 != null) {
b2.toInt() and 0xff shl 8 or (b1.toInt() and 0xff)
} else {
b1.toInt() and 0xff
}
}
BitConversion.BIG_ENDIAN -> {
if (b4 != null) {
b1.toInt() and 0xff shl 24 or (b2!!.toInt() and 0xff shl 16) or (b3!!.toInt() and 0xff shl 8) or (b4.toInt() and 0xff)
} else if (b3 != null) {
b1.toInt() and 0xff shl 16 or (b2!!.toInt() and 0xff shl 8) or (b3.toInt() and 0xff)
} else if (b2 != null) {
b1.toInt() and 0xff shl 8 or (b2.toInt() and 0xff)
} else {
b1.toInt() and 0xff
}
}
else -> {
if (b4 != null) {
b1.toInt() and 0xff shl 24 or (b2!!.toInt() and 0xff shl 16) or (b3!!.toInt() and 0xff shl 8) or (b4.toInt() and 0xff)
} else if (b3 != null) {
b1.toInt() and 0xff shl 16 or (b2!!.toInt() and 0xff shl 8) or (b3.toInt() and 0xff)
} else if (b2 != null) {
b1.toInt() and 0xff shl 8 or (b2.toInt() and 0xff)
} else {
b1.toInt() and 0xff
}
}
}
}
fun toInt(b1: Int, b2: Int): Int {
return toInt(b1, b2, null, null, BitConversion.BIG_ENDIAN)
}
fun toInt(b1: Int, b2: Int, flag: BitConversion?): Int {
return toInt(b1, b2, null, null, flag)
}
fun toInt(b1: Byte, b2: Byte): Int {
return toInt(b1, b2, null, null, BitConversion.BIG_ENDIAN)
}
fun toInt(b1: Int, b2: Int, b3: Int): Int {
return toInt(b1, b2, b3, null, BitConversion.BIG_ENDIAN)
}
fun toInt(b1: Byte, b2: Byte, b3: Byte): Int {
return toInt(b1, b2, b3, null, BitConversion.BIG_ENDIAN)
}
fun makeUnsignedShort(i: Int, j: Int): Int {
return i and 0xff shl 8 or (j and 0xff)
}
fun getCorrectHexValue(inp: Byte): String? {
val hx = Integer.toHexString(Char(inp.toUShort()).code)
when (hx.length) {
1 -> return "0$hx"
2 -> return hx
4 -> return hx.substring(2)
else -> {
println("Hex Error: $inp")
}
}
return null
}
fun getHex(aByte0: ByteArray?): String? {
return if (aByte0 != null) getHex(aByte0, aByte0.size) else null
}
fun getHex(aByte0: ByteArray?, i: Int): String {
var index = i
val sb = StringBuilder()
if (aByte0 != null) {
index = min(index, aByte0.size)
for (j in 0 until index) {
sb.append(shortHexString(aByte0[j]))
if (j < index - 1) {
sb.append(" ")
}
}
}
return sb.toString()
}
fun getHex(list: List<Byte>): String {
val aByte0 = getByteArrayFromList(list)
return getHex(aByte0, aByte0.size)
}
fun getHex(byte0: Byte): String {
val s = if (byte0.toInt() != -1) "0x" else ""
return s + getHexCompact(byte0)
}
fun getHexCompact(byte0: Byte): String {
val i = if (byte0.toInt() != -1) convertUnsignedByteToInt(byte0) else byte0.toInt()
return getHexCompact(i)
}
fun convertUnsignedByteToInt(data: Byte): Int {
return data.toInt() and 0xff
}
fun getHexCompact(l: Int): String {
val s = java.lang.Long.toHexString(l.toLong()).uppercase(Locale.getDefault())
val s1 = if (isOdd(s.length)) "0" else ""
return if (l.toLong() != -1L) s1 + s else "-1"
}
fun isEven(i: Int): Boolean {
return i % 2 == 0
}
fun isOdd(i: Int): Boolean {
return !isEven(i)
}
// 00 03 00 05 01 00 C8 00 A0
fun createByteArrayFromString(dataFull: String): ByteArray {
val data = dataFull.replace(" ", "")
return createByteArrayFromCompactString(data, 0, data.length)
}
fun createByteArrayFromHexString(dataFull: String): ByteArray {
var data = dataFull.replace(" 0x", "")
data = data.replace("0x", "")
return createByteArrayFromCompactString(data, 0, data.length)
}
// 000300050100C800A0
fun createByteArrayFromCompactString(dataFull: String, startIndex: Int = 0, length: Int = dataFull.length): ByteArray {
var data = dataFull.substring(startIndex)
data = data.substring(0, length)
val len = data.length
val outArray = ByteArray(len / 2)
var i = 0
while (i < len) {
outArray[i / 2] = ((data[i].digitToInt(16) shl 4) + data[i + 1].digitToInt(16)).toByte()
i += 2
}
return outArray
}
enum class BitConversion {
LITTLE_ENDIAN, // 20 0 0 0 = reverse
BIG_ENDIAN // 0 0 0 20 = normal - java
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.pump.core.utils; package info.nightscout.pump.common.utils;
import org.joda.time.LocalDateTime; import org.joda.time.LocalDateTime;

View file

@ -1,4 +1,4 @@
package info.nightscout.pump.core.utils; package info.nightscout.pump.common.utils;
/** /**
* Created by geoff on 5/27/16. * Created by geoff on 5/27/16.

View file

@ -1,449 +0,0 @@
package info.nightscout.pump.core.utils;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Created by geoff on 4/28/15.
*/
public class ByteUtil {
private final static char[] HEX_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private final static String HEX_DIGITS_STR = "0123456789ABCDEF";
/** @noinspection SpellCheckingInspection*/
public static int asUINT8(byte b) {
return (b < 0) ? b + 256 : b;
}
public static byte[] getBytesFromInt16(int value) {
byte[] array = getBytesFromInt(value);
return new byte[]{array[2], array[3]};
}
public static byte[] getBytesFromInt(int value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
/* For Reference: static void System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) */
public static byte[] concat(byte[] a, byte[] b) {
if (b == null) {
return a;
}
int aLen = a.length;
int bLen = b.length;
byte[] c = new byte[aLen + bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
public static byte[] concat(byte[] a, byte b) {
int aLen = a.length;
byte[] c = new byte[aLen + 1];
System.arraycopy(a, 0, c, 0, aLen);
c[aLen] = b;
return c;
}
public static byte[] concat(byte a, byte[] b) {
int aLen = b.length;
byte[] c = new byte[aLen + 1];
c[0] = a;
System.arraycopy(b, 0, c, 1, aLen);
return c;
}
public static byte[] substring(byte[] a, int start, int len) {
byte[] rVal = new byte[len];
System.arraycopy(a, start, rVal, 0, len);
return rVal;
}
public static byte[] substring(List<Byte> a, int start, int len) {
byte[] rVal = new byte[len];
for (int i = start, j = 0; i < start + len; i++, j++) {
rVal[j] = a.get(i);
}
return rVal;
}
public static byte[] substring(byte[] a, int start) {
int len = a.length - start;
byte[] rVal = new byte[len];
System.arraycopy(a, start, rVal, 0, len);
return rVal;
}
public static String shortHexString(byte[] ra) {
StringBuilder rVal = new StringBuilder();
if (ra == null) {
return rVal.toString();
}
if (ra.length == 0) {
return rVal.toString();
}
for (int i = 0; i < ra.length; i++) {
rVal.append(HEX_DIGITS[(ra[i] & 0xF0) >> 4]);
rVal.append(HEX_DIGITS[(ra[i] & 0x0F)]);
if (i < ra.length - 1) {
rVal.append(" ");
}
}
return rVal.toString();
}
public static String shortHexStringWithoutSpaces(byte[] byteArray) {
StringBuilder hexString = new StringBuilder();
if (byteArray == null) {
return hexString.toString();
}
for (byte b : byteArray) {
hexString.append(HEX_DIGITS[(b & 0xF0) >> 4]);
hexString.append(HEX_DIGITS[(b & 0x0F)]);
}
return hexString.toString();
}
public static String shortHexString(List<Byte> list) {
byte[] aByte0 = getByteArrayFromList(list);
return shortHexString(aByte0);
}
public static String shortHexString(byte val) {
return getHexCompact(val);
}
public static byte[] fromHexString(String src) {
String s = src.toUpperCase();
byte[] rVal = new byte[]{};
if ((s.length() % 2) != 0) {
// invalid hex string!
return null;
}
for (int i = 0; i < s.length(); i += 2) {
int highNibbleOrd = HEX_DIGITS_STR.indexOf(s.charAt(i));
if (highNibbleOrd < 0) {
// Not a hex digit.
return null;
}
int lowNibbleOrd = HEX_DIGITS_STR.indexOf(s.charAt(i + 1));
if (lowNibbleOrd < 0) {
// Not a hex digit
return null;
}
rVal = concat(rVal, (byte) (highNibbleOrd * 16 + lowNibbleOrd));
}
return rVal;
}
public static List<Byte> getListFromByteArray(byte[] array) {
List<Byte> listOut = new ArrayList<>();
for (byte val : array) {
listOut.add(val);
}
return listOut;
}
public static byte[] getByteArrayFromList(List<Byte> list) {
byte[] out = new byte[list.size()];
for (int i = 0; i < list.size(); i++) {
out[i] = list.get(i);
}
return out;
}
// compares byte strings like strcmp
public static int compare(byte[] s1, byte[] s2) {
int i;
int len1 = s1.length;
int len2 = s2.length;
if (len1 > len2) {
return 1;
}
if (len2 > len1) {
return -1;
}
int acc = 0;
for (i = 0; i < len1; i++) {
acc += s1[i];
acc -= s2[i];
if (acc != 0) {
return acc;
}
}
return 0;
}
/**
* Converts 4 (or less) ints into int. (Shorts are objects, so you can send null if you have less parameters)
*
* @param b1 short 1
* @param b2 short 2
* @param b3 short 3
* @param b4 short 4
* @param flag Conversion Flag (Big Endian, Little endian)
* @return int value
*/
public static int toInt(Integer b1, Integer b2, Integer b3, Integer b4, BitConversion flag) {
switch (flag) {
case LITTLE_ENDIAN: {
if (b4 != null) {
return (b4 & 0xff) << 24 | (b3 & 0xff) << 16 | (b2 & 0xff) << 8 | b1 & 0xff;
} else if (b3 != null) {
return (b3 & 0xff) << 16 | (b2 & 0xff) << 8 | b1 & 0xff;
} else if (b2 != null) {
return (b2 & 0xff) << 8 | b1 & 0xff;
} else {
return b1 & 0xff;
}
}
default:
case BIG_ENDIAN: {
if (b4 != null) {
return (b1 & 0xff) << 24 | (b2 & 0xff) << 16 | (b3 & 0xff) << 8 | b4 & 0xff;
} else if (b3 != null) {
return (b1 & 0xff) << 16 | (b2 & 0xff) << 8 | b3 & 0xff;
} else if (b2 != null) {
return (b1 & 0xff) << 8 | b2 & 0xff;
} else {
return b1 & 0xff;
}
}
}
}
/**
* Converts 4 (or less) ints into int. (Shorts are objects, so you can send null if you have less parameters)
*
* @param b1 short 1
* @param b2 short 2
* @param b3 short 3
* @param b4 short 4
* @param flag Conversion Flag (Big Endian, Little endian)
* @return int value
*/
public static int toInt(Byte b1, Byte b2, Byte b3, Byte b4, BitConversion flag) {
switch (flag) {
case LITTLE_ENDIAN: {
if (b4 != null) {
return (b4 & 0xff) << 24 | (b3 & 0xff) << 16 | (b2 & 0xff) << 8 | b1 & 0xff;
} else if (b3 != null) {
return (b3 & 0xff) << 16 | (b2 & 0xff) << 8 | b1 & 0xff;
} else if (b2 != null) {
return (b2 & 0xff) << 8 | b1 & 0xff;
} else {
return b1 & 0xff;
}
}
default:
case BIG_ENDIAN: {
if (b4 != null) {
return (b1 & 0xff) << 24 | (b2 & 0xff) << 16 | (b3 & 0xff) << 8 | b4 & 0xff;
} else if (b3 != null) {
return (b1 & 0xff) << 16 | (b2 & 0xff) << 8 | b3 & 0xff;
} else if (b2 != null) {
return (b1 & 0xff) << 8 | b2 & 0xff;
} else {
return b1 & 0xff;
}
}
}
}
public static int toInt(int b1, int b2) {
return toInt(b1, b2, null, null, BitConversion.BIG_ENDIAN);
}
public static int toInt(Byte b1, Byte b2) {
return toInt(b1, b2, null, null, BitConversion.BIG_ENDIAN);
}
public static int toInt(int b1, int b2, int b3) {
return toInt(b1, b2, b3, null, BitConversion.BIG_ENDIAN);
}
public static int toInt(Byte b1, Byte b2, Byte b3) {
return toInt(b1, b2, b3, null, BitConversion.BIG_ENDIAN);
}
public static int toInt(int b1, int b2, BitConversion flag) {
return toInt(b1, b2, null, null, flag);
}
public static int makeUnsignedShort(int i, int j) {
return (i & 0xff) << 8 | j & 0xff;
}
public static String getCorrectHexValue(byte inp) {
String hx = Integer.toHexString((char) inp);
if (hx.length() == 1)
return "0" + hx;
else if (hx.length() == 2)
return hx;
else if (hx.length() == 4)
return hx.substring(2);
else {
System.out.println("Hex Error: " + inp);
}
return null;
}
public static String getHex(byte[] aByte0) {
return aByte0 != null ? getHex(aByte0, aByte0.length) : null;
}
public static String getString(short[] aByte0) {
StringBuilder sb = new StringBuilder();
for (short i : aByte0) {
sb.append(i);
sb.append(" ");
}
return sb.toString();
}
public static String getHex(List<Byte> list) {
byte[] aByte0 = getByteArrayFromList(list);
return getHex(aByte0, aByte0.length);
}
public static String getHex(byte[] aByte0, int i) {
StringBuilder sb = new StringBuilder();
if (aByte0 != null) {
i = Math.min(i, aByte0.length);
for (int j = 0; j < i; j++) {
sb.append(shortHexString(aByte0[j]));
if (j < i - 1) {
sb.append(" ");
}
}
}
return new String(sb);
}
public static String getHex(byte byte0) {
String s = byte0 != -1 ? "0x" : "";
return s + getHexCompact(byte0);
}
public static String getHexCompact(byte byte0) {
int i = byte0 != -1 ? convertUnsignedByteToInt(byte0) : (int) byte0;
return getHexCompact(i);
}
public static int convertUnsignedByteToInt(byte data) {
return data & 0xff;
}
public static String getHexCompact(int l) {
String s = Long.toHexString(l).toUpperCase();
String s1 = isOdd(s.length()) ? "0" : "";
return l != -1L ? s1 + s : "-1";
}
public static boolean isEven(int i) {
return i % 2 == 0;
}
public static boolean isOdd(int i) {
return !isEven(i);
}
public enum BitConversion {
LITTLE_ENDIAN, // 20 0 0 0 = reverse
BIG_ENDIAN // 0 0 0 20 = normal - java
}
// 000300050100C800A0
public static byte[] createByteArrayFromCompactString(String dataFull) {
return createByteArrayFromCompactString(dataFull, 0, dataFull.length());
}
// 00 03 00 05 01 00 C8 00 A0
public static byte[] createByteArrayFromString(String dataFull) {
String data = dataFull.replace(" ", "");
return createByteArrayFromCompactString(data, 0, data.length());
}
public static byte[] createByteArrayFromHexString(String dataFull) {
String data = dataFull.replace(" 0x", "");
data = data.replace("0x", "");
return createByteArrayFromCompactString(data, 0, data.length());
}
public static byte[] createByteArrayFromCompactString(String dataFull, int startIndex, int length) {
String data = dataFull.substring(startIndex);
data = data.substring(0, length);
int len = data.length();
byte[] outArray = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
outArray[i / 2] = (byte) ((Character.digit(data.charAt(i), 16) << 4) + Character.digit(data.charAt(i + 1),
16));
}
return outArray;
}
}

View file

@ -0,0 +1,166 @@
package info.nightscout.pump.common.utils
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
internal class ByteUtilTest {
@Test fun asUINT8() {
assertThat(ByteUtil.asUINT8(-1)).isEqualTo(255)
}
@Test
fun getBytesFromInt16() {
assertThat(ByteUtil.getBytesFromInt16(0x0102)[0]).isEqualTo(1)
assertThat(ByteUtil.getBytesFromInt16(0x0102)[1]).isEqualTo(2)
assertThat(ByteUtil.getBytesFromInt16(0x0102)).hasLength(2)
}
@Test
fun getBytesFromInt() {
assertThat(ByteUtil.getBytesFromInt(0x01020304)[0]).isEqualTo(1)
assertThat(ByteUtil.getBytesFromInt(0x01020304)[1]).isEqualTo(2)
assertThat(ByteUtil.getBytesFromInt(0x01020304)[2]).isEqualTo(3)
assertThat(ByteUtil.getBytesFromInt(0x01020304)[3]).isEqualTo(4)
assertThat(ByteUtil.getBytesFromInt(0x0102)).hasLength(4)
}
@Test
fun concat() {
assertThat(ByteUtil.concat(byteArrayOf(1), null)).hasLength(1)
assertThat(ByteUtil.concat(byteArrayOf(1), byteArrayOf(2))).hasLength(2)
assertThat(ByteUtil.concat(byteArrayOf(1), byteArrayOf(2))[1]).isEqualTo(2)
assertThat(ByteUtil.concat(byteArrayOf(1), 2.toByte())).hasLength(2)
assertThat(ByteUtil.concat(byteArrayOf(1), 2.toByte())[1]).isEqualTo(2)
}
@Test
fun substring() {
assertThat(ByteUtil.substring(byteArrayOf(0x01, 0x02, 0x03), 1, 2)).hasLength(2)
assertThat(ByteUtil.substring(byteArrayOf(0x01, 0x02, 0x03), 1, 2)[1]).isEqualTo(3)
assertThat(ByteUtil.substring(arrayListOf(0x01.toByte(), 0x02.toByte(), 0x03.toByte()), 1, 2)).hasLength(2)
assertThat(ByteUtil.substring(arrayListOf(0x01.toByte(), 0x02.toByte(), 0x03.toByte()), 1, 2)[1]).isEqualTo(3)
assertThat(ByteUtil.substring(byteArrayOf(0x01, 0x02, 0x03), 1)).hasLength(2)
assertThat(ByteUtil.substring(byteArrayOf(0x01, 0x02, 0x03), 1)[1]).isEqualTo(3)
}
@Test
fun shortHexString() {
assertThat(ByteUtil.shortHexString(null as ByteArray?)).isEqualTo("")
assertThat(ByteUtil.shortHexString(byteArrayOf())).isEqualTo("")
assertThat(ByteUtil.shortHexString(byteArrayOf(0x01, 0x02, 0x03))).isEqualTo("01 02 03")
assertThat(ByteUtil.shortHexString(arrayListOf(0x01.toByte(), 0x02.toByte(), 0x03.toByte()))).isEqualTo("01 02 03")
assertThat(ByteUtil.shortHexString(0x01.toByte())).isEqualTo("01")
}
@Test
fun shortHexStringWithoutSpaces() {
assertThat(ByteUtil.shortHexStringWithoutSpaces(null as ByteArray?)).isEqualTo("")
assertThat(ByteUtil.shortHexStringWithoutSpaces(byteArrayOf())).isEqualTo("")
assertThat(ByteUtil.shortHexStringWithoutSpaces(byteArrayOf(0x01, 0x02, 0x03))).isEqualTo("010203")
}
@Test
fun fromHexString() {
assertThat(ByteUtil.fromHexString("1")).isEqualTo(null)
assertThat(ByteUtil.fromHexString("GA")).isEqualTo(null)
assertThat(ByteUtil.fromHexString("AG")).isEqualTo(null)
assertThat(ByteUtil.fromHexString("0102")?.get(0)).isEqualTo(1)
assertThat(ByteUtil.fromHexString("0102")?.get(1)).isEqualTo(2)
}
@Test
fun getListFromByteArray() {
assertThat(ByteUtil.getListFromByteArray(byteArrayOf(0x01, 0x02, 0x03))).hasSize(3)
}
@Test
fun compare() {
assertThat(ByteUtil.compare(byteArrayOf(0x01, 0x02), byteArrayOf(0x01))).isEqualTo(1)
assertThat(ByteUtil.compare(byteArrayOf(0x01), byteArrayOf(0x01, 0x02))).isEqualTo(-1)
assertThat(ByteUtil.compare(byteArrayOf(0x01, 0x02), byteArrayOf(0x01, 0x02))).isEqualTo(0)
assertThat(ByteUtil.compare(byteArrayOf(0x01, 0x02), byteArrayOf(0x02, 0x01))).isEqualTo(-1)
assertThat(ByteUtil.compare(byteArrayOf(0x02, 0x01), byteArrayOf(0x01, 0x02))).isEqualTo(1)
}
@Suppress("RemoveRedundantCallsOfConversionMethods")
@Test
fun toInt() {
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt(), 0x03.toInt(), 0x04.toInt(), ByteUtil.BitConversion.LITTLE_ENDIAN)).isEqualTo(0x04030201)
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt(), 0x03.toInt(), null, ByteUtil.BitConversion.LITTLE_ENDIAN)).isEqualTo(0x030201)
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt(), null, null, ByteUtil.BitConversion.LITTLE_ENDIAN)).isEqualTo(0x0201)
assertThat(ByteUtil.toInt(0x01.toInt(), null, null, null, ByteUtil.BitConversion.LITTLE_ENDIAN)).isEqualTo(0x01)
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt(), 0x03.toInt(), 0x04.toInt(), ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x01020304)
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt(), 0x03.toInt(), null, ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x010203)
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt(), null, null, ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x0102)
assertThat(ByteUtil.toInt(0x01.toInt(), null, null, null, ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x01)
assertThat(ByteUtil.toInt(0x01.toByte(), 0x02.toByte(), 0x03.toByte(), 0x04.toByte(), ByteUtil.BitConversion.LITTLE_ENDIAN)).isEqualTo(0x04030201)
assertThat(ByteUtil.toInt(0x01.toByte(), 0x02.toByte(), 0x03.toByte(), null, ByteUtil.BitConversion.LITTLE_ENDIAN)).isEqualTo(0x030201)
assertThat(ByteUtil.toInt(0x01.toByte(), 0x02.toByte(), null, null, ByteUtil.BitConversion.LITTLE_ENDIAN)).isEqualTo(0x0201)
assertThat(ByteUtil.toInt(0x01.toByte(), null, null, null, ByteUtil.BitConversion.LITTLE_ENDIAN)).isEqualTo(0x01)
assertThat(ByteUtil.toInt(0x01.toByte(), 0x02.toByte(), 0x03.toByte(), 0x04.toByte(), ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x01020304)
assertThat(ByteUtil.toInt(0x01.toByte(), 0x02.toByte(), 0x03.toByte(), null, ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x010203)
assertThat(ByteUtil.toInt(0x01.toByte(), 0x02.toByte(), null, null, ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x0102)
assertThat(ByteUtil.toInt(0x01.toByte(), null, null, null, ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x01)
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt())).isEqualTo(0x0102)
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt(), ByteUtil.BitConversion.BIG_ENDIAN)).isEqualTo(0x0102)
assertThat(ByteUtil.toInt(0x01.toByte(), 0x02.toByte())).isEqualTo(0x0102)
assertThat(ByteUtil.toInt(0x01.toByte(), 0x02.toByte(), 0x03.toByte())).isEqualTo(0x010203)
assertThat(ByteUtil.toInt(0x01.toInt(), 0x02.toInt(), 0x03.toInt())).isEqualTo(0x010203)
}
@Test
fun makeUnsignedShort() {
assertThat(ByteUtil.makeUnsignedShort(0xF1, 0xF2)).isEqualTo(61938)
}
@Test
fun getCorrectHexValue() {
assertThat(ByteUtil.getCorrectHexValue(0x1.toByte())).isEqualTo("01")
assertThat(ByteUtil.getCorrectHexValue(0xF1.toByte())).isEqualTo("f1")
assertThat(ByteUtil.getCorrectHexValue(0xABF1.toByte())).isEqualTo("f1")
}
@Test
fun getHex() {
assertThat(ByteUtil.getHex(null as ByteArray?)).isEqualTo(null)
assertThat(ByteUtil.getHex(byteArrayOf(0xF1.toByte(), 0xDB.toByte()))).isEqualTo("F1 DB")
assertThat(ByteUtil.getHex(byteArrayOf(0xF1.toByte(), 0xDB.toByte(), 0xAB.toByte()), 2)).isEqualTo("F1 DB")
assertThat(ByteUtil.getHex(arrayListOf(0xF1.toByte(), 0xDB.toByte(), 0xAB.toByte()))).isEqualTo("F1 DB AB")
assertThat(ByteUtil.getHex((-1).toByte())).isEqualTo("-1")
assertThat(ByteUtil.getHex((11).toByte())).isEqualTo("0x0B")
assertThat(ByteUtil.getHex((0xFA).toByte())).isEqualTo("0xFA")
}
@Test
fun createByteArrayFromCompactString() {
assertThat(ByteUtil.createByteArrayFromCompactString("C800A0")[0]).isEqualTo(-56)
assertThat(ByteUtil.createByteArrayFromCompactString("C800A0")[2]).isEqualTo(-96)
}
@Test
fun createByteArrayFromString() {
assertThat(ByteUtil.createByteArrayFromString("C8 00 A0")[0]).isEqualTo(-56)
assertThat(ByteUtil.createByteArrayFromString("C8 00 A0")[2]).isEqualTo(-96)
}
@Test
fun createByteArrayFromHexString() {
assertThat(ByteUtil.createByteArrayFromHexString("0xC800A0")[0]).isEqualTo(-56)
assertThat(ByteUtil.createByteArrayFromHexString("0xC800A0")[2]).isEqualTo(-96)
}
@Test
fun testCreateByteArrayFromCompactString() {
assertThat(ByteUtil.createByteArrayFromCompactString("FFC800A0", 2, 6)[0]).isEqualTo(-56)
assertThat(ByteUtil.createByteArrayFromCompactString("FFC800A0", 2, 6)[2]).isEqualTo(-96)
}
}

View file

@ -4,7 +4,7 @@ import android.content.Context
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice
import info.nightscout.pump.core.defs.PumpDeviceState import info.nightscout.pump.common.defs.PumpDeviceState
import info.nightscout.rx.events.EventStatus import info.nightscout.rx.events.EventStatus
open class EventRileyLinkDeviceStatusChange : EventStatus { open class EventRileyLinkDeviceStatusChange : EventStatus {

View file

@ -21,8 +21,8 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask;
import info.nightscout.interfaces.plugin.ActivePlugin; import info.nightscout.interfaces.plugin.ActivePlugin;
import info.nightscout.interfaces.utils.Round; import info.nightscout.interfaces.utils.Round;
import info.nightscout.pump.core.defs.PumpDeviceState; import info.nightscout.pump.common.defs.PumpDeviceState;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import info.nightscout.rx.logging.AAPSLogger; import info.nightscout.rx.logging.AAPSLogger;
import info.nightscout.rx.logging.LTag; import info.nightscout.rx.logging.LTag;
import info.nightscout.shared.sharedPreferences.SP; import info.nightscout.shared.sharedPreferences.SP;
@ -33,6 +33,8 @@ import info.nightscout.shared.sharedPreferences.SP;
* Created by andy on 5/10/18. * Created by andy on 5/10/18.
*/ */
public abstract class RileyLinkCommunicationManager<T extends RLMessage> { public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
private final int SCAN_TIMEOUT = 1500;
private final int ALLOWED_PUMP_UNREACHABLE = 10 * 60 * 1000; // 10 minutes
@Inject protected AAPSLogger aapsLogger; @Inject protected AAPSLogger aapsLogger;
@Inject protected SP sp; @Inject protected SP sp;
@Inject protected RileyLinkServiceData rileyLinkServiceData; @Inject protected RileyLinkServiceData rileyLinkServiceData;
@ -40,10 +42,6 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
@Inject protected RFSpy rfspy; @Inject protected RFSpy rfspy;
@Inject protected HasAndroidInjector injector; @Inject protected HasAndroidInjector injector;
@Inject protected ActivePlugin activePlugin; @Inject protected ActivePlugin activePlugin;
private final int SCAN_TIMEOUT = 1500;
private final int ALLOWED_PUMP_UNREACHABLE = 10 * 60 * 1000; // 10 minutes
protected int receiverDeviceAwakeForMinutes = 1; // override this in constructor of specific implementation protected int receiverDeviceAwakeForMinutes = 1; // override this in constructor of specific implementation
protected String receiverDeviceID; // String representation of receiver device (ex. Pump (xxxxxx) or Pod (yyyyyy)) protected String receiverDeviceID; // String representation of receiver device (ex. Pump (xxxxxx) or Pod (yyyyyy))
protected long lastGoodReceiverCommunicationTime = 0; protected long lastGoodReceiverCommunicationTime = 0;
@ -74,7 +72,7 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
// internal flag // internal flag
boolean showPumpMessages = true; boolean showPumpMessages = true;
if (showPumpMessages) { if (showPumpMessages) {
aapsLogger.info(LTag.PUMPBTCOMM, "Sent:" + ByteUtil.shortHexString(msg.getTxData())); aapsLogger.info(LTag.PUMPBTCOMM, "Sent:" + ByteUtil.INSTANCE.shortHexString(msg.getTxData()));
} }
RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(injector, msg.getTxData()), RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(injector, msg.getTxData()),
@ -112,7 +110,7 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
} }
if (showPumpMessages) { if (showPumpMessages) {
aapsLogger.info(LTag.PUMPBTCOMM, "Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse(injector).getPayload())); aapsLogger.info(LTag.PUMPBTCOMM, "Received:" + ByteUtil.INSTANCE.shortHexString(rfSpyResponse.getRadioResponse(injector).getPayload()));
} }
return response; return response;
@ -153,7 +151,7 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple
RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 200, RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 200,
(byte) 0, (byte) 0, 25000, (byte) 0); (byte) 0, (byte) 0, 25000, (byte) 0);
aapsLogger.info(LTag.PUMPBTCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); aapsLogger.info(LTag.PUMPBTCOMM, "wakeup: raw response is " + ByteUtil.INSTANCE.shortHexString(resp.getRaw()));
// FIXME wakeUp successful !!!!!!!!!!!!!!!!!! // FIXME wakeUp successful !!!!!!!!!!!!!!!!!!
@ -170,7 +168,7 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
// byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.PowerOn); // byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.PowerOn);
// RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, (byte) // RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, (byte)
// 0, (byte) 0, 15000, (byte) 0); // 0, (byte) 0, 15000, (byte) 0);
// LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); // LOG.info("wakeup: raw response is " + ByteUtil.INSTANCE.shortHexString(resp.getRaw()));
// } else { // } else {
// LOG.trace("Last pump communication was recent, not waking pump."); // LOG.trace("Last pump communication was recent, not waking pump.");
// } // }
@ -247,17 +245,17 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
trial.rssiList.add(rssi); trial.rssiList.add(rssi);
trial.successes++; trial.successes++;
} else { } else {
aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to parse radio response: " + ByteUtil.shortHexString(resp.getRaw())); aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to parse radio response: " + ByteUtil.INSTANCE.shortHexString(resp.getRaw()));
trial.rssiList.add(-99); trial.rssiList.add(-99);
} }
} catch (RileyLinkCommunicationException rle) { } catch (RileyLinkCommunicationException rle) {
aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to decode radio response: " + ByteUtil.INSTANCE.shortHexString(resp.getRaw()));
trial.rssiList.add(-99); trial.rssiList.add(-99);
} }
} else { } else {
aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: raw response is " + ByteUtil.shortHexString(resp.getRaw())); aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: raw response is " + ByteUtil.INSTANCE.shortHexString(resp.getRaw()));
trial.rssiList.add(-99); trial.rssiList.add(-99);
} }
trial.tries++; trial.tries++;
@ -332,11 +330,11 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
return calculateRssi(radioResponse.rssi); return calculateRssi(radioResponse.rssi);
} else { } else {
aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: invalid radio response:" aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: invalid radio response:"
+ ByteUtil.shortHexString(radioResponse.getPayload())); + ByteUtil.INSTANCE.shortHexString(radioResponse.getPayload()));
} }
} catch (RileyLinkCommunicationException e) { } catch (RileyLinkCommunicationException e) {
aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to decode radio response: " + ByteUtil.INSTANCE.shortHexString(resp.getRaw()));
} }
} }

View file

@ -31,9 +31,9 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.Rile
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import info.nightscout.pump.core.utils.StringUtil; import info.nightscout.pump.common.utils.StringUtil;
import info.nightscout.pump.core.utils.ThreadUtil; import info.nightscout.pump.common.utils.ThreadUtil;
import info.nightscout.rx.bus.RxBus; import info.nightscout.rx.bus.RxBus;
import info.nightscout.rx.events.EventRefreshOverview; import info.nightscout.rx.events.EventRefreshOverview;
import info.nightscout.rx.logging.AAPSLogger; import info.nightscout.rx.logging.AAPSLogger;
@ -49,26 +49,23 @@ public class RFSpy {
private static final long DEFAULT_BATTERY_CHECK_INTERVAL_MILLIS = 30 * 60 * 1_000L; // 30 minutes; private static final long DEFAULT_BATTERY_CHECK_INTERVAL_MILLIS = 30 * 60 * 1_000L; // 30 minutes;
private static final long LOW_BATTERY_BATTERY_CHECK_INTERVAL_MILLIS = 10 * 60 * 1_000L; // 10 minutes; private static final long LOW_BATTERY_BATTERY_CHECK_INTERVAL_MILLIS = 10 * 60 * 1_000L; // 10 minutes;
private static final int LOW_BATTERY_PERCENTAGE_THRESHOLD = 20; private static final int LOW_BATTERY_PERCENTAGE_THRESHOLD = 20;
private static final long RILEYLINK_FREQ_XTAL = 24000000;
private static final int EXPECTED_MAX_BLUETOOTH_LATENCY_MS = 7500; // 1500
private final HasAndroidInjector injector;
private final RileyLinkBLE rileyLinkBle;
private final UUID radioServiceUUID = UUID.fromString(GattAttributes.SERVICE_RADIO);
private final UUID radioDataUUID = UUID.fromString(GattAttributes.CHARA_RADIO_DATA);
private final UUID radioVersionUUID = UUID.fromString(GattAttributes.CHARA_RADIO_VERSION);
private final UUID batteryServiceUUID = UUID.fromString(GattAttributes.SERVICE_BATTERY);
private final UUID batteryLevelUUID = UUID.fromString(GattAttributes.CHARA_BATTERY_LEVEL);
public int notConnectedCount = 0;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject ResourceHelper rh; @Inject ResourceHelper rh;
@Inject SP sp; @Inject SP sp;
@Inject RileyLinkServiceData rileyLinkServiceData; @Inject RileyLinkServiceData rileyLinkServiceData;
@Inject RileyLinkUtil rileyLinkUtil; @Inject RileyLinkUtil rileyLinkUtil;
@Inject RxBus rxBus; @Inject RxBus rxBus;
private final HasAndroidInjector injector;
private static final long RILEYLINK_FREQ_XTAL = 24000000;
private static final int EXPECTED_MAX_BLUETOOTH_LATENCY_MS = 7500; // 1500
public int notConnectedCount = 0;
private final RileyLinkBLE rileyLinkBle;
private RFSpyReader reader; private RFSpyReader reader;
private final UUID radioServiceUUID = UUID.fromString(GattAttributes.SERVICE_RADIO);
private final UUID radioDataUUID = UUID.fromString(GattAttributes.CHARA_RADIO_DATA);
private final UUID radioVersionUUID = UUID.fromString(GattAttributes.CHARA_RADIO_VERSION);
private final UUID batteryServiceUUID = UUID.fromString(GattAttributes.SERVICE_BATTERY);
private final UUID batteryLevelUUID = UUID.fromString(GattAttributes.CHARA_BATTERY_LEVEL);
private String bleVersion; // We don't use it so no need of sofisticated logic private String bleVersion; // We don't use it so no need of sofisticated logic
private Double currentFrequencyMHz; private Double currentFrequencyMHz;
private long nextBatteryCheck = 0; private long nextBatteryCheck = 0;
@ -79,6 +76,25 @@ public class RFSpy {
this.rileyLinkBle = rileyLinkBle; this.rileyLinkBle = rileyLinkBle;
} }
static RileyLinkFirmwareVersion getFirmwareVersion(AAPSLogger aapsLogger, String bleVersion, String cc1110Version) {
if (cc1110Version != null) {
RileyLinkFirmwareVersion version = RileyLinkFirmwareVersion.getByVersionString(cc1110Version);
aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version string: %s, resolved to %s.", cc1110Version, version));
if (version != RileyLinkFirmwareVersion.UnknownVersion) {
return version;
}
}
aapsLogger.error(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version can't be determined. Checking with BLE Version [%s].", bleVersion));
if (bleVersion.contains(" 2.")) {
return RileyLinkFirmwareVersion.Version_2_0;
}
return RileyLinkFirmwareVersion.UnknownVersion;
}
@Inject @Inject
public void onInit() { public void onInit() {
//aapsLogger.debug("RileyLinkServiceData:" + rileyLinkServiceData); //aapsLogger.debug("RileyLinkServiceData:" + rileyLinkServiceData);
@ -155,7 +171,7 @@ public class RFSpy {
byte[] getVersionRaw = getByteArray(RileyLinkCommandType.GetVersion.code); byte[] getVersionRaw = getByteArray(RileyLinkCommandType.GetVersion.code);
byte[] response = writeToDataRaw(getVersionRaw, 5000); byte[] response = writeToDataRaw(getVersionRaw, 5000);
aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version. GetVersion [response=%s]", ByteUtil.shortHexString(response))); aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version. GetVersion [response=%s]", ByteUtil.INSTANCE.shortHexString(response)));
if (response != null) { // && response[0] == (byte) 0xDD) { if (response != null) { // && response[0] == (byte) 0xDD) {
@ -173,25 +189,6 @@ public class RFSpy {
return null; return null;
} }
static RileyLinkFirmwareVersion getFirmwareVersion(AAPSLogger aapsLogger, String bleVersion, String cc1110Version) {
if (cc1110Version != null) {
RileyLinkFirmwareVersion version = RileyLinkFirmwareVersion.getByVersionString(cc1110Version);
aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version string: %s, resolved to %s.", cc1110Version, version));
if (version != RileyLinkFirmwareVersion.UnknownVersion) {
return version;
}
}
aapsLogger.error(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version can't be determined. Checking with BLE Version [%s].", bleVersion));
if (bleVersion.contains(" 2.")) {
return RileyLinkFirmwareVersion.Version_2_0;
}
return RileyLinkFirmwareVersion.UnknownVersion;
}
private byte[] writeToDataRaw(byte[] bytes, int responseTimeout_ms) { private byte[] writeToDataRaw(byte[] bytes, int responseTimeout_ms) {
SystemClock.sleep(100); SystemClock.sleep(100);
// FIXME drain read queue? // FIXME drain read queue?
@ -199,14 +196,14 @@ public class RFSpy {
while (junkInBuffer != null) { while (junkInBuffer != null) {
aapsLogger.warn(LTag.PUMPBTCOMM, ThreadUtil.sig() + "writeToData: draining read queue, found this: " aapsLogger.warn(LTag.PUMPBTCOMM, ThreadUtil.sig() + "writeToData: draining read queue, found this: "
+ ByteUtil.shortHexString(junkInBuffer)); + ByteUtil.INSTANCE.shortHexString(junkInBuffer));
junkInBuffer = reader.poll(0); junkInBuffer = reader.poll(0);
} }
// prepend length, and send it. // prepend length, and send it.
byte[] prepended = ByteUtil.concat(new byte[]{(byte) (bytes.length)}, bytes); byte[] prepended = ByteUtil.INSTANCE.concat(new byte[]{(byte) (bytes.length)}, bytes);
aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "writeToData (raw=%s)", ByteUtil.shortHexString(prepended))); aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "writeToData (raw=%s)", ByteUtil.INSTANCE.shortHexString(prepended)));
BLECommOperationResult writeCheck = rileyLinkBle.writeCharacteristicBlocking(radioServiceUUID, radioDataUUID, BLECommOperationResult writeCheck = rileyLinkBle.writeCharacteristicBlocking(radioServiceUUID, radioDataUUID,
prepended); prepended);

View file

@ -4,8 +4,8 @@ import android.os.SystemClock
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.pump.core.utils.ThreadUtil import info.nightscout.pump.common.utils.ThreadUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import java.util.UUID import java.util.UUID

View file

@ -28,8 +28,8 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData
import info.nightscout.interfaces.Config import info.nightscout.interfaces.Config
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.pump.core.utils.ThreadUtil import info.nightscout.pump.common.utils.ThreadUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP
@ -54,6 +54,7 @@ class RileyLinkBLE @Inject constructor(
private val orangeLink: OrangeLinkImpl, private val orangeLink: OrangeLinkImpl,
private val config: Config private val config: Config
) { ) {
private val gattDebugEnabled = true private val gattDebugEnabled = true
private var manualDisconnect = false private var manualDisconnect = false

View file

@ -10,12 +10,10 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Radi
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkCommandType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkCommandType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
public class SendAndListen extends RileyLinkCommand { public class SendAndListen extends RileyLinkCommand {
@Inject RileyLinkServiceData rileyLinkServiceData;
private final byte sendChannel; private final byte sendChannel;
private final byte repeatCount; private final byte repeatCount;
private final int delayBetweenPackets_ms; private final int delayBetweenPackets_ms;
@ -24,14 +22,15 @@ public class SendAndListen extends RileyLinkCommand {
private final byte retryCount; private final byte retryCount;
private final Integer preambleExtension_ms; private final Integer preambleExtension_ms;
private final RadioPacket packetToSend; private final RadioPacket packetToSend;
@Inject RileyLinkServiceData rileyLinkServiceData;
public SendAndListen(HasAndroidInjector injector, byte sendChannel, byte repeatCount, byte delayBetweenPackets_ms, byte listenChannel, public SendAndListen(HasAndroidInjector injector, byte sendChannel, byte repeatCount, byte delayBetweenPackets_ms, byte listenChannel,
int timeout_ms, byte retryCount, RadioPacket packetToSend int timeout_ms, byte retryCount, RadioPacket packetToSend
) { ) {
this(injector, sendChannel, repeatCount, delayBetweenPackets_ms, listenChannel, timeout_ms, retryCount, null, this(injector, sendChannel, repeatCount, delayBetweenPackets_ms, listenChannel, timeout_ms, retryCount, null,
packetToSend); packetToSend);
} }
@ -66,7 +65,7 @@ public class SendAndListen extends RileyLinkCommand {
boolean isPacketV2 = rileyLinkServiceData.firmwareVersion == null || rileyLinkServiceData.firmwareVersion boolean isPacketV2 = rileyLinkServiceData.firmwareVersion == null || rileyLinkServiceData.firmwareVersion
.isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher); .isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher);
ArrayList<Byte> bytes = new ArrayList<Byte>(); ArrayList<Byte> bytes = new ArrayList<>();
bytes.add(this.getCommandType().code); bytes.add(this.getCommandType().code);
bytes.add(this.sendChannel); bytes.add(this.sendChannel);
bytes.add(this.repeatCount); bytes.add(this.repeatCount);
@ -76,7 +75,7 @@ public class SendAndListen extends RileyLinkCommand {
bytes.add(delayBuff[2]); bytes.add(delayBuff[2]);
bytes.add(delayBuff[3]); bytes.add(delayBuff[3]);
} else { } else {
bytes.add((byte)delayBetweenPackets_ms); bytes.add((byte) delayBetweenPackets_ms);
} }
bytes.add(this.listenChannel); bytes.add(this.listenChannel);
@ -96,7 +95,7 @@ public class SendAndListen extends RileyLinkCommand {
bytes.add(preambleBuf[3]); bytes.add(preambleBuf[3]);
} }
return ByteUtil.concat(ByteUtil.getByteArrayFromList(bytes), packetToSend.getEncoded()); return ByteUtil.INSTANCE.concat(ByteUtil.INSTANCE.getByteArrayFromList(bytes), packetToSend.getEncoded());
} }
} }

View file

@ -7,7 +7,7 @@ import javax.inject.Inject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.CRC; import info.nightscout.androidaps.plugins.pump.common.utils.CRC;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
/** /**
* Created by geoff on 5/22/16. * Created by geoff on 5/22/16.
@ -15,9 +15,8 @@ import info.nightscout.pump.core.utils.ByteUtil;
public class RadioPacket { public class RadioPacket {
@Inject RileyLinkUtil rileyLinkUtil;
private final byte[] pkt; private final byte[] pkt;
@Inject RileyLinkUtil rileyLinkUtil;
public RadioPacket(HasAndroidInjector injector, byte[] pkt) { public RadioPacket(HasAndroidInjector injector, byte[] pkt) {
@ -32,8 +31,7 @@ public class RadioPacket {
private byte[] getWithCRC() { private byte[] getWithCRC() {
byte[] withCRC = ByteUtil.concat(pkt, CRC.crc8(pkt)); return ByteUtil.INSTANCE.concat(pkt, CRC.crc8(pkt));
return withCRC;
} }
@ -48,7 +46,7 @@ public class RadioPacket {
byte[] withCRC = getWithCRC(); byte[] withCRC = getWithCRC();
byte[] encoded = rileyLinkUtil.getEncoding4b6b().encode4b6b(withCRC); byte[] encoded = rileyLinkUtil.getEncoding4b6b().encode4b6b(withCRC);
return ByteUtil.concat(encoded, (byte) 0); return ByteUtil.INSTANCE.concat(encoded, (byte) 0);
} }
case FourByteSixByteRileyLink: { case FourByteSixByteRileyLink: {

View file

@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.Rile
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData;
import info.nightscout.androidaps.plugins.pump.common.utils.CRC; import info.nightscout.androidaps.plugins.pump.common.utils.CRC;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import info.nightscout.rx.logging.AAPSLogger; import info.nightscout.rx.logging.AAPSLogger;
import info.nightscout.rx.logging.LTag; import info.nightscout.rx.logging.LTag;
@ -23,12 +23,11 @@ import info.nightscout.rx.logging.LTag;
public class RadioResponse { public class RadioResponse {
public int rssi;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject RileyLinkServiceData rileyLinkServiceData; @Inject RileyLinkServiceData rileyLinkServiceData;
@Inject RileyLinkUtil rileyLinkUtil; @Inject RileyLinkUtil rileyLinkUtil;
private boolean decodedOK = false; private boolean decodedOK = false;
public int rssi;
private int responseNumber; private int responseNumber;
private byte[] decodedPayload = new byte[0]; private byte[] decodedPayload = new byte[0];
private byte receivedCRC; private byte receivedCRC;
@ -75,11 +74,11 @@ public class RadioResponse {
byte[] encodedPayload; byte[] encodedPayload;
if (rileyLinkServiceData.firmwareVersion.isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) { if (rileyLinkServiceData.firmwareVersion.isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) {
encodedPayload = ByteUtil.substring(rxData, 3, rxData.length - 3); encodedPayload = ByteUtil.INSTANCE.substring(rxData, 3, rxData.length - 3);
rssi = rxData[1]; rssi = rxData[1];
responseNumber = rxData[2]; responseNumber = rxData[2];
} else { } else {
encodedPayload = ByteUtil.substring(rxData, 2, rxData.length - 2); encodedPayload = ByteUtil.INSTANCE.substring(rxData, 2, rxData.length - 2);
rssi = rxData[0]; rssi = rxData[0];
responseNumber = rxData[1]; responseNumber = rxData[1];
} }
@ -111,7 +110,7 @@ public class RadioResponse {
if (decodeThis != null && decodeThis.length > 2) { if (decodeThis != null && decodeThis.length > 2) {
decodedOK = true; decodedOK = true;
decodedPayload = ByteUtil.substring(decodeThis, 0, decodeThis.length - 1); decodedPayload = ByteUtil.INSTANCE.substring(decodeThis, 0, decodeThis.length - 1);
receivedCRC = decodeThis[decodeThis.length - 1]; receivedCRC = decodeThis[decodeThis.length - 1];
byte calculatedCRC = CRC.crc8(decodedPayload); byte calculatedCRC = CRC.crc8(decodedPayload);
if (receivedCRC != calculatedCRC) { if (receivedCRC != calculatedCRC) {
@ -130,7 +129,7 @@ public class RadioResponse {
} }
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
decodedOK = false; decodedOK = false;
aapsLogger.error(LTag.PUMPBTCOMM, "Failed to decode radio data: " + ByteUtil.shortHexString(encodedPayload)); aapsLogger.error(LTag.PUMPBTCOMM, "Failed to decode radio data: " + ByteUtil.INSTANCE.shortHexString(encodedPayload));
} }
} }

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.encoding; package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.encoding;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import info.nightscout.rx.logging.AAPSLogger; import info.nightscout.rx.logging.AAPSLogger;
@ -22,12 +22,20 @@ public abstract class Encoding4b6bAbstract implements Encoding4b6b {
// 21, 49, 50, 35, 52, 37, 38, 22, 26, 25, 42, 11, 44, 13, 14, 28 // 21, 49, 50, 35, 52, 37, 38, 22, 26, 25, 42, 11, 44, 13, 14, 28
/* O(n) lookup. Run on an O(n) translation of a byte-stream, gives O(n**2) performance. Sigh. */
public static int encode4b6bListIndex(byte b) {
for (int i = 0; i < encode4b6bList.length; i++) {
if (b == encode4b6bList[i]) {
return i;
}
}
return -1;
}
@Override public abstract byte[] encode4b6b(byte[] data); @Override public abstract byte[] encode4b6b(byte[] data);
@Override public abstract byte[] decode4b6b(byte[] data) throws RileyLinkCommunicationException; @Override public abstract byte[] decode4b6b(byte[] data) throws RileyLinkCommunicationException;
protected short convertUnsigned(byte x) { protected short convertUnsigned(byte x) {
short ss = x; short ss = x;
@ -38,18 +46,6 @@ public abstract class Encoding4b6bAbstract implements Encoding4b6b {
return ss; return ss;
} }
/* O(n) lookup. Run on an O(n) translation of a byte-stream, gives O(n**2) performance. Sigh. */
public static int encode4b6bListIndex(byte b) {
for (int i = 0; i < encode4b6bList.length; i++) {
if (b == encode4b6bList[i]) {
return i;
}
}
return -1;
}
public void writeError(AAPSLogger aapsLogger, byte[] raw, String errorData) { public void writeError(AAPSLogger aapsLogger, byte[] raw, String errorData) {
aapsLogger.error(String.format("\n" + aapsLogger.error(String.format("\n" +
@ -58,7 +54,7 @@ public abstract class Encoding4b6bAbstract implements Encoding4b6b {
" encodedPayload: %s\n" + " encodedPayload: %s\n" +
" errors: %s\n" + " errors: %s\n" +
"=============================================================================", // "=============================================================================", //
ByteUtil.getHex(raw), errorData)); ByteUtil.INSTANCE.getHex(raw), errorData));
//FabricUtil.createEvent("MedtronicDecode4b6bError", null); //FabricUtil.createEvent("MedtronicDecode4b6bError", null);

View file

@ -6,7 +6,7 @@ import java.util.Locale;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
import info.nightscout.rx.logging.AAPSLogger; import info.nightscout.rx.logging.AAPSLogger;
/** /**
@ -26,7 +26,7 @@ public class Encoding4b6bGeoff extends Encoding4b6bAbstract {
// LOG.error("Warning: data is odd number of bytes"); // LOG.error("Warning: data is odd number of bytes");
// } // }
// use arraylists because byte[] is annoying. // use arraylists because byte[] is annoying.
List<Byte> inData = ByteUtil.getListFromByteArray(data); List<Byte> inData = ByteUtil.INSTANCE.getListFromByteArray(data);
List<Byte> outData = new ArrayList<>(); List<Byte> outData = new ArrayList<>();
int acc = 0; int acc = 0;
@ -65,7 +65,7 @@ public class Encoding4b6bGeoff extends Encoding4b6bAbstract {
} }
// convert back to byte[] // convert back to byte[]
byte[] rval = ByteUtil.getByteArrayFromList(outData); byte[] rval = ByteUtil.INSTANCE.getByteArrayFromList(outData);
return rval; return rval;
@ -83,7 +83,7 @@ public class Encoding4b6bGeoff extends Encoding4b6bAbstract {
StringBuilder errorMessageBuilder = new StringBuilder(); StringBuilder errorMessageBuilder = new StringBuilder();
errorMessageBuilder.append("Input data: " + ByteUtil.shortHexString(raw) + "\n"); errorMessageBuilder.append("Input data: " + ByteUtil.INSTANCE.shortHexString(raw) + "\n");
if ((raw.length % 2) != 0) { if ((raw.length % 2) != 0) {
errorMessageBuilder.append("Warn: odd number of bytes.\n"); errorMessageBuilder.append("Warn: odd number of bytes.\n");
@ -94,7 +94,7 @@ public class Encoding4b6bGeoff extends Encoding4b6bAbstract {
int codingErrors = 0; int codingErrors = 0;
int x = 0; int x = 0;
// Log.w(TAG,"decode4b6b: untested code"); // Log.w(TAG,"decode4b6b: untested code");
// Log.w(TAG,String.format("Decoding %d bytes: %s",raw.length,ByteUtil.shortHexString(raw))); // Log.w(TAG,String.format("Decoding %d bytes: %s",raw.length,ByteUtil.INSTANCE.shortHexString(raw)));
for (int i = 0; i < raw.length; i++) { for (int i = 0; i < raw.length; i++) {
int unsignedValue = raw[i]; int unsignedValue = raw[i];
if (unsignedValue < 0) { if (unsignedValue < 0) {
@ -112,14 +112,14 @@ public class Encoding4b6bGeoff extends Encoding4b6bAbstract {
// special case at end of transmission on uneven boundaries: // special case at end of transmission on uneven boundaries:
if ((highIndex >= 0) && (lowIndex >= 0)) { if ((highIndex >= 0) && (lowIndex >= 0)) {
byte decoded = (byte) ((highIndex << 4) + lowIndex); byte decoded = (byte) ((highIndex << 4) + lowIndex);
rval = ByteUtil.concat(rval, decoded); rval = ByteUtil.INSTANCE.concat(rval, decoded);
/* /*
* LOG.debug(String.format( * LOG.debug(String.format(
* "i=%d,x=0x%08X,0x%02X->0x%02X, 0x%02X->0x%02X, result: 0x%02X, %d bits remaining, errors %d, bytes remaining: %s" * "i=%d,x=0x%08X,0x%02X->0x%02X, 0x%02X->0x%02X, result: 0x%02X, %d bits remaining, errors %d, bytes remaining: %s"
* , * ,
* i,x,highcode,highIndex, lowcode, * i,x,highcode,highIndex, lowcode,
* lowIndex,decoded,availableBits,codingErrors,ByteUtil.shortHexString * lowIndex,decoded,availableBits,codingErrors,ByteUtil.INSTANCE.shortHexString
* (ByteUtil.substring(raw,i+1,raw.length-i-1)))); * (ByteUtil.INSTANCE.substring(raw,i+1,raw.length-i-1))));
*/ */
} else { } else {
// LOG.debug(String.format("i=%d,x=%08X, coding error: highcode=0x%02X, lowcode=0x%02X, %d bits remaining",i,x,highcode,lowcode,availableBits)); // LOG.debug(String.format("i=%d,x=%08X, coding error: highcode=0x%02X, lowcode=0x%02X, %d bits remaining",i,x,highcode,lowcode,availableBits));
@ -179,7 +179,7 @@ public class Encoding4b6bGeoff extends Encoding4b6bAbstract {
// int codingErrors = 0; // int codingErrors = 0;
// int x = 0; // int x = 0;
// // Log.w(TAG,"decode4b6b: untested code"); // // Log.w(TAG,"decode4b6b: untested code");
// // Log.w(TAG,String.format("Decoding %d bytes: %s",raw.length,ByteUtil.shortHexString(raw))); // // Log.w(TAG,String.format("Decoding %d bytes: %s",raw.length,ByteUtil.INSTANCE.shortHexString(raw)));
// for (int i = 0; i < raw.length; i++) { // for (int i = 0; i < raw.length; i++) {
// int unsignedValue = raw[i]; // int unsignedValue = raw[i];
// if (unsignedValue < 0) { // if (unsignedValue < 0) {
@ -197,15 +197,15 @@ public class Encoding4b6bGeoff extends Encoding4b6bAbstract {
// // special case at end of transmission on uneven boundaries: // // special case at end of transmission on uneven boundaries:
// if ((highIndex >= 0) && (lowIndex >= 0)) { // if ((highIndex >= 0) && (lowIndex >= 0)) {
// byte decoded = (byte)((highIndex << 4) + lowIndex); // byte decoded = (byte)((highIndex << 4) + lowIndex);
// rval = ByteUtil.concat(rval, decoded); // rval = ByteUtil.INSTANCE.concat(rval, decoded);
// /* // /*
// * LOG.debug(String.format( // * LOG.debug(String.format(
// * // *
// "i=%d,x=0x%08X,0x%02X->0x%02X, 0x%02X->0x%02X, result: 0x%02X, %d bits remaining, errors %d, bytes remaining: %s" // "i=%d,x=0x%08X,0x%02X->0x%02X, 0x%02X->0x%02X, result: 0x%02X, %d bits remaining, errors %d, bytes remaining: %s"
// * , // * ,
// * i,x,highcode,highIndex, lowcode, // * i,x,highcode,highIndex, lowcode,
// * lowIndex,decoded,availableBits,codingErrors,ByteUtil.shortHexString // * lowIndex,decoded,availableBits,codingErrors,ByteUtil.INSTANCE.shortHexString
// * (ByteUtil.substring(raw,i+1,raw.length-i-1)))); // * (ByteUtil.INSTANCE.substring(raw,i+1,raw.length-i-1))));
// */ // */
// } else { // } else {
// // // //

View file

@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLink
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData
import info.nightscout.pump.core.utils.ByteUtil import info.nightscout.pump.common.utils.ByteUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP

View file

@ -5,7 +5,7 @@ import org.joda.time.LocalDateTime;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice;
import info.nightscout.pump.core.defs.PumpDeviceState; import info.nightscout.pump.common.defs.PumpDeviceState;
import info.nightscout.shared.interfaces.ResourceHelper; import info.nightscout.shared.interfaces.ResourceHelper;

View file

@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData
import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.ActivePlugin
import info.nightscout.pump.core.utils.StringUtil import info.nightscout.pump.common.utils.StringUtil
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP

View file

@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileylinkStatusHistoryBinding import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileylinkStatusHistoryBinding
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileylinkStatusHistoryItemBinding import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileylinkStatusHistoryItemBinding
import info.nightscout.pump.core.defs.PumpDeviceState import info.nightscout.pump.common.defs.PumpDeviceState
import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.interfaces.ResourceHelper
import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.DateUtil
import javax.inject.Inject import javax.inject.Inject

View file

@ -15,7 +15,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.Rile
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState
import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.ActivePlugin
import info.nightscout.pump.core.defs.PumpDeviceState import info.nightscout.pump.common.defs.PumpDeviceState
import info.nightscout.rx.bus.RxBus import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag import info.nightscout.rx.logging.LTag
@ -140,7 +140,7 @@ abstract class RileyLinkService : DaggerService() {
fun doTuneUpDevice() { fun doTuneUpDevice() {
rileyLinkServiceData.setServiceState(RileyLinkServiceState.TuneUpDevice) rileyLinkServiceData.setServiceState(RileyLinkServiceState.TuneUpDevice)
setPumpDeviceState(PumpDeviceState.Sleeping) setPumpDeviceState(PumpDeviceState.Sleeping)
val lastGoodFrequency = rileyLinkServiceData.lastGoodFrequency ?: sp.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0) val lastGoodFrequency = rileyLinkServiceData.lastGoodFrequency ?: sp.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0)
val newFrequency = deviceCommunicationManager.tuneForDevice() val newFrequency = deviceCommunicationManager.tuneForDevice()
if (newFrequency != 0.0 && newFrequency != lastGoodFrequency) { if (newFrequency != 0.0 && newFrequency != lastGoodFrequency) {
aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Saving new pump frequency of %.3f MHz", newFrequency)) aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Saving new pump frequency of %.3f MHz", newFrequency))

View file

@ -10,7 +10,7 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.encoding.Encoding4b6bGeoff; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.encoding.Encoding4b6bGeoff;
import info.nightscout.pump.core.utils.ByteUtil; import info.nightscout.pump.common.utils.ByteUtil;
/** /**
* Created by andy on 11/21/18. * Created by andy on 11/21/18.
@ -19,7 +19,11 @@ import info.nightscout.pump.core.utils.ByteUtil;
public class RFToolsParametrizedUTest { public class RFToolsParametrizedUTest {
private static final String TAG = "RFToolsUTest"; private static final String TAG = "RFToolsUTest";
@Parameterized.Parameter
// first data value (0) is default
public/* NOT private */ byte[] decoded;
@Parameterized.Parameter(1)
public/* NOT private */ byte[] encoded;
@Parameterized.Parameters @Parameterized.Parameters
public static Collection<Object[]> data() { public static Collection<Object[]> data() {
@ -52,14 +56,6 @@ public class RFToolsParametrizedUTest {
}); });
} }
@Parameterized.Parameter
// first data value (0) is default
public/* NOT private */ byte[] decoded;
@Parameterized.Parameter(1)
public/* NOT private */ byte[] encoded;
/** /**
* @noinspection JUnit3StyleTestMethodInJUnit4Class, unused * @noinspection JUnit3StyleTestMethodInJUnit4Class, unused
*/ // @Test */ // @Test
@ -94,8 +90,8 @@ public class RFToolsParametrizedUTest {
if (ByteUtil.compare(bs, out) != 0) { if (ByteUtil.compare(bs, out) != 0) {
Log.e( Log.e(
TAG, TAG,
"encode Data failed: expected " + ByteUtil.shortHexString(out) + " but got " "encode Data failed: expected " + ByteUtil.INSTANCE.shortHexString(out) + " but got "
+ ByteUtil.shortHexString(bs)); + ByteUtil.INSTANCE.shortHexString(bs));
Assert.fail(); Assert.fail();
} }
bs = decoder.encode4b6b(new byte[]{(byte) 0xa7, 0x12}); bs = decoder.encode4b6b(new byte[]{(byte) 0xa7, 0x12});
@ -103,8 +99,8 @@ public class RFToolsParametrizedUTest {
if (ByteUtil.compare(bs, out) != 0) { if (ByteUtil.compare(bs, out) != 0) {
Log.e( Log.e(
TAG, TAG,
"encode Data failed: expected " + ByteUtil.shortHexString(out) + " but got " "encode Data failed: expected " + ByteUtil.INSTANCE.shortHexString(out) + " but got "
+ ByteUtil.shortHexString(bs)); + ByteUtil.INSTANCE.shortHexString(bs));
Assert.fail(); Assert.fail();
} }
bs = decoder.encode4b6b(new byte[]{(byte) 0xa7, 0x12, (byte) 0xa7}); bs = decoder.encode4b6b(new byte[]{(byte) 0xa7, 0x12, (byte) 0xa7});
@ -112,8 +108,8 @@ public class RFToolsParametrizedUTest {
if (ByteUtil.compare(bs, out) != 0) { if (ByteUtil.compare(bs, out) != 0) {
Log.e( Log.e(
TAG, TAG,
"encode Data failed: expected " + ByteUtil.shortHexString(out) + " but got " "encode Data failed: expected " + ByteUtil.INSTANCE.shortHexString(out) + " but got "
+ ByteUtil.shortHexString(bs)); + ByteUtil.INSTANCE.shortHexString(bs));
Assert.fail(); Assert.fail();
} }

Some files were not shown because too many files have changed in this diff Show more